repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
isel-leic-cg/1415i-public | OpenGL/05-Gears-JOGL/src/Gears.java | 15577 |
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import com.jogamp.newt.Window;
import com.jogamp.newt.event.KeyAdapter;
import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.KeyListener;
import com.jogamp.newt.event.MouseAdapter;
import com.jogamp.newt.event.MouseEvent;
import com.jogamp.newt.event.MouseListener;
import com.jogamp.newt.event.awt.AWTKeyAdapter;
import com.jogamp.newt.event.awt.AWTMouseAdapter;
import com.jogamp.opengl.util.Animator;
/**
* Gears.java <BR>
* author: Brian Paul (converted to Java by Ron Cemer and Sven Gothel) <P>
*
* This version is equal to Brian Paul's version 1.2 1999/10/21
*/
public class Gears implements GLEventListener {
private float view_rotx = 20.0f, view_roty = 30.0f;
private final float view_rotz = 0.0f;
private int gear1=0, gear2=0, gear3=0;
private float angle = 0.0f;
private final int swapInterval;
private int prevMouseX, prevMouseY;
public static void main(String[] args) {
// set argument 'NotFirstUIActionOnProcess' in the JNLP's application-desc tag for example
// <application-desc main-class="demos.j2d.TextCube"/>
// <argument>NotFirstUIActionOnProcess</argument>
// </application-desc>
// boolean firstUIActionOnProcess = 0==args.length || !args[0].equals("NotFirstUIActionOnProcess") ;
java.awt.Frame frame = new java.awt.Frame("Gear Demo");
frame.setSize(300, 300);
frame.setLayout(new java.awt.BorderLayout());
final Animator animator = new Animator();
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
// Run this on another thread than the AWT event queue to
// make sure the call to Animator.stop() completes before
// exiting
new Thread(new Runnable() {
@Override
public void run() {
animator.stop();
System.exit(0);
}
}).start();
}
});
GLCanvas canvas = new GLCanvas();
animator.add(canvas);
// GLCapabilities caps = new GLCapabilities(GLProfile.getDefault());
// GLCanvas canvas = new GLCanvas(caps);
final Gears gears = new Gears();
canvas.addGLEventListener(gears);
frame.add(canvas, java.awt.BorderLayout.CENTER);
frame.validate();
frame.setVisible(true);
animator.start();
}
public Gears(int swapInterval) {
this.swapInterval = swapInterval;
}
public Gears() {
this.swapInterval = 1;
}
public void setGears(int g1, int g2, int g3) {
gear1 = g1;
gear2 = g2;
gear3 = g3;
}
/**
* @return display list gear1
*/
public int getGear1() { return gear1; }
/**
* @return display list gear2
*/
public int getGear2() { return gear2; }
/**
* @return display list gear3
*/
public int getGear3() { return gear3; }
@Override
public void init(GLAutoDrawable drawable) {
System.err.println("Gears: Init: "+drawable);
// Use debug pipeline
// drawable.setGL(new DebugGL(drawable.getGL()));
GL2 gl = drawable.getGL().getGL2();
System.err.println("Chosen GLCapabilities: " + drawable.getChosenGLCapabilities());
System.err.println("INIT GL IS: " + gl.getClass().getName());
System.err.println("GL_VENDOR: " + gl.glGetString(GL2.GL_VENDOR));
System.err.println("GL_RENDERER: " + gl.glGetString(GL2.GL_RENDERER));
System.err.println("GL_VERSION: " + gl.glGetString(GL2.GL_VERSION));
float pos[] = { 5.0f, 5.0f, 10.0f, 0.0f };
float red[] = { 0.8f, 0.1f, 0.0f, 0.7f };
float green[] = { 0.0f, 0.8f, 0.2f, 0.7f };
float blue[] = { 0.2f, 0.2f, 1.0f, 0.7f };
gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, pos, 0);
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_LIGHT0);
gl.glEnable(GL2.GL_DEPTH_TEST);
/* make the gears */
if(0>=gear1) {
gear1 = gl.glGenLists(1);
gl.glNewList(gear1, GL2.GL_COMPILE);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT_AND_DIFFUSE, red, 0);
gear(gl, 1.0f, 4.0f, 1.0f, 20, 0.7f);
gl.glEndList();
System.err.println("gear1 list created: "+gear1);
} else {
System.err.println("gear1 list reused: "+gear1);
}
if(0>=gear2) {
gear2 = gl.glGenLists(1);
gl.glNewList(gear2, GL2.GL_COMPILE);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT_AND_DIFFUSE, green, 0);
gear(gl, 0.5f, 2.0f, 2.0f, 10, 0.7f);
gl.glEndList();
System.err.println("gear2 list created: "+gear2);
} else {
System.err.println("gear2 list reused: "+gear2);
}
if(0>=gear3) {
gear3 = gl.glGenLists(1);
gl.glNewList(gear3, GL2.GL_COMPILE);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT_AND_DIFFUSE, blue, 0);
gear(gl, 1.3f, 2.0f, 0.5f, 10, 0.7f);
gl.glEndList();
System.err.println("gear3 list created: "+gear3);
} else {
System.err.println("gear3 list reused: "+gear3);
}
gl.glEnable(GL2.GL_NORMALIZE);
// MouseListener gearsMouse = new TraceMouseAdapter(new GearsMouseAdapter());
MouseListener gearsMouse = new GearsMouseAdapter();
KeyListener gearsKeys = new GearsKeyAdapter();
if (drawable instanceof Window) {
Window window = (Window) drawable;
window.addMouseListener(gearsMouse);
window.addKeyListener(gearsKeys);
} else if (GLProfile.isAWTAvailable() && drawable instanceof java.awt.Component) {
java.awt.Component comp = (java.awt.Component) drawable;
new AWTMouseAdapter(gearsMouse, (Window) drawable).addTo(comp);
new AWTKeyAdapter(gearsKeys, (Window) drawable).addTo(comp);
}
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
System.err.println("Gears: Reshape "+x+"/"+y+" "+width+"x"+height);
GL2 gl = drawable.getGL().getGL2();
gl.setSwapInterval(swapInterval);
float h = (float)height / (float)width;
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustum(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -40.0f);
}
@Override
public void dispose(GLAutoDrawable drawable) {
System.err.println("Gears: Dispose");
setGears(0, 0, 0);
}
@Override
public void display(GLAutoDrawable drawable) {
// Turn the gears' teeth
angle += 2.0f;
// Get the GL corresponding to the drawable we are animating
GL2 gl = drawable.getGL().getGL2();
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
// Special handling for the case where the GLJPanel is translucent
// and wants to be composited with other Java 2D content
if (GLProfile.isAWTAvailable() &&
(drawable instanceof javax.media.opengl.awt.GLJPanel) &&
!((javax.media.opengl.awt.GLJPanel) drawable).isOpaque() &&
((javax.media.opengl.awt.GLJPanel) drawable).shouldPreserveColorBufferIfTranslucent()) {
gl.glClear(GL2.GL_DEPTH_BUFFER_BIT);
} else {
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
}
// Rotate the entire assembly of gears based on how the user
// dragged the mouse around
gl.glPushMatrix();
gl.glRotatef(view_rotx, 1.0f, 0.0f, 0.0f);
gl.glRotatef(view_roty, 0.0f, 1.0f, 0.0f);
gl.glRotatef(view_rotz, 0.0f, 0.0f, 1.0f);
// Place the first gear and call its display list
gl.glPushMatrix();
gl.glTranslatef(-3.0f, -2.0f, 0.0f);
gl.glRotatef(angle, 0.0f, 0.0f, 1.0f);
gl.glCallList(gear1);
gl.glPopMatrix();
// Place the second gear and call its display list
gl.glPushMatrix();
gl.glTranslatef(3.1f, -2.0f, 0.0f);
gl.glRotatef(-2.0f * angle - 9.0f, 0.0f, 0.0f, 1.0f);
gl.glCallList(gear2);
gl.glPopMatrix();
// Place the third gear and call its display list
gl.glPushMatrix();
gl.glTranslatef(-3.1f, 4.2f, 0.0f);
gl.glRotatef(-2.0f * angle - 25.0f, 0.0f, 0.0f, 1.0f);
gl.glCallList(gear3);
gl.glPopMatrix();
// Remember that every push needs a pop; this one is paired with
// rotating the entire gear assembly
gl.glPopMatrix();
}
public static void gear(GL2 gl,
float inner_radius,
float outer_radius,
float width,
int teeth,
float tooth_depth)
{
int i;
float r0, r1, r2;
float angle, da;
float u, v, len;
r0 = inner_radius;
r1 = outer_radius - tooth_depth / 2.0f;
r2 = outer_radius + tooth_depth / 2.0f;
da = 2.0f * (float) Math.PI / teeth / 4.0f;
gl.glShadeModel(GL2.GL_FLAT);
gl.glNormal3f(0.0f, 0.0f, 1.0f);
/* draw front face */
gl.glBegin(GL2.GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++)
{
angle = i * 2.0f * (float) Math.PI / teeth;
gl.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), width * 0.5f);
if(i < teeth)
{
gl.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(angle + 3.0f * da), r1 * (float)Math.sin(angle + 3.0f * da), width * 0.5f);
}
}
gl.glEnd();
/* draw front sides of teeth */
gl.glBegin(GL2.GL_QUADS);
for (i = 0; i < teeth; i++)
{
angle = i * 2.0f * (float) Math.PI / teeth;
gl.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), width * 0.5f);
gl.glVertex3f(r2 * (float)Math.cos(angle + da), r2 * (float)Math.sin(angle + da), width * 0.5f);
gl.glVertex3f(r2 * (float)Math.cos(angle + 2.0f * da), r2 * (float)Math.sin(angle + 2.0f * da), width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(angle + 3.0f * da), r1 * (float)Math.sin(angle + 3.0f * da), width * 0.5f);
}
gl.glEnd();
/* draw back face */
gl.glBegin(GL2.GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++)
{
angle = i * 2.0f * (float) Math.PI / teeth;
gl.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), -width * 0.5f);
gl.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), -width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(angle + 3 * da), r1 * (float)Math.sin(angle + 3 * da), -width * 0.5f);
gl.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), -width * 0.5f);
}
gl.glEnd();
/* draw back sides of teeth */
gl.glBegin(GL2.GL_QUADS);
for (i = 0; i < teeth; i++)
{
angle = i * 2.0f * (float) Math.PI / teeth;
gl.glVertex3f(r1 * (float)Math.cos(angle + 3 * da), r1 * (float)Math.sin(angle + 3 * da), -width * 0.5f);
gl.glVertex3f(r2 * (float)Math.cos(angle + 2 * da), r2 * (float)Math.sin(angle + 2 * da), -width * 0.5f);
gl.glVertex3f(r2 * (float)Math.cos(angle + da), r2 * (float)Math.sin(angle + da), -width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), -width * 0.5f);
}
gl.glEnd();
/* draw outward faces of teeth */
gl.glBegin(GL2.GL_QUAD_STRIP);
for (i = 0; i < teeth; i++)
{
angle = i * 2.0f * (float) Math.PI / teeth;
gl.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), -width * 0.5f);
u = r2 * (float)Math.cos(angle + da) - r1 * (float)Math.cos(angle);
v = r2 * (float)Math.sin(angle + da) - r1 * (float)Math.sin(angle);
len = (float)Math.sqrt(u * u + v * v);
u /= len;
v /= len;
gl.glNormal3f(v, -u, 0.0f);
gl.glVertex3f(r2 * (float)Math.cos(angle + da), r2 * (float)Math.sin(angle + da), width * 0.5f);
gl.glVertex3f(r2 * (float)Math.cos(angle + da), r2 * (float)Math.sin(angle + da), -width * 0.5f);
gl.glNormal3f((float)Math.cos(angle), (float)Math.sin(angle), 0.0f);
gl.glVertex3f(r2 * (float)Math.cos(angle + 2 * da), r2 * (float)Math.sin(angle + 2 * da), width * 0.5f);
gl.glVertex3f(r2 * (float)Math.cos(angle + 2 * da), r2 * (float)Math.sin(angle + 2 * da), -width * 0.5f);
u = r1 * (float)Math.cos(angle + 3 * da) - r2 * (float)Math.cos(angle + 2 * da);
v = r1 * (float)Math.sin(angle + 3 * da) - r2 * (float)Math.sin(angle + 2 * da);
gl.glNormal3f(v, -u, 0.0f);
gl.glVertex3f(r1 * (float)Math.cos(angle + 3 * da), r1 * (float)Math.sin(angle + 3 * da), width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(angle + 3 * da), r1 * (float)Math.sin(angle + 3 * da), -width * 0.5f);
gl.glNormal3f((float)Math.cos(angle), (float)Math.sin(angle), 0.0f);
}
gl.glVertex3f(r1 * (float)Math.cos(0), r1 * (float)Math.sin(0), width * 0.5f);
gl.glVertex3f(r1 * (float)Math.cos(0), r1 * (float)Math.sin(0), -width * 0.5f);
gl.glEnd();
gl.glShadeModel(GL2.GL_SMOOTH);
/* draw inside radius cylinder */
gl.glBegin(GL2.GL_QUAD_STRIP);
for (i = 0; i <= teeth; i++)
{
angle = i * 2.0f * (float) Math.PI / teeth;
gl.glNormal3f(-(float)Math.cos(angle), -(float)Math.sin(angle), 0.0f);
gl.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), -width * 0.5f);
gl.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), width * 0.5f);
}
gl.glEnd();
}
class GearsKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
if(KeyEvent.VK_LEFT == kc) {
view_roty -= 1;
} else if(KeyEvent.VK_RIGHT == kc) {
view_roty += 1;
} else if(KeyEvent.VK_UP == kc) {
view_rotx -= 1;
} else if(KeyEvent.VK_DOWN == kc) {
view_rotx += 1;
}
}
}
class GearsMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
prevMouseX = e.getX();
prevMouseY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
final int x = e.getX();
final int y = e.getY();
int width=0, height=0;
Object source = e.getSource();
if(source instanceof Window) {
Window window = (Window) source;
width=window.getWidth();
height=window.getHeight();
} else if(source instanceof GLAutoDrawable) {
GLAutoDrawable glad = (GLAutoDrawable) source;
width=glad.getWidth();
height=glad.getHeight();
} else if (GLProfile.isAWTAvailable() && source instanceof java.awt.Component) {
java.awt.Component comp = (java.awt.Component) source;
width=comp.getWidth();
height=comp.getHeight();
} else {
throw new RuntimeException("Event source neither Window nor Component: "+source);
}
float thetaY = 360.0f * ( (float)(x-prevMouseX)/(float)width);
float thetaX = 360.0f * ( (float)(prevMouseY-y)/(float)height);
prevMouseX = x;
prevMouseY = y;
view_rotx += thetaX;
view_roty += thetaY;
}
}
} | gpl-2.0 |
Pugduddly/enderX | apps/PoC/src/main/java/com/mojang/escape/level/block/ChestBlock.java | 878 | /*
* Decompiled with CFR 0_123.
*/
package com.mojang.escape.level.block;
import com.mojang.escape.Art;
import com.mojang.escape.Sound;
import com.mojang.escape.entities.Item;
import com.mojang.escape.gui.Sprite;
import com.mojang.escape.level.Level;
import com.mojang.escape.level.block.Block;
public class ChestBlock
extends Block {
private boolean open = false;
private Sprite chestSprite;
public ChestBlock() {
this.tex = 1;
this.blocksMotion = true;
this.chestSprite = new Sprite(0.0, 0.0, 0.0, 16, Art.getCol(16776960));
this.addSprite(this.chestSprite);
}
public boolean use(Level level, Item item) {
if (this.open) {
return false;
}
++this.chestSprite.tex;
this.open = true;
level.getLoot(this.id);
Sound.treasure.play();
return true;
}
}
| gpl-2.0 |
gpakorea/java-more-math-and-strings | Tester.java | 659 | /*
* Project: Tester.java
* Description: Tests Circle.java, Dice.java, Polygon.java
* Name: Aaron Snowberger
* Date: Oct 8, 2015
*/
public class Tester {
public static void main( String[] args ) {
Circle c = new Circle();
System.out.println( "Circle Area: " + c.calcArea(3) ); // static method can be calcArea(3);
Dice d = new Dice();
int roll = d.rollDice();
while( roll != 6 ) {
System.out.println( "\nThe dice shows " + roll );
roll = d.rollDice();
}
Polygon p = new Polygon(40);
System.out.println( "\n" + p.sidesToString() );
} // end main method
} // end Tester | gpl-2.0 |
Corvu/dbeaver | plugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/cache/ExasolViewCache.java | 4507 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2016-2016 Karl Griesser (fullref@gmail.com)
* Copyright (C) 2010-2016 Serge Rieder (serge@jkiss.org)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* as published by the Free Software Foundation.
*
* 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 org.jkiss.dbeaver.ext.exasol.model.cache;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.exasol.model.ExasolSchema;
import org.jkiss.dbeaver.ext.exasol.model.ExasolTableColumn;
import org.jkiss.dbeaver.ext.exasol.model.ExasolView;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement;
import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCStructCache;
import java.sql.SQLException;
/**
* Cache for Exasol Views
*
* @author Karl Griesser
*/
public class ExasolViewCache extends JDBCStructCache<ExasolSchema, ExasolView, ExasolTableColumn> {
/* rename columns for compatibility to TableBase Object */
private static final String SQL_VIEWS =
"select * from ("
+ " SELECT "
+ " VIEW_OWNER AS TABLE_OWNER,"
+ " VIEW_NAME AS TABLE_NAME, "
+ " VIEW_COMMENT AS REMARKS,"
+ " 'VIEW' as TABLE_TYPE,"
+ " VIEW_TEXT FROM EXA_ALL_VIEWS "
+ " WHERE VIEW_SCHEMA = ? "
+ " union all "
+ " select "
+ " 'SYS' as TABLE_OWNER, "
+ " object_name as TABLE_NAME, "
+ " object_comment as REMARKS, "
+ " object_type, "
+ " 'N/A for sysobjects' as view_text "
+ " from sys.exa_syscat "
+ " where "
+ " SCHEMA_NAME = ? "
+ " ) "
+ "order by table_name";
private static final String SQL_COLS_VIEW = "SELECT c.*,CAST(NULL AS INTEGER) as key_seq FROM \"$ODBCJDBC\".\"ALL_COLUMNS\" c WHERE c.table_SCHEM = ? AND c.TABLE_name = ? order by ORDINAL_POSITION";
private static final String SQL_COLS_ALL = "SELECT c.*,CAST(NULL AS INTEGER) as key_seq FROM \"$ODBCJDBC\".\"ALL_COLUMNS\" c WHERE c.table_SCHEM = ? order by c.TABLE_name,ORDINAL_POSITION";
public ExasolViewCache() {
super("TABLE_NAME");
}
@Override
protected JDBCStatement prepareObjectsStatement(@NotNull JDBCSession session, @NotNull ExasolSchema exasolSchema) throws SQLException {
final JDBCPreparedStatement dbStat = session.prepareStatement(SQL_VIEWS);
dbStat.setString(1, exasolSchema.getName());
dbStat.setString(2, exasolSchema.getName());
return dbStat;
}
@Override
protected ExasolView fetchObject(@NotNull JDBCSession session, @NotNull ExasolSchema exasolSchema, @NotNull JDBCResultSet dbResult) throws SQLException,
DBException {
return new ExasolView(session.getProgressMonitor(), exasolSchema, dbResult);
}
@Override
protected JDBCStatement prepareChildrenStatement(@NotNull JDBCSession session, @NotNull ExasolSchema exasolSchema, @Nullable ExasolView forView) throws SQLException {
String sql;
if (forView != null) {
sql = SQL_COLS_VIEW;
} else {
sql = SQL_COLS_ALL;
}
JDBCPreparedStatement dbStat = session.prepareStatement(sql);
dbStat.setString(1, exasolSchema.getName());
if (forView != null) {
dbStat.setString(2, forView.getName());
}
return dbStat;
}
@Override
protected ExasolTableColumn fetchChild(@NotNull JDBCSession session, @NotNull ExasolSchema exasolSchema, @NotNull ExasolView exasolView, @NotNull JDBCResultSet dbResult)
throws SQLException, DBException {
return new ExasolTableColumn(session.getProgressMonitor(), exasolView, dbResult);
}
}
| gpl-2.0 |
HotswapProjects/HotswapAgent | plugin/hotswap-agent-cxf-plugin/src/main/java/org/hotswap/agent/plugin/cxf/jaxrs/CxfJAXRSTransformer.java | 5921 | package org.hotswap.agent.plugin.cxf.jaxrs;
import org.hotswap.agent.annotation.OnClassLoadEvent;
import org.hotswap.agent.javassist.CannotCompileException;
import org.hotswap.agent.javassist.ClassPool;
import org.hotswap.agent.javassist.CtClass;
import org.hotswap.agent.javassist.CtConstructor;
import org.hotswap.agent.javassist.CtMethod;
import org.hotswap.agent.javassist.CtNewConstructor;
import org.hotswap.agent.javassist.NotFoundException;
import org.hotswap.agent.logging.AgentLogger;
import org.hotswap.agent.util.PluginManagerInvoker;
/**
* The Class CxfJAXRSTransformer.
*/
public class CxfJAXRSTransformer {
private static AgentLogger LOGGER = AgentLogger.getLogger(CxfJAXRSTransformer.class);
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.utils.ResourceUtils")
public static void patchResourceUtils(CtClass ctClass, ClassPool classPool){
try{
CtMethod createCriMethods[] = ctClass.getDeclaredMethods("createClassResourceInfo");
for (CtMethod method: createCriMethods) {
if (method.getParameterTypes()[0].getName().equals(Class.class.getName())) {
method.insertAfter(
"if($_ != null && !$_.getClass().getName().contains(\"$$\") ) { " +
"ClassLoader $$cl = java.lang.Thread.currentThread().getContextClassLoader();" +
"if ($$cl==null) $$cl = $1.getClassLoader();" +
PluginManagerInvoker.buildInitializePlugin(CxfJAXRSPlugin.class, "$$cl") +
"try {" +
org.hotswap.agent.javassist.runtime.Desc.class.getName() + ".setUseContextClassLoaderLocally();" +
"$_ = " + ClassResourceInfoProxyHelper.class.getName() + ".createProxy($_, $sig, $args);" +
"} finally {"+
org.hotswap.agent.javassist.runtime.Desc.class.getName() + ".resetUseContextClassLoaderLocally();" +
"}" +
"if ($_.getClass().getName().contains(\"$$\")) {" +
PluginManagerInvoker.buildCallPluginMethod("$$cl", CxfJAXRSPlugin.class, "registerClassResourceInfo",
"$_.getServiceClass()", "java.lang.Class", "$_", "java.lang.Object") +
"}" +
"}" +
"return $_;"
);
}
}
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.model.ClassResourceInfo")
public static void patchClassResourceInfo(CtClass ctClass, ClassPool classPool) {
try {
// Add default constructor used in proxy creation
CtConstructor c = CtNewConstructor.make("public " + ctClass.getSimpleName() + "() { super(null); }", ctClass);
ctClass.addConstructor(c);
} catch (CannotCompileException e) {
LOGGER.error("Error patching ClassResourceInfo", e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.cdi.JAXRSCdiResourceExtension")
public static void patchCxfJARSCdiExtension(CtClass ctClass, ClassPool classPool){
try{
CtMethod loadMethod = ctClass.getDeclaredMethod("load");
loadMethod.insertAfter( "{ " +
"ClassLoader $$cl = java.lang.Thread.currentThread().getContextClassLoader();" +
"if ($$cl==null) $$cl = this.bus.getClass().getClassLoader();" +
"Object $$plugin =" + PluginManagerInvoker.buildInitializePlugin(CxfJAXRSPlugin.class, "$$cl") +
HaCdiExtraCxfContext.class.getName() + ".registerExtraContext($$plugin);" +
"}"
);
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.spring.SpringResourceFactory")
public static void patchSpringResourceFactory(CtClass ctClass, ClassPool classPool){
try{
CtMethod loadMethod = ctClass.getDeclaredMethod("getInstance");
loadMethod.insertBefore( "{ " +
"if(isSingleton() && this.singletonInstance==null){ " +
"try{" +
"this.singletonInstance=ac.getBean(beanId);" +
"}catch (Exception ex) {}" +
"}" +
"}"
);
ctClass.addMethod(CtMethod.make(
"public void clearSingletonInstance() { this.singletonInstance=null; }", ctClass));
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
}
@OnClassLoadEvent(classNameRegexp = "org.apache.cxf.jaxrs.provider.AbstractJAXBProvider")
public static void patchAbstractJAXBProvider(CtClass ctClass, ClassPool classPool){
try{
CtMethod loadMethod = ctClass.getDeclaredMethod("init");
loadMethod.insertAfter( "{ " +
"ClassLoader $$cl = java.lang.Thread.currentThread().getContextClassLoader();" +
"if ($$cl==null) $$cl = getClass().getClassLoader();" +
PluginManagerInvoker.buildInitializePlugin(CxfJAXRSPlugin.class, "$$cl") +
PluginManagerInvoker.buildCallPluginMethod("$$cl", CxfJAXRSPlugin.class, "registerJAXBProvider",
"this", "java.lang.Object") +
"}"
);
} catch(NotFoundException | CannotCompileException e){
LOGGER.error("Error patching ResourceUtils", e);
}
}
}
| gpl-2.0 |
draknyte1/MiscUtils | src/Java/binnie/core/machines/RendererMachine.java | 2351 | package binnie.core.machines;
import binnie.Binnie;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class RendererMachine
extends TileEntitySpecialRenderer
implements ISimpleBlockRenderingHandler
{
RenderBlocks blockRenderer;
public void renderTileEntityAt(TileEntity entity, double x, double y, double z, float var8)
{
renderTileEntity((TileEntityMachine)entity, x, y, z, var8, this.blockRenderer);
}
public void renderTileEntity(TileEntityMachine entity, double x, double y, double z, float var8, RenderBlocks renderer)
{
if ((entity != null) && (entity.getMachine() != null))
{
MachinePackage machinePackage = entity.getMachine().getPackage();
machinePackage.renderMachine(entity.getMachine(), x, y, z, var8, renderer);
}
}
public void renderInvBlock(RenderBlocks renderblocks, Block block, int i, int j)
{
TileEntity entity = block.createTileEntity((World)null, i);
renderTileEntity((TileEntityMachine)entity, 0.0D, -0.1D, 0.0D, 0.0625F, renderblocks);
}
public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer)
{
if (modelID == Binnie.Machine.getMachineRenderID()) {
renderInvBlock(renderer, block, metadata, modelID);
}
}
public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
TileEntityMachine tile = (TileEntityMachine)world.getTileEntity(x, y, z);
if ((tile != null) && (tile.getMachine() != null) && (tile.getMachine().getPackage() != null) && (tile.getMachine().getPackage().getGroup() != null) && (!tile.getMachine().getPackage().getGroup().customRenderer)) {
renderTileEntity(tile, x, y, z, 1.0F, renderer);
}
return true;
}
public boolean shouldRender3DInInventory(int i)
{
return true;
}
public int getRenderId()
{
return Binnie.Machine.getMachineRenderID();
}
public void func_147496_a(World par1World)
{
this.blockRenderer = new RenderBlocks(par1World);
}
}
| gpl-2.0 |
781852423/ExamStack | scoreMarker/src/main/java/com/examstack/scoremarker/config/ScoreMarkConfig.java | 3254 | package com.examstack.scoremarker.config;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.client.RestTemplate;
import com.examstack.common.Constants;
import com.examstack.common.domain.exam.ExamPaper;
import com.examstack.scoremarker.ScoreMarkerMain;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
/**
*
* @author Ocelot
*
*/
@Configuration
@ComponentScan("com.examstack.scoremarker")
public class ScoreMarkConfig {
private static final Logger LOGGER = Logger.getLogger(ScoreMarkerMain.class);
@Value("${rabbitmq.host}")
private String messageQueueHostname;
@Value("${examstack.answersheet.posturi}")
private String answerSheetPostUri;
@Value("${examstack.exampaper.geturi}")
private String examPaperGetUri;
// private HashMap<String,ExamPaper> examPapersMap = new HashMap<String,ExamPaper>();;
@Bean
QueueingConsumer queueingConsumer() throws IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(messageQueueHostname);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(Constants.ANSWERSHEET_DATA_QUEUE, true, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(Constants.ANSWERSHEET_DATA_QUEUE, true, consumer);
return consumer;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
String propertyFilePath = Constants.CONFIG_PATH + File.separator + "config" + File.separator + "scoremaker.properties";
File f = new File(propertyFilePath);
if (!f.exists()){
propertyFilePath = "config" + File.separator + "scoremaker.properties";
}
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
org.springframework.core.io.Resource[] properties = new FileSystemResource[] { new FileSystemResource(propertyFilePath) };
propertySourcesPlaceholderConfigurer.setLocations(properties);
return propertySourcesPlaceholderConfigurer;
}
@Bean
ObjectMapper objectMapper()
{
return new ObjectMapper();
}
@Bean
HashMap<String, ExamPaper> examPapersMap()
{
return new HashMap<String, ExamPaper>();
}
@Bean
String answerSheetPostUri()
{
return answerSheetPostUri;
}
@Bean
String examPaperGetUri()
{
return examPaperGetUri;
}
@Bean
RestTemplate restTemplate()
{
return new RestTemplate();
}
}
| gpl-2.0 |
gabuzomeu/geoPingProject | geoPing/src/main/java/eu/ttbox/geoping/ui/core/validator/validate/OrTwoRequiredValidate.java | 1810 | package eu.ttbox.geoping.ui.core.validator.validate;
import android.content.Context;
import android.widget.TextView;
import eu.ttbox.geoping.ui.core.validator.ValidateField;
import eu.ttbox.geoping.ui.core.validator.Validator;
import eu.ttbox.geoping.ui.core.validator.validator.NotEmptyValidator;
/**
* Validator class to validate if the fields are empty fields of 2 or not. If
* one of them is null, no error. If both are nulls: Error
*
* @author throrin19
*/
public class OrTwoRequiredValidate implements ValidateField {
private TextView mField1;
private TextView mField2;
private Context mContext;
private TextView source;
private String mErrorMessage;
public OrTwoRequiredValidate(TextView field1, TextView field2) {
this.mField1 = field1;
this.mField2 = field2;
source = mField1;
mContext = field1.getContext();
}
@Override
public boolean isValid(CharSequence value) {
ValidateTextView field1Validator = new ValidateTextView(mField1) //
.addValidator(new NotEmptyValidator());
ValidateTextView field2Validator = new ValidateTextView(mField2) //
.addValidator(new NotEmptyValidator());
if (field1Validator.isValid(mField1.getText()) || field2Validator.isValid(mField2.getText())) {
return true;
} else {
mErrorMessage = field1Validator.getMessages();
return false;
}
}
@Override
public String getMessages() {
return mErrorMessage;
}
@Override
public OrTwoRequiredValidate addValidator(Validator validator) {
return this;
}
@Override
public TextView getSource() {
return source;
}
}
| gpl-2.0 |
meijmOrg/Repo-test | freelance-hr-component/src/java/com/yh/hr/component/unit/service/UtOrganizationComService.java | 1418 | package com.yh.hr.component.unit.service;
import com.yh.hr.res.unit.dto.UtOrgDTO;
import com.yh.hr.res.unit.dto.UtUnitDTO;
import com.yh.platform.core.exception.ServiceException;
public interface UtOrganizationComService {
/**
* 同步创建机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseCreateUnitInfo(UtUnitDTO utUnitDTO) throws ServiceException;
/**
* 同步更新机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseUpdateUnitInfo(UtUnitDTO utUnitDTO) throws ServiceException;
/**
* 同步创建内设机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseCreateOrgInfo(UtOrgDTO utOrgDTO) throws ServiceException;
/**
* 同步更新内设机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseUpdateOrgInfo(UtOrgDTO utOrgDTO) throws ServiceException;
/**
* 同步删除内设机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseDeleteOrgInfo(Long orgOid) throws ServiceException;
/**
* 查找单位主管单位
* @param unitOid
* @return UtUnitDTO
* @throws ServiceException
*/
public UtUnitDTO getAdminUnit(Long unitOid) throws ServiceException;
}
| gpl-2.0 |
consulo/jdi | lib/src/main/java/consulo/internal/com/sun/jdi/VMOutOfMemoryException.java | 1689 | /*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package consulo.internal.com.sun.jdi;
/**
* Thrown to indicate that the requested operation cannot be
* completed because the target VM has run out of memory.
*
* @author Gordon Hirsch
* @since 1.3
*/
public class VMOutOfMemoryException extends RuntimeException {
private static final long serialVersionUID = 71504228548910686L;
public VMOutOfMemoryException() {
super();
}
public VMOutOfMemoryException(String s) {
super(s);
}
}
| gpl-2.0 |
ZooMMX/Omoikane | test/src/omoikane/producto/compras/ComprasProductoTest.java | 2073 | package omoikane.producto.compras;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import javafx.application.Application;
import omoikane.principal.Principal;
import omoikane.producto.DummyJFXApp;
import omoikane.repository.ProductoRepo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* User: octavioruizcastillo
* Date: 16/02/13
* Time: 11:40
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-test.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
//@DatabaseSetup("../repository/sampleDataLight.xml")
public class ComprasProductoTest {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ComprasProductoTest.class);
@Autowired
ProductoRepo productoRepo;
@Test
public void ListaDePreciosProductoViewTest() {
Principal.applicationContext = new ClassPathXmlApplicationContext("applicationContext-test.xml");
HashMap testProperties = (HashMap) Principal.applicationContext.getBean( "properties" );
testProperties.put("DummyJFXApp.viewBeanToTest", "comprasProductoView");
Application.launch(DummyJFXApp.class);
}
}
| gpl-2.0 |
isaacl/openjdk-jdk | src/share/classes/javax/print/DocFlavor.java | 56612 | /*
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* Class <code>DocFlavor</code> encapsulates an object that specifies the
* format in which print data is supplied to a {@link DocPrintJob}.
* "Doc" is a short, easy-to-pronounce term that means "a piece of print data."
* The print data format, or "doc flavor", consists of two things:
* <UL>
* <LI>
* <B>MIME type.</B> This is a Multipurpose Internet Mail Extensions (MIME)
* media type (as defined in <A HREF="http://www.ietf.org/rfc/rfc2045.txt">RFC
* 2045</A> and <A HREF="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</A>)
* that specifies how the print data is to be interpreted.
* The charset of text data should be the IANA MIME-preferred name, or its
* canonical name if no preferred name is specified. Additionally a few
* historical names supported by earlier versions of the Java platform may
* be recognized.
* See <a href="../../java/lang/package-summary.html#charenc">
* character encodings</a> for more information on the character encodings
* supported on the Java platform.
*
* <LI>
* <B>Representation class name.</B> This specifies the fully-qualified name of
* the class of the object from which the actual print data comes, as returned
* by the {@link java.lang.Class#getName() Class.getName()} method.
* (Thus the class name for <CODE>byte[]</CODE> is <CODE>"[B"</CODE>, for
* <CODE>char[]</CODE> it is <CODE>"[C"</CODE>.)
* </UL>
* <P>
* A <code>DocPrintJob</code> obtains its print data by means of interface
* {@link Doc Doc}. A <code>Doc</code> object lets the <code>DocPrintJob</code>
* determine the doc flavor the client can supply. A <code>Doc</code> object
* also lets the <code>DocPrintJob</code> obtain an instance of the doc flavor's
* representation class, from which the <code>DocPrintJob</code> then obtains
* the actual print data.
*
* <HR>
* <H3>Client Formatted Print Data</H3>
* There are two broad categories of print data, client formatted print data
* and service formatted print data.
* <P>
* For <B>client formatted print data</B>, the client determines or knows the
* print data format.
* For example the client may have a JPEG encoded image, a URL for
* HTML code, or a disk file containing plain text in some encoding,
* possibly obtained from an external source, and
* requires a way to describe the data format to the print service.
* <p>
* The doc flavor's representation class is a conduit for the JPS
* <code>DocPrintJob</code> to obtain a sequence of characters or
* bytes from the client. The
* doc flavor's MIME type is one of the standard media types telling how to
* interpret the sequence of characters or bytes. For a list of standard media
* types, see the Internet Assigned Numbers Authority's (IANA's) <A
* HREF="http://www.iana.org/assignments/media-types/">Media Types
* Directory</A>. Interface {@link Doc Doc} provides two utility operations,
* {@link Doc#getReaderForText() getReaderForText} and
* {@link Doc#getStreamForBytes() getStreamForBytes()}, to help a
* <code>Doc</code> object's client extract client formatted print data.
* <P>
* For client formatted print data, the print data representation class is
* typically one of the following (although other representation classes are
* permitted):
* <UL>
* <LI>
* Character array (<CODE>char[]</CODE>) -- The print data consists of the
* Unicode characters in the array.
*
* <LI>
* <code>String</code> --
* The print data consists of the Unicode characters in the string.
*
* <LI>
* Character stream ({@link java.io.Reader java.io.Reader})
* -- The print data consists of the Unicode characters read from the stream
* up to the end-of-stream.
*
* <LI>
* Byte array (<CODE>byte[]</CODE>) -- The print data consists of the bytes in
* the array. The bytes are encoded in the character set specified by the doc
* flavor's MIME type. If the MIME type does not specify a character set, the
* default character set is US-ASCII.
*
* <LI>
* Byte stream ({@link java.io.InputStream java.io.InputStream}) --
* The print data consists of the bytes read from the stream up to the
* end-of-stream. The bytes are encoded in the character set specified by the
* doc flavor's MIME type. If the MIME type does not specify a character set,
* the default character set is US-ASCII.
* <LI>
* Uniform Resource Locator ({@link java.net.URL URL})
* -- The print data consists of the bytes read from the URL location.
* The bytes are encoded in the character set specified by the doc flavor's
* MIME type. If the MIME type does not specify a character set, the default
* character set is US-ASCII.
* <P>
* When the representation class is a URL, the print service itself accesses
* and downloads the document directly from its URL address, without involving
* the client. The service may be some form of network print service which
* is executing in a different environment.
* This means you should not use a URL print data flavor to print a
* document at a restricted URL that the client can see but the printer cannot
* see. This also means you should not use a URL print data flavor to print a
* document stored in a local file that is not available at a URL
* accessible independently of the client.
* For example, a file that is not served up by an HTTP server or FTP server.
* To print such documents, let the client open an input stream on the URL
* or file and use an input stream data flavor.
* </UL>
*
* <HR>
* <h3>Default and Platform Encodings</h3>
* <P>
* For byte print data where the doc flavor's MIME type does not include a
* <CODE>charset</CODE> parameter, the Java Print Service instance assumes the
* US-ASCII character set by default. This is in accordance with
* <A HREF="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</A>, which says the
* default character set is US-ASCII. Note that US-ASCII is a subset of
* UTF-8, so in the future this may be widened if a future RFC endorses
* UTF-8 as the default in a compatible manner.
* <p>
* Also note that this is different than the behaviour of the Java runtime
* when interpreting a stream of bytes as text data. That assumes the
* default encoding for the user's locale. Thus, when spooling a file in local
* encoding to a Java Print Service it is important to correctly specify
* the encoding. Developers working in the English locales should
* be particularly conscious of this, as their platform encoding corresponds
* to the default mime charset. By this coincidence that particular
* case may work without specifying the encoding of platform data.
* <p>
* Every instance of the Java virtual machine has a default character encoding
* determined during virtual-machine startup and typically depends upon the
* locale and charset being used by the underlying operating system.
* In a distributed environment there is no guarantee that two VM share
* the same default encoding. Thus clients which want to stream platform
* encoded text data from the host platform to a Java Print Service instance
* must explicitly declare the charset and not rely on defaults.
* <p>
* The preferred form is the official IANA primary name for an encoding.
* Applications which stream text data should always specify the charset
* in the mime type, which necessitates obtaining the encoding of the host
* platform for data (eg files) stored in that platform's encoding.
* A CharSet which corresponds to this and is suitable for use in a
* mime-type for a DocFlavor can be obtained
* from {@link DocFlavor#hostEncoding DocFlavor.hostEncoding}
* This may not always be the primary IANA name but is guaranteed to be
* understood by this VM.
* For common flavors, the pre-defined *HOST DocFlavors may be used.
* <p>
* See <a href="../../java/lang/package-summary.html#charenc">
* character encodings</a> for more information on the character encodings
* supported on the Java platform.
* <HR>
* <h3>Recommended DocFlavors</h3>
* <P>
* The Java Print Service API does not define any mandatorily supported
* DocFlavors.
* However, here are some examples of MIME types that a Java Print Service
* instance might support for client formatted print data.
* Nested classes inside class DocFlavor declare predefined static
* constant DocFlavor objects for these example doc flavors; class DocFlavor's
* constructor can be used to create an arbitrary doc flavor.
* <UL>
* <LI>Preformatted text
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
* <TR>
* <TD><CODE>"text/plain"</CODE></TD>
* <TD>Plain text in the default character set (US-ASCII)</TD>
* </TR>
* <TR>
* <TD><CODE>"text/plain; charset=<I>xxx</I>"</CODE></TD>
* <TD>Plain text in character set <I>xxx</I></TD>
* </TR>
* <TR>
* <TD><CODE>"text/html"</CODE></TD>
* <TD>HyperText Markup Language in the default character set (US-ASCII)</TD>
* </TR>
* <TR>
* <TD><CODE>"text/html; charset=<I>xxx</I>"</CODE></TD>
* <TD>HyperText Markup Language in character set <I>xxx</I></TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted text print data is provided either in a character
* oriented representation class (character array, String, Reader) or in a
* byte oriented representation class (byte array, InputStream, URL).
*
* <LI>Preformatted page description language (PDL) documents
*
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*<TR>
* <TD><CODE>"application/pdf"</CODE></TD>
* <TD>Portable Document Format document</TD>
* </TR>
* <TR>
* <TD><CODE>"application/postscript"</CODE></TD>
* <TD>PostScript document</TD>
* </TR>
* <TR>
* <TD><CODE>"application/vnd.hp-PCL"</CODE></TD>
* <TD>Printer Control Language document</TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted PDL print data is provided in a byte oriented
* representation class (byte array, InputStream, URL).
*
* <LI>Preformatted images
*
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*
* <TR>
* <TD><CODE>"image/gif"</CODE></TD>
* <TD>Graphics Interchange Format image</TD>
* </TR>
* <TR>
* <TD><CODE>"image/jpeg"</CODE></TD>
* <TD>Joint Photographic Experts Group image</TD>
* </TR>
* <TR>
* <TD><CODE>"image/png"</CODE></TD>
* <TD>Portable Network Graphics image</TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted image print data is provided in a byte oriented
* representation class (byte array, InputStream, URL).
*
* <LI>Preformatted autosense print data
*
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*
* <TR>
* <TD><CODE>"application/octet-stream"</CODE></TD>
* <TD>The print data format is unspecified (just an octet stream)</TD>
* </TABLE>
* <P>
* The printer decides how to interpret the print data; the way this
* "autosensing" works is implementation dependent. In general, preformatted
* autosense print data is provided in a byte oriented representation class
* (byte array, InputStream, URL).
* </UL>
*
* <HR>
* <H3>Service Formatted Print Data</H3>
* <P>
* For <B>service formatted print data</B>, the Java Print Service instance
* determines the print data format. The doc flavor's representation class
* denotes an interface whose methods the <code>DocPrintJob</code> invokes to
* determine the content to be printed -- such as a renderable image
* interface or a Java printable interface.
* The doc flavor's MIME type is the special value
* <CODE>"application/x-java-jvm-local-objectref"</CODE> indicating the client
* will supply a reference to a Java object that implements the interface
* named as the representation class.
* This MIME type is just a placeholder; what's
* important is the print data representation class.
* <P>
* For service formatted print data, the print data representation class is
* typically one of the following (although other representation classes are
* permitted). Nested classes inside class DocFlavor declare predefined static
* constant DocFlavor objects for these example doc flavors; class DocFlavor's
* constructor can be used to create an arbitrary doc flavor.
* <UL>
* <LI>
* Renderable image object -- The client supplies an object that implements
* interface
* {@link java.awt.image.renderable.RenderableImage RenderableImage}. The
* printer calls methods
* in that interface to obtain the image to be printed.
*
* <LI>
* Printable object -- The client supplies an object that implements interface
* {@link java.awt.print.Printable Printable}.
* The printer calls methods in that interface to obtain the pages to be
* printed, one by one.
* For each page, the printer supplies a graphics context, and whatever the
* client draws in that graphics context gets printed.
*
* <LI>
* Pageable object -- The client supplies an object that implements interface
* {@link java.awt.print.Pageable Pageable}. The printer calls
* methods in that interface to obtain the pages to be printed, one by one.
* For each page, the printer supplies a graphics context, and whatever
* the client draws in that graphics context gets printed.
* </UL>
*
* <HR>
*
* <HR>
* <H3>Pre-defined Doc Flavors</H3>
* A Java Print Service instance is not <B><I>required</I></B> to support the
* following print data formats and print data representation classes. In
* fact, a developer using this class should <b>never</b> assume that a
* particular print service supports the document types corresponding to
* these pre-defined doc flavors. Always query the print service
* to determine what doc flavors it supports. However,
* developers who have print services that support these doc flavors are
* encouraged to refer to the predefined singleton instances created here.
* <UL>
* <LI>
* Plain text print data provided through a byte stream. Specifically, the
* following doc flavors are recommended to be supported:
* <BR>·
* <CODE>("text/plain", "java.io.InputStream")</CODE>
* <BR>·
* <CODE>("text/plain; charset=us-ascii", "java.io.InputStream")</CODE>
* <BR>·
* <CODE>("text/plain; charset=utf-8", "java.io.InputStream")</CODE>
*
* <LI>
* Renderable image objects. Specifically, the following doc flavor is
* recommended to be supported:
* <BR>·
* <CODE>("application/x-java-jvm-local-objectref", "java.awt.image.renderable.RenderableImage")</CODE>
* </UL>
* <P>
* A Java Print Service instance is allowed to support any other doc flavors
* (or none) in addition to the above mandatory ones, at the implementation's
* choice.
* <P>
* Support for the above doc flavors is desirable so a printing client can rely
* on being able to print on any JPS printer, regardless of which doc flavors
* the printer supports. If the printer doesn't support the client's preferred
* doc flavor, the client can at least print plain text, or the client can
* convert its data to a renderable image and print the image.
* <P>
* Furthermore, every Java Print Service instance must fulfill these
* requirements for processing plain text print data:
* <UL>
* <LI>
* The character pair carriage return-line feed (CR-LF) means
* "go to column 1 of the next line."
* <LI>
* A carriage return (CR) character standing by itself means
* "go to column 1 of the next line."
* <LI>
* A line feed (LF) character standing by itself means
* "go to column 1 of the next line."
* <LI>
* </UL>
* <P>
* The client must itself perform all plain text print data formatting not
* addressed by the above requirements.
*
* <H3>Design Rationale</H3>
* <P>
* Class DocFlavor in package javax.print.data is similar to class
* {@link java.awt.datatransfer.DataFlavor DataFlavor}. Class
* <code>DataFlavor</code>
* is not used in the Java Print Service (JPS) API
* for three reasons which are all rooted in allowing the JPS API to be
* shared by other print services APIs which may need to run on Java profiles
* which do not include all of the Java Platform, Standard Edition.
* <OL TYPE=1>
* <LI>
* The JPS API is designed to be used in Java profiles which do not support
* AWT.
*
* <LI>
* The implementation of class <code>java.awt.datatransfer.DataFlavor</code>
* does not guarantee that equivalent data flavors will have the same
* serialized representation. DocFlavor does, and can be used in services
* which need this.
*
* <LI>
* The implementation of class <code>java.awt.datatransfer.DataFlavor</code>
* includes a human presentable name as part of the serialized representation.
* This is not appropriate as part of a service matching constraint.
* </OL>
* <P>
* Class DocFlavor's serialized representation uses the following
* canonical form of a MIME type string. Thus, two doc flavors with MIME types
* that are not identical but that are equivalent (that have the same
* canonical form) may be considered equal.
* <UL>
* <LI> The media type, media subtype, and parameters are retained, but all
* comments and whitespace characters are discarded.
* <LI> The media type, media subtype, and parameter names are converted to
* lowercase.
* <LI> The parameter values retain their original case, except a charset
* parameter value for a text media type is converted to lowercase.
* <LI> Quote characters surrounding parameter values are removed.
* <LI> Quoting backslash characters inside parameter values are removed.
* <LI> The parameters are arranged in ascending order of parameter name.
* </UL>
* <P>
* Class DocFlavor's serialized representation also contains the
* fully-qualified class <I>name</I> of the representation class
* (a String object), rather than the representation class itself
* (a Class object). This allows a client to examine the doc flavors a
* Java Print Service instance supports without having
* to load the representation classes, which may be problematic for
* limited-resource clients.
* <P>
*
* @author Alan Kaminsky
*/
public class DocFlavor implements Serializable, Cloneable {
private static final long serialVersionUID = -4512080796965449721L;
/**
* A String representing the host operating system encoding.
* This will follow the conventions documented in
* <a href="http://www.ietf.org/rfc/rfc2278.txt">
* <i>RFC 2278: IANA Charset Registration Procedures</i></a>
* except where historical names are returned for compatibility with
* previous versions of the Java platform.
* The value returned from method is valid only for the VM which
* returns it, for use in a DocFlavor.
* This is the charset for all the "HOST" pre-defined DocFlavors in
* the executing VM.
*/
public static final String hostEncoding;
static {
hostEncoding =
java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("file.encoding"));
}
/**
* MIME type.
*/
private transient MimeType myMimeType;
/**
* Representation class name.
* @serial
*/
private String myClassName;
/**
* String value for this doc flavor. Computed when needed and cached.
*/
private transient String myStringValue = null;
/**
* Constructs a new doc flavor object from the given MIME type and
* representation class name. The given MIME type is converted into
* canonical form and stored internally.
*
* @param mimeType MIME media type string.
* @param className Fully-qualified representation class name.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null or
* <CODE>className</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public DocFlavor(String mimeType, String className) {
if (className == null) {
throw new NullPointerException();
}
myMimeType = new MimeType (mimeType);
myClassName = className;
}
/**
* Returns this doc flavor object's MIME type string based on the
* canonical form. Each parameter value is enclosed in quotes.
* @return the mime type
*/
public String getMimeType() {
return myMimeType.getMimeType();
}
/**
* Returns this doc flavor object's media type (from the MIME type).
* @return the media type
*/
public String getMediaType() {
return myMimeType.getMediaType();
}
/**
* Returns this doc flavor object's media subtype (from the MIME type).
* @return the media sub-type
*/
public String getMediaSubtype() {
return myMimeType.getMediaSubtype();
}
/**
* Returns a <code>String</code> representing a MIME
* parameter.
* Mime types may include parameters which are usually optional.
* The charset for text types is a commonly useful example.
* This convenience method will return the value of the specified
* parameter if one was specified in the mime type for this flavor.
* <p>
* @param paramName the name of the paramater. This name is internally
* converted to the canonical lower case format before performing
* the match.
* @return String representing a mime parameter, or
* null if that parameter is not in the mime type string.
* @exception NullPointerException if paramName is null.
*/
public String getParameter(String paramName) {
return myMimeType.getParameterMap().get(paramName.toLowerCase());
}
/**
* Returns the name of this doc flavor object's representation class.
* @return the name of the representation class.
*/
public String getRepresentationClassName() {
return myClassName;
}
/**
* Converts this <code>DocFlavor</code> to a string.
*
* @return MIME type string based on the canonical form. Each parameter
* value is enclosed in quotes.
* A "class=" parameter is appended to the
* MIME type string to indicate the representation class name.
*/
public String toString() {
return getStringValue();
}
/**
* Returns a hash code for this doc flavor object.
*/
public int hashCode() {
return getStringValue().hashCode();
}
/**
* Determines if this doc flavor object is equal to the given object.
* The two are equal if the given object is not null, is an instance
* of <code>DocFlavor</code>, has a MIME type equivalent to this doc
* flavor object's MIME type (that is, the MIME types have the same media
* type, media subtype, and parameters), and has the same representation
* class name as this doc flavor object. Thus, if two doc flavor objects'
* MIME types are the same except for comments, they are considered equal.
* However, two doc flavor objects with MIME types of "text/plain" and
* "text/plain; charset=US-ASCII" are not considered equal, even though
* they represent the same media type (because the default character
* set for plain text is US-ASCII).
*
* @param obj Object to test.
*
* @return True if this doc flavor object equals <CODE>obj</CODE>, false
* otherwise.
*/
public boolean equals(Object obj) {
return
obj != null &&
obj instanceof DocFlavor &&
getStringValue().equals (((DocFlavor) obj).getStringValue());
}
/**
* Returns this doc flavor object's string value.
*/
private String getStringValue() {
if (myStringValue == null) {
myStringValue = myMimeType + "; class=\"" + myClassName + "\"";
}
return myStringValue;
}
/**
* Write the instance to a stream (ie serialize the object).
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(myMimeType.getMimeType());
}
/**
* Reconstitute an instance from a stream (that is, deserialize it).
*
* @serialData
* The serialised form of a DocFlavor is the String naming the
* representation class followed by the String representing the canonical
* form of the mime type.
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
myMimeType = new MimeType((String)s.readObject());
}
/**
* Class DocFlavor.BYTE_ARRAY provides predefined static constant
* DocFlavor objects for example doc flavors using a byte array
* (<CODE>byte[]</CODE>) as the print data representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class BYTE_ARRAY extends DocFlavor {
private static final long serialVersionUID = -9065578006593857475L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"[B"</CODE> (byte array).
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public BYTE_ARRAY (String mimeType) {
super (mimeType, "[B");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_HOST =
new BYTE_ARRAY ("text/plain; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_8 =
new BYTE_ARRAY ("text/plain; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16 =
new BYTE_ARRAY ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16BE =
new BYTE_ARRAY ("text/plain; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16LE =
new BYTE_ARRAY ("text/plain; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_US_ASCII =
new BYTE_ARRAY ("text/plain; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_HTML_HOST =
new BYTE_ARRAY ("text/html; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_8 =
new BYTE_ARRAY ("text/html; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16 =
new BYTE_ARRAY ("text/html; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16BE =
new BYTE_ARRAY ("text/html; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16LE =
new BYTE_ARRAY ("text/html; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_HTML_US_ASCII =
new BYTE_ARRAY ("text/html; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY PDF = new BYTE_ARRAY ("application/pdf");
/**
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY POSTSCRIPT =
new BYTE_ARRAY ("application/postscript");
/**
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY PCL =
new BYTE_ARRAY ("application/vnd.hp-PCL");
/**
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY GIF = new BYTE_ARRAY ("image/gif");
/**
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY JPEG = new BYTE_ARRAY ("image/jpeg");
/**
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY PNG = new BYTE_ARRAY ("image/png");
/**
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array). The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final BYTE_ARRAY AUTOSENSE =
new BYTE_ARRAY ("application/octet-stream");
}
/**
* Class DocFlavor.INPUT_STREAM provides predefined static constant
* DocFlavor objects for example doc flavors using a byte stream ({@link
* java.io.InputStream java.io.InputStream}) as the print
* data representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class INPUT_STREAM extends DocFlavor {
private static final long serialVersionUID = -7045842700749194127L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public INPUT_STREAM (String mimeType) {
super (mimeType, "java.io.InputStream");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_HOST =
new INPUT_STREAM ("text/plain; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_8 =
new INPUT_STREAM ("text/plain; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16 =
new INPUT_STREAM ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16BE =
new INPUT_STREAM ("text/plain; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16LE =
new INPUT_STREAM ("text/plain; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_US_ASCII =
new INPUT_STREAM ("text/plain; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_HOST =
new INPUT_STREAM ("text/html; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_8 =
new INPUT_STREAM ("text/html; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16 =
new INPUT_STREAM ("text/html; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16BE =
new INPUT_STREAM ("text/html; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16LE =
new INPUT_STREAM ("text/html; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_US_ASCII =
new INPUT_STREAM ("text/html; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"java.io.InputStream"</CODE>
* (byte stream).
*/
public static final INPUT_STREAM PDF = new INPUT_STREAM ("application/pdf");
/**
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM POSTSCRIPT =
new INPUT_STREAM ("application/postscript");
/**
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM PCL =
new INPUT_STREAM ("application/vnd.hp-PCL");
/**
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM GIF = new INPUT_STREAM ("image/gif");
/**
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM JPEG = new INPUT_STREAM ("image/jpeg");
/**
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM PNG = new INPUT_STREAM ("image/png");
/**
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
* The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final INPUT_STREAM AUTOSENSE =
new INPUT_STREAM ("application/octet-stream");
}
/**
* Class DocFlavor.URL provides predefined static constant DocFlavor
* objects.
* For example doc flavors using a Uniform Resource Locator ({@link
* java.net.URL java.net.URL}) as the print data
* representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class URL extends DocFlavor {
private static final long serialVersionUID = 2936725788144902062L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"java.net.URL"</CODE>.
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public URL (String mimeType) {
super (mimeType, "java.net.URL");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_HOST =
new URL ("text/plain; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_8 =
new URL ("text/plain; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>java.net.URL""</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16 =
new URL ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16BE =
new URL ("text/plain; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16LE =
new URL ("text/plain; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_US_ASCII =
new URL ("text/plain; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_HOST =
new URL ("text/html; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_8 =
new URL ("text/html; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16 =
new URL ("text/html; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16BE =
new URL ("text/html; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16LE =
new URL ("text/html; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_US_ASCII =
new URL ("text/html; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PDF = new URL ("application/pdf");
/**
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL POSTSCRIPT = new URL ("application/postscript");
/**
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PCL = new URL ("application/vnd.hp-PCL");
/**
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL GIF = new URL ("image/gif");
/**
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL JPEG = new URL ("image/jpeg");
/**
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PNG = new URL ("image/png");
/**
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
* The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final URL AUTOSENSE = new URL ("application/octet-stream");
}
/**
* Class DocFlavor.CHAR_ARRAY provides predefined static constant
* DocFlavor objects for example doc flavors using a character array
* (<CODE>char[]</CODE>) as the print data representation class. As such,
* the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class CHAR_ARRAY extends DocFlavor {
private static final long serialVersionUID = -8720590903724405128L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of
* <CODE>"[C"</CODE> (character array).
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public CHAR_ARRAY (String mimeType) {
super (mimeType, "[C");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"[C"</CODE> (character array).
*/
public static final CHAR_ARRAY TEXT_PLAIN =
new CHAR_ARRAY ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"[C"</CODE> (character array).
*/
public static final CHAR_ARRAY TEXT_HTML =
new CHAR_ARRAY ("text/html; charset=utf-16");
}
/**
* Class DocFlavor.STRING provides predefined static constant DocFlavor
* objects for example doc flavors using a string ({@link java.lang.String
* java.lang.String}) as the print data representation class.
* As such, the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class STRING extends DocFlavor {
private static final long serialVersionUID = 4414407504887034035L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"java.lang.String"</CODE>.
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public STRING (String mimeType) {
super (mimeType, "java.lang.String");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.lang.String"</CODE>.
*/
public static final STRING TEXT_PLAIN =
new STRING ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.lang.String"</CODE>.
*/
public static final STRING TEXT_HTML =
new STRING ("text/html; charset=utf-16");
}
/**
* Class DocFlavor.READER provides predefined static constant DocFlavor
* objects for example doc flavors using a character stream ({@link
* java.io.Reader java.io.Reader}) as the print data
* representation class. As such, the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class READER extends DocFlavor {
private static final long serialVersionUID = 7100295812579351567L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of\
* <CODE>"java.io.Reader"</CODE> (character stream).
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public READER (String mimeType) {
super (mimeType, "java.io.Reader");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.io.Reader"</CODE> (character stream).
*/
public static final READER TEXT_PLAIN =
new READER ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.io.Reader"</CODE> (character stream).
*/
public static final READER TEXT_HTML =
new READER ("text/html; charset=utf-16");
}
/**
* Class DocFlavor.SERVICE_FORMATTED provides predefined static constant
* DocFlavor objects for example doc flavors for service formatted print
* data.
* <P>
*
* @author Alan Kaminsky
*/
public static class SERVICE_FORMATTED extends DocFlavor {
private static final long serialVersionUID = 6181337766266637256L;
/**
* Constructs a new doc flavor with a MIME type of
* <CODE>"application/x-java-jvm-local-objectref"</CODE> indicating
* service formatted print data and the given print data
* representation class name.
*
* @param className Fully-qualified representation class name.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>className</CODE> is
* null.
*/
public SERVICE_FORMATTED (String className) {
super ("application/x-java-jvm-local-objectref", className);
}
/**
* Service formatted print data doc flavor with print data
* representation class name =
* <CODE>"java.awt.image.renderable.RenderableImage"</CODE>
* (renderable image object).
*/
public static final SERVICE_FORMATTED RENDERABLE_IMAGE =
new SERVICE_FORMATTED("java.awt.image.renderable.RenderableImage");
/**
* Service formatted print data doc flavor with print data
* representation class name = <CODE>"java.awt.print.Printable"</CODE>
* (printable object).
*/
public static final SERVICE_FORMATTED PRINTABLE =
new SERVICE_FORMATTED ("java.awt.print.Printable");
/**
* Service formatted print data doc flavor with print data
* representation class name = <CODE>"java.awt.print.Pageable"</CODE>
* (pageable object).
*/
public static final SERVICE_FORMATTED PAGEABLE =
new SERVICE_FORMATTED ("java.awt.print.Pageable");
}
}
| gpl-2.0 |
mizadri/java_tp | 2pr/src/tp/pr2/mv/OperandStack.java | 2424 | package tp.pr2.mv;
/**
* Clase que representa la pila de operandos.
* @author Adrian Garcia y Omar Gaytan
*
*/
public class OperandStack {
private int maxSize = 100;
private Integer[] stack;
private int top = -1;
private int numElements = 0;
/**
* Constructor sin parametros
*/
public OperandStack(){
this.stack = new Integer[maxSize];
}
/**
* Devuelve el número de elementos en la pila
* @return numElements
*/
public int getNumElem(){
return this.numElements;
}
/**
* Comprueba si la pila esta vacía
* @return aux
*/
public boolean isEmpty(){
boolean aux = true;
if(top >= 0) aux = false;
return aux;
}
/**
* Inserta un valor en la cima de la pila.
* @param value
* @return aux
*/
public boolean push(int value){
boolean aux = false;
if(top < maxSize -1){
stack[++top] = value;
aux = true;
this.numElements++;
}
return aux;
}
/**
* Disminuye la cima de la pila.
*/
public int pop() {
Integer n = this.stack[top];
top--;
this.numElements--;
return n;
}
/**
* Devuelve la cima de la pila.
* @return i
*/
public int top(){
int i = 0;
if(!this.isEmpty()){
i = stack[top] ;
}
return i;
}
/**
* Devuelve el contenido de la pila en forma de string.
*/
public String toString(){
String s = "";
if(!this.isEmpty()){
for(int i =0;i<=top;i++){
s = s + " " + stack[i];
}
}else{
s = s + " <vacia>";
}
return s;
}
/**
* Duplica el tamaño de la pila(llamada por cpu cuando se supera el tamaño).
*/
public void reSize() {
int[] aux = new int[maxSize];
for(int i=0;i<maxSize;i++){
aux[i] = stack[i];
}
maxSize = maxSize*2;
stack = new Integer[maxSize];
for(int i=0;i<maxSize/2;i++){
stack[i] = aux[i];
}
}
} | gpl-2.0 |
mikeAopeneng/joyo-kanji | KanjiDroid/src/androidTest/java/com.ichi2.anki.tests/MediaTest.java | 9354 | /****************************************************************************************
* Copyright (c) 2014 Houssam Salem <houssam.salem.au@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package website.openeng.anki.tests;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.Suppress;
import website.openeng.anki.BackupManager;
import website.openeng.anki.exception.APIVersionException;
import website.openeng.libanki.Collection;
import website.openeng.libanki.Note;
import website.openeng.libanki.Media;
import website.openeng.anki.tests.Shared;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import website.openeng.utils.*;
/**
* Unit tests for {@link Media}.
*/
public class MediaTest extends AndroidTestCase {
public void testAdd() throws IOException, APIVersionException {
// open new empty collection
Collection d = Shared.getEmptyCol(getContext());
File dir = Shared.getTestDir(getContext());
BackupManager.removeDir(dir);
dir.mkdirs();
File path = new File(dir, "foo.jpg");
FileOutputStream os;
os = new FileOutputStream(path, false);
os.write("hello".getBytes());
os.close();
// new file, should preserve name
String r = d.getMedia().addFile(path);
assertEquals("foo.jpg", r);
// adding the same file again should not create a duplicate
assertEquals("foo.jpg", d.getMedia().addFile(path));
// but if it has a different md5, it should
os = new FileOutputStream(path, false);
os.write("world".getBytes());
os.close();
assertEquals("foo (1).jpg", d.getMedia().addFile(path));
}
public void testStrings() throws IOException {
Collection d = Shared.getEmptyCol(getContext());
Long mid = d.getModels().getModels().entrySet().iterator().next().getKey();
List<String> expected;
List<String> actual;
expected = Arrays.asList();
actual = d.getMedia().filesInStr(mid, "aoeu");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src='foo.jpg'>ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg", "bar.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src='foo.jpg'><img src=\"bar.jpg\">ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src=foo.jpg style=bar>ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("one", "two");
actual = d.getMedia().filesInStr(mid, "<img src=one><img src=two>");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src=\"foo.jpg\">ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg", "fo");
actual = d.getMedia().filesInStr(mid, "aoeu<img src=\"foo.jpg\"><img class=yo src=fo>ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.mp3");
actual = d.getMedia().filesInStr(mid, "aou[sound:foo.mp3]aou");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
assertEquals("aoeu", d.getMedia().strip("aoeu"));
assertEquals("aoeuaoeu", d.getMedia().strip("aoeu[sound:foo.mp3]aoeu"));
assertEquals("aoeu", d.getMedia().strip("a<img src=yo>oeu"));
assertEquals("aoeu", d.getMedia().escapeImages("aoeu"));
assertEquals("<img src='http://foo.com'>", d.getMedia().escapeImages("<img src='http://foo.com'>"));
assertEquals("<img src=\"foo%20bar.jpg\">", d.getMedia().escapeImages("<img src=\"foo bar.jpg\">"));
}
public void testDeckIntegration() throws IOException, APIVersionException {
Collection d = Shared.getEmptyCol(getContext());
// create a media dir
d.getMedia().dir();
// Put a file into it
File file = new File(Shared.getTestDir(getContext()), "fake.png");
file.createNewFile();
d.getMedia().addFile(file);
// add a note which references it
Note f = d.newNote();
f.setitem("Front", "one");
f.setitem("Back", "<img src='fake.png'>");
d.addNote(f);
// and one which references a non-existent file
f = d.newNote();
f.setitem("Front", "one");
f.setitem("Back", "<img src='fake2.png'>");
d.addNote(f);
// and add another file which isn't used
FileOutputStream os;
os = new FileOutputStream(new File(d.getMedia().dir(), "foo.jpg"), false);
os.write("test".getBytes());
os.close();
// check media
List<List<String>> ret = d.getMedia().check();
List<String> expected;
List<String> actual;
expected = Arrays.asList("fake2.png");
actual = ret.get(0);
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = ret.get(1);
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
}
@Suppress
private List<String> added(Collection d) {
return d.getMedia().getDb().queryColumn(String.class, "select fname from media where csum is not null", 0);
}
@Suppress
private List<String> removed(Collection d) {
return d.getMedia().getDb().queryColumn(String.class, "select fname from media where csum is null", 0);
}
public void testChanges() throws IOException, APIVersionException {
Collection d = Shared.getEmptyCol(getContext());
assertTrue(d.getMedia()._changed() != null);
assertTrue(added(d).size() == 0);
assertTrue(removed(d).size() == 0);
// add a file
File dir = Shared.getTestDir(getContext());
File path = new File(dir, "foo.jpg");
FileOutputStream os;
os = new FileOutputStream(path, false);
os.write("hello".getBytes());
os.close();
path = new File(d.getMedia().dir(), d.getMedia().addFile(path));
// should have been logged
d.getMedia().findChanges();
assertTrue(added(d).size() > 0);
assertTrue(removed(d).size() == 0);
// if we modify it, the cache won't notice
os = new FileOutputStream(path, true);
os.write("world".getBytes());
os.close();
assertTrue(added(d).size() == 1);
assertTrue(removed(d).size() == 0);
// but if we add another file, it will
path = new File(path.getAbsolutePath()+"2");
os = new FileOutputStream(path, true);
os.write("yo".getBytes());
os.close();
d.getMedia().findChanges(true);
assertTrue(added(d).size() == 2);
assertTrue(removed(d).size() == 0);
// deletions should get noticed too
path.delete();
d.getMedia().findChanges(true);
assertTrue(added(d).size() == 1);
assertTrue(removed(d).size() == 1);
}
public void testIllegal() throws IOException {
Collection d = Shared.getEmptyCol(getContext());
String aString = "a:b|cd\\e/f\0g*h";
String good = "abcdefgh";
assertTrue(d.getMedia().stripIllegal(aString).equals(good));
for (int i = 0; i < aString.length(); i++) {
char c = aString.charAt(i);
boolean bad = d.getMedia().hasIllegal("something" + c + "morestring");
if (bad) {
assertTrue(good.indexOf(c) == -1);
} else {
assertTrue(good.indexOf(c) != -1);
}
}
}
}
| gpl-2.0 |
ParallelAndReconfigurableComputing/Pyjama | src/pj/parser/ast/visitor/PyjamaToJavaVisitor.java | 69061 | /*
* Copyright (C) 2013-2016 Parallel and Reconfigurable Computing Group, University of Auckland.
*
* Authors: <http://homepages.engineering.auckland.ac.nz/~parallel/ParallelIT/People.html>
*
* This file is part of Pyjama, a Java implementation of OpenMP-like directive-based
* parallelisation compiler and its runtime routines.
*
* Pyjama 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.
*
* Pyjama 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 Pyjama. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Xing Fan
* @version 1.0
*/
package pj.parser.ast.visitor;
import pj.parser.ast.*;
import pj.parser.ast.body.*;
import pj.parser.ast.expr.*;
import pj.parser.ast.omp.*;
import pj.parser.ast.stmt.*;
import pj.parser.ast.symbolscope.SymbolTable;
import pj.parser.ast.type.*;
import pj.parser.ast.visitor.constructwrappers.*;
import pj.parser.ast.visitor.dataclausehandler.DataClausesHandler;
import pj.parser.ast.visitor.dataclausehandler.DataClauseHandlerUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
public class PyjamaToJavaVisitor implements VoidVisitor<SourcePrinter> {
protected File file;
protected String compilationFileName;
protected final static String PYJAMA_FILE_EXTENSION = ".pj";
static protected int nextOpenMPRegionUniqueID = 0;
static protected int nextTargetBlockID = 0;
static protected int nextTaskBlockID = 0;
static protected int nextWorkShareID = 0;
static protected int nextGuiCodeID = 0;
protected static final String prefixTaskNameForParallelRegion = "_OMP_ParallelRegion_";
protected static final String prefixTaskNameForTargetTaskRegion = "_OMP_TargetTaskRegion_";
protected static final String prefixTaskNameForTaskRegion = "_OMP_TaskRegion_";
protected static final String prefixTaskNameForWorkShare = "_OMP_WorkShare_";
protected static final String prefixTaskNameForGuiCode = "_OMP_GuiCode_";
//this hashmap stores the id of each generated region, in order to avoid id mismatch for same OpenMP construct.
static HashMap<OpenMPStatement, Integer> OpenMPStatementIDPairing = new HashMap<OpenMPStatement, Integer>();
//this hashmap stores the virtual targets with their name_as names. A name may pair multiple target blocks.
static HashMap<String, HashSet<TargetTaskCodeClassBuilder>> nameAsTargetBlocks = new HashMap<String, HashSet<TargetTaskCodeClassBuilder>>();
protected Stack<Boolean> stateMachineVisitingMode = new Stack<Boolean>();
protected SourcePrinter CodePrinter = new SourcePrinter();
protected SourcePrinter PrinterForAuxiliaryClasses = new SourcePrinter();
protected SourcePrinter PrinterForAsyncMethodStateMachineBuilder = new SourcePrinter();
protected SourcePrinter PrinterForAsyncTargetTaskStateMachineBuilder = new SourcePrinter();
//keep track of current method whether is static, used for the generate of parallel region class, and work share method
public boolean currentMethodIsStatic = false;
//keep track of current method or constructor's statements, this statements may used in freeguithread visitor
protected List<Statement> currentMethodOrConstructorStmts = null;
//keep track of current type of declaration of variables 2014.7.14
protected Type currentVarDeclarationType = null;
//if current var declaration is in foreach header, do not give initial value 2014.7.4 => 2014.10.27
protected boolean needNotVarInit = false;
//keep track of current worksharing block's private variables, including firstprivate, lastprivate, and reduction
/* 2015.6.29
* currentPrivateVariableInOMPWorksharingBlock: contain all variable name inside current //#omp for or //#omp sections
* need to be renamed. This is used in NameExpr visitor.
*/
protected HashMap<String,String> currentPrivateVariableInOMPWorksharingBlock = new HashMap<String,String>();
private SymbolTable symbolTable = null;
public PyjamaToJavaVisitor(SymbolTable symbolTable) {
this.symbolTable = symbolTable;
}
public PyjamaToJavaVisitor(SymbolTable symbolTable, Stack<Boolean> visitingMode) {
this.symbolTable = symbolTable;
this.stateMachineVisitingMode = visitingMode;
}
public SymbolTable getSymbolTable() {
return symbolTable;
}
public Stack<Boolean> getVisitingModeTrack() {
return this.stateMachineVisitingMode;
}
//OpenMP add BEGIN*******************************************************************************OpenMP add BEGIN//
public void visit(Node n, SourcePrinter printer){
throw new RuntimeException("Node: This abstract class should not appear.");
}
//------------------------------------------------------
public void visit(OmpParallelConstruct n, SourcePrinter printer){
//get current OmpParallelConstruct's scopeinfo from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
n.processAllReachableVariablesIfNecessary();
int uniqueOpenMPRegionID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueOpenMPRegionID = nextOpenMPRegionUniqueID++;
OpenMPStatementIDPairing.put(n, uniqueOpenMPRegionID);
} else {
uniqueOpenMPRegionID = OpenMPStatementIDPairing.get(n);
}
ParallelRegionClassBuilder currentPRClass = ParallelRegionClassBuilder.create(n, this.currentMethodIsStatic, this, this.currentMethodOrConstructorStmts);
currentPRClass.className = prefixTaskNameForParallelRegion + uniqueOpenMPRegionID;
printer.printLn("/*OpenMP Parallel region (#" + uniqueOpenMPRegionID + ") -- START */");
this.PrinterForAuxiliaryClasses.printLn(currentPRClass.getSource());
String previous_icv = "icv_previous_" + currentPRClass.className;
String new_icv = "icv_" + currentPRClass.className;
String thread_number = "_threadNum_" + currentPRClass.className;
printer.printLn("InternalControlVariables " + previous_icv + " = PjRuntime.getCurrentThreadICV();");
printer.printLn("InternalControlVariables " + new_icv + " = PjRuntime.inheritICV(" + previous_icv + ");");
if (null != n.getNumThreadsExpression()) {
String numThreadsClause = n.getNumThreadsExpression().getNumExpression().toString();
printer.printLn("int " + thread_number + " = " + numThreadsClause + ";");
} else {
printer.printLn("int " + thread_number + " = " + new_icv + ".nthreads_var.get("+ new_icv + ".levels_var);");
}
printer.printLn(currentPRClass.className + " " + currentPRClass.className + "_in = new "+ currentPRClass.className + "(" + thread_number + "," + new_icv + ");");
DataClausesHandler.processDataClausesBeforePRClassInvocation(currentPRClass, printer);
printer.printLn(currentPRClass.className + "_in" + ".runParallelCode();");
if (!n.isFreegui()) {
// if directive is normal parallel directive, recovery data from PRClass
DataClausesHandler.processDataClausesAfterPRClassInvocation(currentPRClass, printer);
printer.printLn("PjRuntime.recoverParentICV(" + previous_icv + ");");
printer.printLn("RuntimeException OMP_ee_" + uniqueOpenMPRegionID + " = (RuntimeException) " + currentPRClass.className + "_in.OMP_CurrentParallelRegionExceptionSlot.get();");
printer.printLn("if (OMP_ee_" + uniqueOpenMPRegionID + " != null) {throw OMP_ee_" + uniqueOpenMPRegionID + ";}");
} else if (n.isFreegui()) {
// if directive is freeguithread property, return after region, following code is invoked in region.
printer.printLn("if (PjRuntime.getCurrentThreadICV() != null) {", -1);
printer.indent();
DataClausesHandler.processDataClausesAfterPRClassInvocation(currentPRClass, printer);
printer.printLn("PjRuntime.recoverParentICV(" + previous_icv + ");");
printer.printLn("return;", -1);
printer.unindent();
printer.printLn("}", -1);
}
printer.printLn("/*OpenMP Parallel region (#" + uniqueOpenMPRegionID + ") -- END */");
}
public void visit(OmpParallelForConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp parallel for: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpParallelSectionsConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp parallel sections: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpForConstruct n, SourcePrinter printer){
//get current OmpParallelConstruct's scopeinfo from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
int uniqueWorkShareRegionID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueWorkShareRegionID = nextOpenMPRegionUniqueID++;
OpenMPStatementIDPairing.put(n, uniqueWorkShareRegionID);
} else {
uniqueWorkShareRegionID = OpenMPStatementIDPairing.get(n);
}
WorkShareBlockBuilder currentWSBlock = new WorkShareBlockBuilder(n, this, uniqueWorkShareRegionID);
printer.printLn("/*OpenMP Work Share region (#" + uniqueWorkShareRegionID + ") -- START */");
//Print Work Share Region
printer.printLn(currentWSBlock.getSource());
printer.printLn("PjRuntime.setBarrier();");
printer.printLn("PjRuntime.reset_OMP_orderCursor();");
printer.printLn("/*OpenMP Work Share region (#" + uniqueWorkShareRegionID + ") -- END */");
}
public void visit(OmpSectionsConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp sections: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpSingleConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp single: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpMasterConstruct n, SourcePrinter printer){
printer.printLn("if (0 == Pyjama.omp_get_thread_num()) {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("}");
}
public void visit(OmpCriticalConstruct n, SourcePrinter printer){
printer.printLn("PjRuntime.OMP_lock.lock();");
printer.printLn("try {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("} finally {");
printer.printLn("PjRuntime.OMP_lock.unlock();");
printer.unindent();
printer.printLn("}");
}
public void visit(OmpOrderedConstruct n, SourcePrinter printer){
printer.printLn("while (PjRuntime.get_OMP_orderCursor().get() < OMP_local_iterator) {}");
n.getStatement().accept(this, printer);
printer.printLn();
printer.printLn("PjRuntime.get_OMP_orderCursor().incrementAndGet();");
}
public void visit(OmpAtomicConstruct n, SourcePrinter printer){
// throw new RuntimeException("//#omp atomic: This should have been normalised.");
// --------------------------- Normalised --------------------//
printer.printLn("PjRuntime.OMP_lock.lock();");
printer.printLn("try {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("} finally {");
printer.printLn("PjRuntime.OMP_lock.unlock();");
printer.unindent();
printer.printLn("}");
}
public void visit(OmpTaskConstruct n, SourcePrinter printer) {
//get current OmpTaskConstruct's scope info from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
n.processAllReachableVariablesIfNecessary();
int uniqueTaskBlockID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueTaskBlockID = nextTaskBlockID++;
OpenMPStatementIDPairing.put(n, uniqueTaskBlockID);
} else {
uniqueTaskBlockID = OpenMPStatementIDPairing.get(n);
}
TaskCodeClassBuilder currentTClass = TaskCodeClassBuilder.create(n, this.currentMethodIsStatic, this, prefixTaskNameForTaskRegion + uniqueTaskBlockID);
printer.printLn("/*OpenMP Task block (#" + uniqueTaskBlockID + ") -- START */");
printer.printLn(currentTClass.className + " " + currentTClass.className + "_in = new "+ currentTClass.className + "();");
DataClausesHandler.processDataClausesBeforeTaskClassInvocation(currentTClass, printer);
printer.printLn("PjRuntime.submitOmpTask(" + currentTClass.className + "_in);");
DataClausesHandler.processDataClausesAfterTaskClassInvocation(currentTClass, printer);
printer.printLn("/*OpenMP Task block (#" + uniqueTaskBlockID + ") -- END */");
this.PrinterForAuxiliaryClasses.printLn(currentTClass.getSource());
}
public void visit(OmpBarrierDirective n, SourcePrinter printer){
printer.printLn("PjRuntime.setBarrier();");
}
public void visit(OmpFlushDirective n, SourcePrinter printer){
printer.printLn("PjRuntime.flushMemory();");
}
public void visit(OmpFreeguiConstruct n, SourcePrinter printer){
throw new RuntimeException("OmpFreeguiConstruct should be normalised as OmpParallelConstruct with freegui property");
}
public void visit(OmpGuiConstruct n, SourcePrinter printer){
//get current OmpParallelConstruct's scopeinfo from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
int uniqueGuiCodeID = nextGuiCodeID++;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueGuiCodeID = nextOpenMPRegionUniqueID++;
OpenMPStatementIDPairing.put(n, uniqueGuiCodeID);
} else {
uniqueGuiCodeID = OpenMPStatementIDPairing.get(n);
}
GuiCodeClassBuilder currentGuiCode = new GuiCodeClassBuilder(n, this);
currentGuiCode.guiName = prefixTaskNameForGuiCode + uniqueGuiCodeID;
printer.printLn("//#BEGIN GUI execution block");
printer.printLn("if (SwingUtilities.isEventDispatchThread()) {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("}");
printer.printLn("else {");
printer.indent();
printer.printLn(currentGuiCode.getSource());
printer.printLn("}");
printer.printLn("//#END GUI execution block");
}
public void visit(OmpCopyprivateDataClause n, SourcePrinter arg) {
throw new RuntimeException("copyprivate Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpDataClause n, SourcePrinter arg) {
throw new RuntimeException("OpenMPStatement: This abstract class should not appear.");
}
public void visit(OmpDefaultDataClause n, SourcePrinter arg) {
throw new RuntimeException("default Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpIfClause n, SourcePrinter arg) {
throw new RuntimeException("if Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpLastprivateDataClause n, SourcePrinter arg) {
throw new RuntimeException("lastprivate Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpNumthreadsClause n, SourcePrinter arg) {
throw new RuntimeException("num_threads Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpPrivateDataClause n, SourcePrinter arg) {
throw new RuntimeException("private Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpReductionDataClause n, SourcePrinter arg) {
throw new RuntimeException("reduction Clause should not be visited by PyjamaToJavaVisitor.");
}
@Override
public void visit(OmpReductionOperator n, SourcePrinter arg) {
throw new RuntimeException("reduction Operator should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpScheduleClause n, SourcePrinter arg) {
throw new RuntimeException("schedule Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpSectionConstruct n, SourcePrinter arg) {
throw new RuntimeException("//#omp section: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpSharedDataClause n, SourcePrinter arg) {
throw new RuntimeException("shared Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OpenMPStatement n, SourcePrinter arg) {
throw new RuntimeException("OpenMPStatement: This abstract class should not appear.");
}
public void visit(OmpNeglectExceptionClause n, SourcePrinter arg) {
throw new RuntimeException("neglect_exception Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpCancellationPointDirective n, SourcePrinter printer) {
if (n.getRegion() == OmpCancellationPointDirective.Region.Parallel) {
printer.printLn("PjRuntime.checkParallelCancellationPoint();");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.For) {
printer.printLn("PjRuntime.checkWorksharingCancellationPoint();");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.Sections) {
printer.printLn("PjRuntime.checkWorksharingCancellationPoint();");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.Taskgroup) {
throw new RuntimeException("Pyjama does not support omp task yet!");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.CurrentTask) {
//omp cancellation point task
printer.printLn("PjRuntime.checkTaskCancellation();");
}
}
public void visit(OmpCancelDirective n, SourcePrinter printer) {
if (n.getRegion() == OmpCancelDirective.Region.Parallel) {
if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Global) {
printer.print("throw new pj.pr.exceptions.OmpParallelRegionGlobalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
} else if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Local) {
printer.printLn("throw new pj.pr.exceptions.OmpParallelRegionLocalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
}
} else if (n.getRegion() == OmpCancelDirective.Region.For || n.getRegion() == OmpCancelDirective.Region.Sections){
if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Global) {
printer.printLn("throw new pj.pr.exceptions.OmpWorksharingGlobalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
} else if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Local) {
printer.printLn("throw new pj.pr.exceptions.OmpWorksharingLocalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
}
} else if (n.getRegion() == OmpCancelDirective.Region.Taskgroup) {
throw new RuntimeException("Pyjama does not support omp task yet!");
}
}
public void visit(OmpTargetConstruct n, SourcePrinter printer) {
//return if current visiting is in a state-machine building mode.
boolean stateMachineBuildingMode = this.stateMachineVisitingMode.peek();
//if current target block contains await, the indicate the compiler, the inside visiting should also visited by a state machine builder.
if (n.containAwait()) {
this.stateMachineVisitingMode.push(true);
} else {
this.stateMachineVisitingMode.push(false);
}
//get current OmpTargetConstruct's scope info from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
n.processAllReachableVariablesIfNecessary();
int uniqueTargetBlockID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueTargetBlockID = nextTargetBlockID++;
OpenMPStatementIDPairing.put(n, uniqueTargetBlockID);
} else {
uniqueTargetBlockID = OpenMPStatementIDPairing.get(n);
}
TargetTaskCodeClassBuilder currentTTClass = TargetTaskCodeClassBuilder.create(n, this.currentMethodIsStatic, this,
prefixTaskNameForTargetTaskRegion + uniqueTargetBlockID, n.containAwait());
printer.printLn("/*OpenMP Target region (#" + uniqueTargetBlockID + ") -- START */");
if (stateMachineBuildingMode) {
printer.printLn(currentTTClass.className + "_in = new "+ currentTTClass.className + "();");
} else {
printer.printLn(currentTTClass.className + " " + currentTTClass.className + "_in = new "+ currentTTClass.className + "();");
}
DataClausesHandler.processDataClausesBeforeTTClassInvocation(currentTTClass, printer);
this.PrinterForAsyncMethodStateMachineBuilder.printLn("private " + currentTTClass.className + " " + currentTTClass.className + "_in;");
this.PrinterForAsyncTargetTaskStateMachineBuilder.printLn("private " + currentTTClass.className + " " + currentTTClass.className + "_in;");
printer.printLn("if (PjRuntime.currentThreadIsTheTarget(\"" + n.getTargetName() + "\")) {");
printer.indent();
/*
* If current thread is already the target, we needn't submit the target task.
* Instead, we execute the target task in current thread.
*/
printer.printLn(currentTTClass.className + "_in.run();");
DataClausesHandler.processDataClausesAfterTTClassInvocation(currentTTClass, printer);
printer.unindent();
printer.printLn("} else {");
printer.indent();
//If this is a state machine building mode, we set completion call back function of current target task.
if (n.isAwait() && stateMachineBuildingMode) {
printer.printLn(currentTTClass.className + "_in.setOnCompleteCall(this, PjRuntime.getVirtualTargetOfCurrentThread());");
}
printer.printLn("PjRuntime.submitTargetTask(Thread.currentThread(), \"" + n.getTargetName() + "\", " + currentTTClass.className + "_in);");
if (n.isSync()) {
/*
* If default policy is applied, the encountering thread waits until the target block is finished.
*/
printer.printLn("PjRuntime.waitTaskTillFinish(" + currentTTClass.className + "_in);");
DataClausesHandler.processDataClausesAfterTTClassInvocation(currentTTClass, printer);
} else if (n.isAwait()) {
/*
* If await is applied, the current thread gives up current function execution, backs when target
* block is finished. For current implementation, we simply adopt an IHP (Irrelevant Handling Processing).
*/
if (!stateMachineBuildingMode) {
/*
* In normal method mode, we simply use IHP, essentially it will do a busy waiting in current implementation.
*/
printer.printLn("PjRuntime.IrrelevantHandlingProcessing(" + currentTTClass.className + "_in);");
} else if (stateMachineBuildingMode){
printer.printLn("if (false == PjRuntime.checkFinish(" + currentTTClass.className + "_in)) {");
printer.indent();
printer.printLn("this.OMP_state++;");
printer.printLn("return null;");
printer.unindent();
printer.printLn("}");
}
} else if (n.isNoWait()) {
/*
* We safely do nothing because we need not care about nowait the finish of the target block.
*/
}
printer.unindent();
printer.printLn("}");
if (n.isTaskAs()) {
storeTargetClassNameByTaskName(n.getTaskName(), currentTTClass);
printer.printLn("PjRuntime.storeTargetHandlerByName(" + currentTTClass.className + "_in, \"" + n.getTaskName() + "\");");
}
if (n.isAwait() && stateMachineBuildingMode) {
printer.printLn("this.OMP_state++;");
}
printer.printLn("/*OpenMP Target region (#" + uniqueTargetBlockID + ") -- END */");
//---Print Auxilary class
this.PrinterForAuxiliaryClasses.printLn(currentTTClass.getSource());
//---pop visiting mode.
this.stateMachineVisitingMode.pop();
}
public void visit(OmpTaskwaitDirective n, SourcePrinter printer) {
if (null != n.getIfClause()) {
printer.print("if(");
n.getIfClause().getIfExpression().accept(this, printer);
printer.printLn("){");
printer.indent();
}
if (null == n.getTaskName()) {
//If taskwait directive is not followed with a task name, this is wait for the tasks in the default parallel region.
printer.printLn("PjRuntime.taskWait();");
} else {
//If taskwait directive is followed with a task name, only wait tasks with this specific name, these tasks must be virtual task.
printer.printLn("PjRuntime.waitTargetBlocksWithTaskNameUntilFinish(\"" + n.getTaskName() + "\");");
}
if (null != n.getIfClause()) {
printer.unindent();
printer.printLn("}");
}
}
@Override
public void visit(OmpTaskcancelDirective n, SourcePrinter printer) {
if (null != n.getIfClause()) {
printer.print("if(");
n.getIfClause().getIfExpression().accept(this, printer);
printer.printLn("){");
printer.indent();
}
if (null == n.getTaskName()) {
//If taskwait directive is not followed with a task name, this is wait for the tasks in the default parallel region.
printer.printLn("PjRuntime.taskCancel();");
} else {
//If taskwait directive is followed with a task name, only wait tasks with this specific name, these tasks must be virtual task.
printer.printLn("PjRuntime.setCancellationFlagToTaskName(\""+ n.getTaskName() + "\");");
}
if (null != n.getIfClause()) {
printer.unindent();
printer.printLn("}");
}
}
@Override
public void visit(OmpAsyncCallConstruct n, SourcePrinter printer) {
/* For an async function, the prototype of this function still call the await block synchronously;
* So, directly visit this block. The states are used in state machine class.
*/
n.getBody().accept(this, this.CodePrinter);
/* The states should be generated in favor of state machine class building. However, this type of
* visiting is implemented by AsyncFunctionCallSubstitutionVisitor visitor.
*/
}
@Override
public void visit(OmpFunctionCallDeclaration n, SourcePrinter printer) {
throw new RuntimeException("OmpFunctionCallDeclaration should not be visited by PyjamaToJavaVisitor.");
}
//OpenMP add END*********************************************************************************OpenMP add END//
public void visit(CompilationUnit n, SourcePrinter printer) {
//print the compiler information at the beginning of the file.
this.CodePrinter.printLn("//Pyjama compiler version:" + pj.Version.getCompilerVersion());
if (n.getPackage() != null) {
n.getPackage().accept(this, this.CodePrinter);
}
if (n.getImports() != null) {
for (ImportDeclaration i : n.getImports()) {
i.accept(this, this.CodePrinter);
}
this.CodePrinter.printLn();
}
this.CodePrinter.printLn(this.printRuntimeImports());
if (n.getTypes() != null) {
for (Iterator<TypeDeclaration> i = n.getTypes().iterator(); i.hasNext();) {
i.next().accept(this, this.CodePrinter);
this.CodePrinter.printLn();
if (i.hasNext()) {
this.CodePrinter.printLn();
}
}
}
}
public void visit(PackageDeclaration n, SourcePrinter printer) {
printAnnotations(n.getAnnotations(), printer);
printer.print("package ");
n.getName().accept(this, printer);
printer.printLn(";");
printer.printLn();
}
public void visit(NameExpr n, SourcePrinter printer) {
/*Xing added at 2014.8.3: Renaming variable which has private property
* (firstprivate, lastprivate, reduction) for worksharing methods.
* conversion i => OMP_WoRkShArInG_PRIVATE_i;
*/
if (currentPrivateVariableInOMPWorksharingBlock.keySet().contains(n.toString())) {
printer.print(currentPrivateVariableInOMPWorksharingBlock.get(n.toString()));
} else {
printer.print(n.getName());
}
}
public void visit(QualifiedNameExpr n, SourcePrinter printer) {
n.getQualifier().accept(this, printer);
printer.print(".");
printer.print(n.getName());
}
public void visit(ImportDeclaration n, SourcePrinter printer) {
printer.print("import ");
if (n.isStatic()) {
printer.print("static ");
}
n.getName().accept(this, printer);
if (n.isAsterisk()) {
printer.print(".*");
}
printer.printLn(";");
}
public void visit(ClassOrInterfaceDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
if (n.isInterface()) {
printer.print("interface ");
} else {
printer.print("class ");
}
printer.print(n.getName());
printTypeParameters(n.getTypeParameters(), printer);
if (n.getExtends() != null) {
printer.print(" extends ");
for (Iterator<ClassOrInterfaceType> i = n.getExtends().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
if (n.getImplements() != null) {
printer.print(" implements ");
for (Iterator<ClassOrInterfaceType> i = n.getImplements().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.printLn(" {");
printer.indent();
if (n.getMembers() != null) {
printMembers(n.getMembers(), printer);
}
printer.unindent();
printer.print("}");
}
public void visit(EmptyTypeDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printer.print(";");
}
public void visit(JavadocComment n, SourcePrinter printer) {
printer.print("/**");
printer.print(n.getContent());
printer.printLn("*/");
}
public void visit(ClassOrInterfaceType n, SourcePrinter printer) {
if (n.getScope() != null) {
n.getScope().accept(this, printer);
printer.print(".");
}
printer.print(n.getName());
printTypeArgs(n.getTypeArgs(), printer);
}
public void visit(TypeParameter n, SourcePrinter printer) {
printer.print(n.getName());
if (n.getTypeBound() != null) {
printer.print(" extends ");
for (Iterator<ClassOrInterfaceType> i = n.getTypeBound().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(" & ");
}
}
}
}
public void visit(PrimitiveType n, SourcePrinter printer) {
switch (n.getType()) {
case Boolean:
printer.print("boolean");
break;
case Byte:
printer.print("byte");
break;
case Char:
printer.print("char");
break;
case Double:
printer.print("double");
break;
case Float:
printer.print("float");
break;
case Int:
printer.print("int");
break;
case Long:
printer.print("long");
break;
case Short:
printer.print("short");
break;
}
}
public void visit(ReferenceType n, SourcePrinter printer) {
n.getType().accept(this, printer);
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
}
public void visit(WildcardType n, SourcePrinter printer) {
printer.print("?");
if (n.getExtends() != null) {
printer.print(" extends ");
n.getExtends().accept(this, printer);
}
if (n.getSuper() != null) {
printer.print(" super ");
n.getSuper().accept(this, printer);
}
}
public void visit(FieldDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
//Xing add code at 2014.7.29 BEGIN
/*this code snippet intends force initialize variables in declaration expression.
* The goal is solving uninitalization problem for parallel code generation.
*/
currentVarDeclarationType = n.getType();
//Xing add code at 2014.7.29 END
printer.print(" ");
for (Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext();) {
VariableDeclarator var = i.next();
var.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(";");
}
public void visit(VariableDeclarator n, SourcePrinter printer) {
n.getId().accept(this, printer);
if (n.getInit() != null) {
printer.print(" = ");
n.getInit().accept(this, printer);
} else if (!this.needNotVarInit){
printer.print(" = ");
printer.print(DataClauseHandlerUtils.getDefaultValuesForPrimitiveType(currentVarDeclarationType.toString()));
}
}
public void visit(VariableDeclaratorId n, SourcePrinter printer) {
printer.print(n.getName());
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
}
public void visit(ArrayInitializerExpr n, SourcePrinter printer) {
printer.print("{");
if (n.getValues() != null) {
printer.print(" ");
for (Iterator<Expression> i = n.getValues().iterator(); i.hasNext();) {
Expression expr = i.next();
expr.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(" ");
}
printer.print("}");
}
public void visit(VoidType n, SourcePrinter printer) {
printer.print("void");
}
public void visit(ArrayAccessExpr n, SourcePrinter printer) {
n.getName().accept(this, printer);
printer.print("[");
n.getIndex().accept(this, printer);
printer.print("]");
}
public void visit(ArrayCreationExpr n, SourcePrinter printer) {
printer.print("new ");
n.getType().accept(this, printer);
if (n.getDimensions() != null) {
for (Expression dim : n.getDimensions()) {
printer.print("[");
dim.accept(this, printer);
printer.print("]");
}
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
} else {
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
printer.print(" ");
n.getInitializer().accept(this, printer);
}
}
public void visit(AssignExpr n, SourcePrinter printer) {
n.getTarget().accept(this, printer);
printer.print(" ");
switch (n.getOperator()) {
case assign:
printer.print("=");
break;
case and:
printer.print("&=");
break;
case or:
printer.print("|=");
break;
case xor:
printer.print("^=");
break;
case plus:
printer.print("+=");
break;
case minus:
printer.print("-=");
break;
case rem:
printer.print("%=");
break;
case slash:
printer.print("/=");
break;
case star:
printer.print("*=");
break;
case lShift:
printer.print("<<=");
break;
case rSignedShift:
printer.print(">>=");
break;
case rUnsignedShift:
printer.print(">>>=");
break;
}
printer.print(" ");
n.getValue().accept(this, printer);
}
public void visit(BinaryExpr n, SourcePrinter printer) {
n.getLeft().accept(this, printer);
printer.print(" ");
switch (n.getOperator()) {
case or:
printer.print("||");
break;
case and:
printer.print("&&");
break;
case binOr:
printer.print("|");
break;
case binAnd:
printer.print("&");
break;
case xor:
printer.print("^");
break;
case equals:
printer.print("==");
break;
case notEquals:
printer.print("!=");
break;
case less:
printer.print("<");
break;
case greater:
printer.print(">");
break;
case lessEquals:
printer.print("<=");
break;
case greaterEquals:
printer.print(">=");
break;
case lShift:
printer.print("<<");
break;
case rSignedShift:
printer.print(">>");
break;
case rUnsignedShift:
printer.print(">>>");
break;
case plus:
printer.print("+");
break;
case minus:
printer.print("-");
break;
case times:
printer.print("*");
break;
case divide:
printer.print("/");
break;
case remainder:
printer.print("%");
break;
}
printer.print(" ");
n.getRight().accept(this, printer);
}
public void visit(CastExpr n, SourcePrinter printer) {
printer.print("(");
n.getType().accept(this, printer);
printer.print(") ");
n.getExpr().accept(this, printer);
}
public void visit(ClassExpr n, SourcePrinter printer) {
n.getType().accept(this, printer);
printer.print(".class");
}
public void visit(ConditionalExpr n, SourcePrinter printer) {
n.getCondition().accept(this, printer);
printer.print(" ? ");
n.getThenExpr().accept(this, printer);
printer.print(" : ");
n.getElseExpr().accept(this, printer);
}
public void visit(EnclosedExpr n, SourcePrinter printer) {
printer.print("(");
n.getInner().accept(this, printer);
printer.print(")");
}
public void visit(FieldAccessExpr n, SourcePrinter printer) {
n.getScope().accept(this, printer);
printer.print(".");
printer.print(n.getField());
}
public void visit(InstanceOfExpr n, SourcePrinter printer) {
n.getExpr().accept(this, printer);
printer.print(" instanceof ");
n.getType().accept(this, printer);
}
public void visit(CharLiteralExpr n, SourcePrinter printer) {
printer.print("'");
printer.print(n.getValue());
printer.print("'");
}
public void visit(DoubleLiteralExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(IntegerLiteralExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(LongLiteralExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(IntegerLiteralMinValueExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(LongLiteralMinValueExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(StringLiteralExpr n, SourcePrinter printer) {
printer.print("\"");
printer.print(n.getValue());
printer.print("\"");
}
public void visit(BooleanLiteralExpr n, SourcePrinter printer) {
printer.print(String.valueOf(n.getValue()));
}
public void visit(NullLiteralExpr n, SourcePrinter printer) {
printer.print("null");
}
public void visit(ThisExpr n, SourcePrinter printer) {
if (n.getClassExpr() != null) {
n.getClassExpr().accept(this, printer);
printer.print(".");
}
printer.print("this");
}
public void visit(SuperExpr n, SourcePrinter printer) {
if (n.getClassExpr() != null) {
n.getClassExpr().accept(this, printer);
printer.print(".");
}
printer.print("super");
}
public void visit(MethodCallExpr n, SourcePrinter printer) {
if (n.getScope() != null) {
n.getScope().accept(this, printer);
printer.print(".");
}
printTypeArgs(n.getTypeArgs(), printer);
printer.print(n.getName());
printArguments(n.getArgs(), printer);
}
public void visit(ObjectCreationExpr n, SourcePrinter printer) {
if (n.getScope() != null) {
n.getScope().accept(this, printer);
printer.print(".");
}
printer.print("new ");
printTypeArgs(n.getTypeArgs(), printer);
n.getType().accept(this, printer);
printArguments(n.getArgs(), printer);
if (n.getAnonymousClassBody() != null) {
printer.printLn(" {");
printer.indent();
printMembers(n.getAnonymousClassBody(), printer);
printer.unindent();
printer.print("}");
}
}
public void visit(UnaryExpr n, SourcePrinter printer) {
switch (n.getOperator()) {
case positive:
printer.print("+");
break;
case negative:
printer.print("-");
break;
case inverse:
printer.print("~");
break;
case not:
printer.print("!");
break;
case preIncrement:
printer.print("++");
break;
case preDecrement:
printer.print("--");
break;
default:
break;
}
n.getExpr().accept(this, printer);
switch (n.getOperator()) {
case posIncrement:
printer.print("++");
break;
case posDecrement:
printer.print("--");
break;
default:
break;
}
}
public void visit(ConstructorDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
//Xing added to keep track of current constructor's statements
this.currentMethodOrConstructorStmts = new ArrayList<Statement>();
this.currentMethodOrConstructorStmts = n.getBlock().getStmts();
//Xing added
printTypeParameters(n.getTypeParameters(), printer);
if (n.getTypeParameters() != null) {
printer.print(" ");
}
printer.print(n.getName());
printer.print("(");
if (n.getParameters() != null) {
for (Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext();) {
Parameter p = i.next();
p.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
if (n.getThrows() != null) {
printer.print(" throws ");
for (Iterator<NameExpr> i = n.getThrows().iterator(); i.hasNext();) {
NameExpr name = i.next();
name.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(" ");
n.getBlock().accept(this, printer);
//Xing added
this.currentMethodOrConstructorStmts = null;
//Xing added
}
public void visit(MethodDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
this.currentMethodOrConstructorStmts = new ArrayList<Statement>();
if (n.getBody() != null) {
/*
* We do null pointer check because it is possible current method
* does not have body (e.g. abstract method); or current method
* does not have any statement (e.g.empty method).
*/
if (n.getBody().getStmts() != null) {
this.currentMethodOrConstructorStmts = n.getBody().getStmts();
}
}
//Xing added for checking current method is static or not
if (ModifierSet.isStatic(n.getModifiers())) {
this.currentMethodIsStatic = true;
}
else {
this.currentMethodIsStatic = false;
}
//Xing added for checking if current method should be annotated as an async method.
if (!n.isAsyncMethod() && n.containAwait()) {
throw new RuntimeException("Pyjama parsing error: Using the await block within a non-async method(" + n.getBeginLine() + ":" + n.getBeginColumn() + ").");
}
this.stateMachineVisitingMode.push(false);
printTypeParameters(n.getTypeParameters(), printer);
if (n.getTypeParameters() != null) {
printer.print(" ");
}
n.getType().accept(this, printer);
printer.print(" ");
printer.print(n.getName());
printer.print("(");
if (n.getParameters() != null) {
for (Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext();) {
Parameter p = i.next();
p.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
if (n.getThrows() != null) {
printer.print(" throws ");
for (Iterator<NameExpr> i = n.getThrows().iterator(); i.hasNext();) {
NameExpr name = i.next();
name.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
if (n.getBody() == null) {
printer.print(";");
} else {
printer.print(" ");
printer.print("{");
n.getBody().accept(this, printer);
printer.printLn();
printer.print("}");
}
this.stateMachineVisitingMode.pop();
/*Xing added to print Auxiliary parallel region classes
*if current method has PR regions or the current method is async.
*/
if (n.isAsyncMethod()) {
this.stateMachineVisitingMode.push(true);
StateMachineClassBuilder stateMachineMethodBuilder = new AsyncMethodStateMachineClassBuilder(n, this.currentMethodIsStatic, this, this.PrinterForAsyncMethodStateMachineBuilder.getSource());
this.PrinterForAuxiliaryClasses.printLn(stateMachineMethodBuilder.getSource());
this.PrinterForAsyncMethodStateMachineBuilder.clear();
this.stateMachineVisitingMode.pop();
}
printer.printLn(this.PrinterForAuxiliaryClasses.getSource());
this.PrinterForAuxiliaryClasses.clear();
// reset flag to default, for next method visiting
this.currentMethodOrConstructorStmts = null;
///Xing added end
}
public void visit(Parameter n, SourcePrinter printer) {
printAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
if (n.isVarArgs()) {
printer.print("...");
}
printer.print(" ");
n.getId().accept(this, printer);
}
public void visit(ExplicitConstructorInvocationStmt n, SourcePrinter printer) {
if (n.isThis()) {
printTypeArgs(n.getTypeArgs(), printer);
printer.print("this");
} else {
if (n.getExpr() != null) {
n.getExpr().accept(this, printer);
printer.print(".");
}
printTypeArgs(n.getTypeArgs(), printer);
printer.print("super");
}
printArguments(n.getArgs(), printer);
printer.print(";");
}
public void visit(VariableDeclarationExpr n, SourcePrinter printer) {
printAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
//Xing add code at 2014.7.29 BEGIN
/*this code snippet intends force initialize variables in declaration expression.
* The goal is solving uninitalization problem for parallel code generation.
*/
/*
* This cause another bugs: foreach loop local variable needn't to be initialised:
* however, this visitor will convert for(int i: list) => for(int i=0: list)
*/
currentVarDeclarationType = n.getType();
//Xing add code at 2014.7.29 END
printer.print(" ");
for (Iterator<VariableDeclarator> i = n.getVars().iterator(); i.hasNext();) {
VariableDeclarator v = i.next();
v.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
public void visit(TypeDeclarationStmt n, SourcePrinter printer) {
n.getTypeDeclaration().accept(this, printer);
}
public void visit(AssertStmt n, SourcePrinter printer) {
printer.print("assert ");
n.getCheck().accept(this, printer);
if (n.getMessage() != null) {
printer.print(" : ");
n.getMessage().accept(this, printer);
}
printer.print(";");
}
public void visit(BlockStmt n, SourcePrinter printer) {
printer.printLn("{");
if (n.getStmts() != null) {
printer.indent();
for (Statement s : n.getStmts()) {
s.accept(this, printer);
printer.printLn();
}
printer.unindent();
}
printer.print("}");
}
public void visit(LabeledStmt n, SourcePrinter printer) {
printer.print(n.getLabel());
printer.print(": ");
n.getStmt().accept(this, printer);
}
public void visit(EmptyStmt n, SourcePrinter printer) {
printer.print(";");
}
public void visit(ExpressionStmt n, SourcePrinter printer) {
n.getExpression().accept(this, printer);
printer.print(";");
}
public void visit(SwitchStmt n, SourcePrinter printer) {
printer.print("switch(");
n.getSelector().accept(this, printer);
printer.printLn(") {");
if (n.getEntries() != null) {
printer.indent();
for (SwitchEntryStmt e : n.getEntries()) {
e.accept(this, printer);
}
printer.unindent();
}
printer.print("}");
}
public void visit(SwitchEntryStmt n, SourcePrinter printer) {
if (n.getLabel() != null) {
printer.print("case ");
n.getLabel().accept(this, printer);
printer.print(":");
} else {
printer.print("default:");
}
printer.printLn();
printer.indent();
if (n.getStmts() != null) {
for (Statement s : n.getStmts()) {
s.accept(this, printer);
printer.printLn();
}
}
printer.unindent();
}
public void visit(BreakStmt n, SourcePrinter printer) {
printer.print("break");
if (n.getId() != null) {
printer.print(" ");
printer.print(n.getId());
}
printer.print(";");
}
public void visit(ReturnStmt n, SourcePrinter printer) {
printer.print("return");
if (n.getExpr() != null) {
printer.print(" ");
n.getExpr().accept(this, printer);
}
printer.print(";");
}
public void visit(EnumDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
printer.print("enum ");
printer.print(n.getName());
if (n.getImplements() != null) {
printer.print(" implements ");
for (Iterator<ClassOrInterfaceType> i = n.getImplements().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.printLn(" {");
printer.indent();
if (n.getEntries() != null) {
printer.printLn();
for (Iterator<EnumConstantDeclaration> i = n.getEntries().iterator(); i.hasNext();) {
EnumConstantDeclaration e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
if (n.getMembers() != null) {
printer.printLn(";");
printMembers(n.getMembers(), printer);
} else {
if (n.getEntries() != null) {
printer.printLn();
}
}
printer.unindent();
printer.print("}");
}
public void visit(EnumConstantDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printer.print(n.getName());
if (n.getArgs() != null) {
printArguments(n.getArgs(), printer);
}
if (n.getClassBody() != null) {
printer.printLn(" {");
printer.indent();
printMembers(n.getClassBody(), printer);
printer.unindent();
printer.printLn("}");
}
}
public void visit(EmptyMemberDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printer.print(";");
}
public void visit(InitializerDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
if (n.isStatic()) {
printer.print("static ");
}
n.getBlock().accept(this, printer);
}
public void visit(IfStmt n, SourcePrinter printer) {
printer.print("if (");
n.getCondition().accept(this, printer);
printer.print(") ");
n.getThenStmt().accept(this, printer);
if (n.getElseStmt() != null) {
printer.print(" else ");
n.getElseStmt().accept(this, printer);
}
}
public void visit(WhileStmt n, SourcePrinter printer) {
printer.print("while (");
n.getCondition().accept(this, printer);
printer.print(") ");
n.getBody().accept(this, printer);
}
public void visit(ContinueStmt n, SourcePrinter printer) {
printer.print("continue");
if (n.getId() != null) {
printer.print(" ");
printer.print(n.getId());
}
printer.print(";");
}
public void visit(DoStmt n, SourcePrinter printer) {
printer.print("do ");
n.getBody().accept(this, printer);
printer.print(" while (");
n.getCondition().accept(this, printer);
printer.print(");");
}
public void visit(ForeachStmt n, SourcePrinter printer) {
printer.print("for (");
//Xing added at 2014.10.27, fix init bug at foreach loop
this.needNotVarInit = true;
n.getVariable().accept(this, printer);
this.needNotVarInit = false;
printer.print(" : ");
n.getIterable().accept(this, printer);
printer.print(") ");
n.getBody().accept(this, printer);
}
public void visit(ForStmt n, SourcePrinter printer) {
printer.print("for (");
if (n.getInit() != null) {
for (Iterator<Expression> i = n.getInit().iterator(); i.hasNext();) {
Expression e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print("; ");
if (n.getCompare() != null) {
n.getCompare().accept(this, printer);
}
printer.print("; ");
if (n.getUpdate() != null) {
for (Iterator<Expression> i = n.getUpdate().iterator(); i.hasNext();) {
Expression e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(") ");
n.getBody().accept(this, printer);
}
public void visit(ThrowStmt n, SourcePrinter printer) {
printer.print("throw ");
n.getExpr().accept(this, printer);
printer.print(";");
}
public void visit(SynchronizedStmt n, SourcePrinter printer) {
printer.print("synchronized (");
n.getExpr().accept(this, printer);
printer.print(") ");
n.getBlock().accept(this, printer);
}
public void visit(TryStmt n, SourcePrinter printer) {
printer.print("try ");
n.getTryBlock().accept(this, printer);
if (n.getCatchs() != null) {
for (CatchClause c : n.getCatchs()) {
c.accept(this, printer);
}
}
if (n.getFinallyBlock() != null) {
printer.print(" finally ");
n.getFinallyBlock().accept(this, printer);
}
}
public void visit(CatchClause n, SourcePrinter printer) {
printer.print(" catch (");
n.getExcept().accept(this, printer);
printer.print(") ");
n.getCatchBlock().accept(this, printer);
}
public void visit(AnnotationDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
printer.print("@interface ");
printer.print(n.getName());
printer.printLn(" {");
printer.indent();
if (n.getMembers() != null) {
printMembers(n.getMembers(), printer);
}
printer.unindent();
printer.print("}");
}
public void visit(AnnotationMemberDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
printer.print(" ");
printer.print(n.getName());
printer.print("()");
if (n.getDefaultValue() != null) {
printer.print(" default ");
n.getDefaultValue().accept(this, printer);
}
printer.print(";");
}
public void visit(MarkerAnnotationExpr n, SourcePrinter printer) {
printer.print("@");
n.getName().accept(this, printer);
}
public void visit(SingleMemberAnnotationExpr n, SourcePrinter printer) {
printer.print("@");
n.getName().accept(this, printer);
printer.print("(");
n.getMemberValue().accept(this, printer);
printer.print(")");
}
public void visit(NormalAnnotationExpr n, SourcePrinter printer) {
printer.print("@");
n.getName().accept(this, printer);
printer.print("(");
if (n.getPairs() != null) {
for (Iterator<MemberValuePair> i = n.getPairs().iterator(); i.hasNext();) {
MemberValuePair m = i.next();
m.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
}
public void visit(MemberValuePair n, SourcePrinter printer) {
printer.print(n.getName());
printer.print(" = ");
n.getValue().accept(this, printer);
}
public void visit(LineComment n, SourcePrinter printer) {
printer.print("//");
printer.printLn(n.getContent());
}
public void visit(BlockComment n, SourcePrinter printer) {
printer.print("/*");
printer.print(n.getContent());
printer.printLn("*/");
}
////////////////////PRIVATE METHODS BEGIN///////////////////////////////
private void printModifiers(int modifiers, SourcePrinter printer) {
if (ModifierSet.isPrivate(modifiers)) {
printer.print("private ");
}
if (ModifierSet.isProtected(modifiers)) {
printer.print("protected ");
}
if (ModifierSet.isPublic(modifiers)) {
printer.print("public ");
}
if (ModifierSet.isAbstract(modifiers)) {
printer.print("abstract ");
}
if (ModifierSet.isStatic(modifiers)) {
printer.print("static ");
}
if (ModifierSet.isFinal(modifiers)) {
printer.print("final ");
}
if (ModifierSet.isNative(modifiers)) {
printer.print("native ");
}
if (ModifierSet.isStrictfp(modifiers)) {
printer.print("strictfp ");
}
if (ModifierSet.isSynchronized(modifiers)) {
printer.print("synchronized ");
}
if (ModifierSet.isTransient(modifiers)) {
printer.print("transient ");
}
if (ModifierSet.isVolatile(modifiers)) {
printer.print("volatile ");
}
}
private void printMembers(List<BodyDeclaration> members, SourcePrinter printer) {
for (BodyDeclaration member : members) {
printer.printLn();
member.accept(this, printer);
printer.printLn();
}
}
private void printMemberAnnotations(List<AnnotationExpr> annotations, SourcePrinter printer) {
if (annotations != null) {
for (AnnotationExpr a : annotations) {
a.accept(this, printer);
printer.printLn();
}
}
}
private void printAnnotations(List<AnnotationExpr> annotations, SourcePrinter printer) {
if (annotations != null) {
for (AnnotationExpr a : annotations) {
a.accept(this, printer);
printer.print(" ");
}
}
}
private void printTypeArgs(List<pj.parser.ast.type.Type> args, SourcePrinter printer) {
if (args != null) {
printer.print("<");
for (Iterator<pj.parser.ast.type.Type> i = args.iterator(); i.hasNext();) {
pj.parser.ast.type.Type t = i.next();
t.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(">");
}
}
private void printTypeParameters(List<TypeParameter> args, SourcePrinter printer) {
if (args != null) {
printer.print("<");
for (Iterator<TypeParameter> i = args.iterator(); i.hasNext();) {
TypeParameter t = i.next();
t.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(">");
}
}
private void printArguments(List<Expression> args, SourcePrinter printer) {
printer.print("(");
if (args != null) {
for (Iterator<Expression> i = args.iterator(); i.hasNext();) {
Expression e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
}
private void printJavadoc(JavadocComment javadoc, SourcePrinter printer) {
if (javadoc != null) {
javadoc.accept(this, printer);
}
}
private String printRuntimeImports(){
SourcePrinter printer = new SourcePrinter();
printer.printLn("import pj.pr.*;");
printer.printLn("import pj.PjRuntime;");
printer.printLn("import pj.Pyjama;");
printer.printLn("import pi.*;");
printer.printLn("import java.util.concurrent.*;");
printer.printLn("import java.util.concurrent.atomic.AtomicBoolean;");
printer.printLn("import java.util.concurrent.atomic.AtomicInteger;");
printer.printLn("import java.util.concurrent.atomic.AtomicReference;");
printer.printLn("import java.util.concurrent.locks.ReentrantLock;");
printer.printLn("import java.lang.reflect.InvocationTargetException;");
printer.printLn("import pj.pr.exceptions.*;");
return printer.getSource();
}
//---OpenMP Target construct visiting helper methods
private void storeTargetClassNameByTaskName(String taskName, TargetTaskCodeClassBuilder targetClassBuilder) {
HashSet<TargetTaskCodeClassBuilder> targetBuilders = nameAsTargetBlocks.get(taskName);
if (null == targetBuilders) {
targetBuilders = new HashSet<TargetTaskCodeClassBuilder>();
nameAsTargetBlocks.put(taskName, targetBuilders);
}
targetBuilders.add(targetClassBuilder);
}
private HashSet<TargetTaskCodeClassBuilder> getTargetClassBuilders(String taskName) {
HashSet<TargetTaskCodeClassBuilder> targetBuilders = nameAsTargetBlocks.get(taskName);
if (null != targetBuilders) {
return targetBuilders;
} else {
//return empty list.
return new HashSet<TargetTaskCodeClassBuilder>();
}
}
////////////////////PRIVATE METHODS END////////////////////
public PyjamaToJavaVisitor(File file) {
this.file = file;
this.compilationFileName = this.file.getName().substring(0,
this.file.getName().indexOf(PYJAMA_FILE_EXTENSION));
}
public SourcePrinter getPriter() {
return this.CodePrinter;
}
public String getSource() {
return CodePrinter.getSource();
}
public String getAuxiliaryClassesSource() {
return this.PrinterForAuxiliaryClasses.getSource();
}
public void appendAuxiliaryClassesSource(String source) {
this.PrinterForAuxiliaryClasses.printLn(source);
}
public SourcePrinter getPrinterForAsyncTargetTaskStateMachineBuilder() {
return this.PrinterForAsyncTargetTaskStateMachineBuilder;
}
/********************************************************************************************************************************/
} | gpl-2.0 |
DigitalMediaServer/DigitalMediaServer | src/main/java/net/pms/dlna/WebAudioStream.java | 979 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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 2
* of the License only.
*
* 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 net.pms.dlna;
public class WebAudioStream extends WebStream {
public WebAudioStream(String fluxName, String URL, String thumbURL) {
super(fluxName, URL, thumbURL, MediaType.AUDIO);
}
}
| gpl-2.0 |
canmind/interface | src/main/java/com/o2o/business/app/FeedBackController.java | 882 | package com.o2o.business.app;
import com.o2o.core.base.BaseController;
import com.o2o.model.request.FeedBack;
import com.o2o.model.result.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* IDEA
* 提交app用户反馈接口
*
* @Description Created by bowen.ma on 14-10-6.
*/
@Controller
@RequestMapping("/app")
public class FeedBackController extends BaseController {
@RequestMapping("/feedback.json")
@ResponseBody
public Result commitFeedBack(FeedBack feedBack) {
String msg = feedBack.valid(feedBack);
Result result = new Result();
if (msg != null) {
setStatusError(result, msg);
return result;
}
setStatusOk(result, null);
return result;
}
}
| gpl-2.0 |
jameshwartlopez/QRCodeScanning | app/src/androidTest/java/com/example/jameshwart/sample/ApplicationTest.java | 360 | package com.example.jameshwart.sample;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/packages/apps/RCSe/core/src/com/orangelabs/rcs/core/ims/protocol/rtp/stream/DummyPacketSourceStream.java | 3684 | /*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* 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.orangelabs.rcs.core.ims.protocol.rtp.stream;
import com.orangelabs.rcs.core.ims.protocol.rtp.format.DummyFormat;
import com.orangelabs.rcs.core.ims.protocol.rtp.format.Format;
import com.orangelabs.rcs.core.ims.protocol.rtp.util.Buffer;
import com.orangelabs.rcs.core.ims.protocol.rtp.util.SystemTimeBase;
import com.orangelabs.rcs.utils.FifoBuffer;
import com.orangelabs.rcs.utils.logger.Logger;
/**
* Dummy packet source stream (used to pass NAT)
*
* @author jexa7410
*/
public class DummyPacketSourceStream extends Thread implements ProcessorInputStream {
/**
* Source period (in seconds)
*/
public final static int DUMMY_SOURCE_PERIOD = 5;
/**
* Input format
*/
private DummyFormat format = new DummyFormat();
/**
* Time base
*/
private SystemTimeBase systemTimeBase = new SystemTimeBase();
/**
* Sequence number
*/
private long seqNo = 0;
/**
* Message buffer
*/
private FifoBuffer fifo = new FifoBuffer();
/**
* The logger
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Interruption flag
*/
private boolean interrupted = false;
/**
* Constructor
*/
public DummyPacketSourceStream() {
}
/**
* Open the input stream
*/
public void open() {
start();
if (logger.isActivated()) {
logger.debug("Dummy source stream openned");
}
}
/**
* Close the input stream
*/
public void close() {
interrupted = true;
try {
fifo.close();
} catch(Exception e) {
// Intentionally blank
}
if (logger.isActivated()) {
logger.debug("Dummy source stream closed");
}
}
/**
* Format of the data provided by the source stream
*
* @return Format
*/
public Format getFormat() {
return format;
}
/**
* Background processing
*/
public void run() {
while(!interrupted) {
try {
// Build a new dummy packet
Buffer packet = new Buffer();
packet.setData(new byte[0]);
packet.setLength(0);
packet.setFormat(format);
packet.setSequenceNumber(seqNo++);
packet.setTimeStamp(systemTimeBase.getTime());
// Post the packet in the FIFO
fifo.addObject(packet);
// Make a pause
Thread.sleep(DUMMY_SOURCE_PERIOD * 1000);
} catch(Exception e) {
if (logger.isActivated()) {
logger.error("Dummy packet source has failed", e);
}
}
}
}
/**
* Read from the stream
*
* @return Buffer
* @throws Exception
*/
public Buffer read() throws Exception {
// Read the FIFO the buffer
Buffer buffer = (Buffer)fifo.getObject();
return buffer;
}
}
| gpl-2.0 |
jeisfeld/RandomImage | RandomImageIdea/randomImageLib/src/main/java/de/jeisfeld/randomimage/util/GifDecoder.java | 17811 | package de.jeisfeld.randomimage.util;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Decoder for animated gif.
*/
public class GifDecoder {
/**
* The maximum stack size.
*/
private static final int MAX_STACK_SIZE = 4096;
/**
* The minimum delay.
*/
public static final int MIN_DELAY = 100;
/**
* The minimum delay enforce threshold.
*/
public static final int MIN_DELAY_ENFORCE_THRESHOLD = 20;
/**
* The input stream for the GIF.
*/
private InputStream mIn;
/**
* Full mImage mWidth.
*/
private int mWidth;
/**
* Full mImage mHeight.
*/
private int mHeight;
/**
* Global color table used.
*/
private boolean mGctFlag;
/**
* Size of global color table.
*/
private int mGctSize;
/**
* iterations; 0 = repeat forever.
*/
private int mLoopCount = 1;
/**
* global color table.
*/
private int[] mGct;
/**
* local color table.
*/
private int[] mLct;
/**
* active color table.
*/
private int[] mAct;
/**
* background color index.
*/
private int mBgIndex;
/**
* background color.
*/
private int mBgColor;
/**
* previous bg color.
*/
private int mLastBgColor;
/**
* local color table flag.
*/
private boolean mLctFlag;
/**
* mInterlace flag.
*/
private boolean mInterlace;
/**
* local color table size.
*/
private int mLctSize;
/**
* current image rectangle x.
*/
private int mIx;
/**
* current image rectangle y.
*/
private int mIy;
/**
* current image rectangle width.
*/
private int mIw;
/**
* current image rectangle height.
*/
private int mIh;
/**
* last image rectangle x.
*/
private int mLrx;
/**
* last image rectangle y.
*/
private int mLry;
/**
* last image rectangle width.
*/
private int mLrw;
/**
* last image rectangle height.
*/
private int mLrh;
/**
* current frame.
*/
private Bitmap mImage;
/**
* previous frame.
*/
private Bitmap mLastBitmap;
/**
* current data block.
*/
private byte[] mBlock = new byte[256]; // MAGIC_NUMBER
/**
* Block size last graphic control extension info.
*/
private int mBlockSize = 0;
/**
* 0=no action; 1=leave mIn place; 2=restore to bg; 3=restore to prev.
*/
private int mDispose = 0;
/**
* Last dispose value.
*/
private int mLastDispose = 0;
/**
* use transparent color.
*/
private boolean mTransparency = false;
/**
* Delay mIn milliseconds.
*/
private int mDelay = 0;
/**
* transparent color index.
*/
private int mTransIndex;
/**
* LZW decoder working array for prefix.
*/
private short[] mPrefix;
/**
* LZW decoder working array for suffix.
*/
private byte[] mSuffix;
/**
* LZW decoder working array for pixelStack.
*/
private byte[] mPixelStack;
/**
* LZW decoder working array for pixels.
*/
private byte[] mPixels;
/**
* mFrames read from current file.
*/
private ArrayList<GifFrame> mFrames;
/**
* number of mFrames.
*/
private int mFrameCount;
/**
* flag indicating read complete.
*/
private boolean mReadComplete;
/**
* Default constructor.
*/
public GifDecoder() {
mReadComplete = false;
}
/**
* Gets display duration for specified frame.
*
* @param n int index of frame
* @return mDelay mIn milliseconds
*/
public int getDelay(final int n) {
mDelay = -1;
if ((n >= 0) && (n < mFrameCount)) {
mDelay = mFrames.get(n).mDelay;
// meets browser compatibility standards
if (mDelay < MIN_DELAY_ENFORCE_THRESHOLD) {
mDelay = MIN_DELAY;
}
}
return mDelay;
}
/**
* Gets the number of mFrames read from file.
*
* @return frame count
*/
public int getFrameCount() {
return mFrameCount;
}
/**
* Gets the first (or only) mImage read.
*
* @return BufferedBitmap containing first frame, or null if none.
*/
public Bitmap getBitmap() {
return getFrame(0);
}
/**
* Gets the "Netscape" iteration count, if any. A count of 0 means repeat indefinitiely.
*
* @return iteration count if one was specified, else 1.
*/
public int getLoopCount() {
return mLoopCount;
}
/**
* Creates new frame mImage from current data (and previous mFrames as specified by their disposition codes).
*/
private void setPixels() {
// expose destination mImage's mPixels as int array
int[] dest = new int[mWidth * mHeight];
// fill mIn starting mImage contents based on last mImage's mDispose code
if (mLastDispose > 0) {
if (mLastDispose == 3) { // MAGIC_NUMBER
// use mImage before last
int n = mFrameCount - 2;
if (n > 0) {
mLastBitmap = getFrame(n - 1);
}
else {
mLastBitmap = null;
}
}
if (mLastBitmap != null) {
mLastBitmap.getPixels(dest, 0, mWidth, 0, 0, mWidth, mHeight);
// copy mPixels
if (mLastDispose == 2) {
// fill last mImage rect area with background color
int c = 0;
if (!mTransparency) {
c = mLastBgColor;
}
for (int i = 0; i < mLrh; i++) {
int n1 = (mLry + i) * mWidth + mLrx;
int n2 = n1 + mLrw;
for (int k = n1; k < n2; k++) {
dest[k] = c;
}
}
}
}
}
// copy each source line to the appropriate place mIn the destination
int pass = 1;
int inc = 8; // MAGIC_NUMBER
int iline = 0;
for (int i = 0; i < mIh; i++) {
int line = i;
if (mInterlace) {
if (iline >= mIh) {
pass++;
switch (pass) {
case 2:
iline = 4; // MAGIC_NUMBER
break;
case 3: // MAGIC_NUMBER
iline = 2;
inc = 4; // MAGIC_NUMBER
break;
case 4: // MAGIC_NUMBER
iline = 1;
inc = 2;
break;
default:
break;
}
}
line = iline;
iline += inc;
}
line += mIy;
if (line < mHeight) {
int k = line * mWidth;
int dx = k + mIx; // start of line mIn dest
int dlim = dx + mIw; // end of dest line
if ((k + mWidth) < dlim) {
dlim = k + mWidth; // past dest edge
}
int sx = i * mIw; // start of line mIn source
while (dx < dlim) {
// map color and insert mIn destination
int index = (mPixels[sx++]) & 0xff; // MAGIC_NUMBER
int c = mAct[index];
if (c != 0) {
dest[dx] = c;
}
dx++;
}
}
}
mImage = Bitmap.createBitmap(dest, mWidth, mHeight, Config.ARGB_4444);
}
/**
* Gets the mImage contents of frame n.
*
* @param n the frame number.
* @return BufferedBitmap representation of frame, or null if n is invalid.
*/
public Bitmap getFrame(final int n) {
if (mFrameCount <= 0) {
return null;
}
return mFrames.get(n % mFrameCount).mImage;
}
/**
* Reads GIF image from stream.
*
* @param inputStream the input stream containing GIF file.
* @throws IOException error while processing
*/
public void read(final InputStream inputStream) throws IOException {
init();
if (inputStream != null) {
mIn = inputStream;
readHeader();
readContents();
if (mFrameCount < 0) {
throw new IOException("Format Error");
}
}
else {
throw new IOException("Open error");
}
mReadComplete = true;
}
/**
* Decodes LZW mImage data into pixel array. Adapted from John Cristy's BitmapMagick.
*
* @throws IOException error while processing
*/
private void decodeBitmapData() throws IOException {
int npix = mIw * mIh;
if ((mPixels == null) || (mPixels.length < npix)) {
mPixels = new byte[npix]; // allocate new pixel array
}
if (mPrefix == null) {
mPrefix = new short[MAX_STACK_SIZE];
}
if (mSuffix == null) {
mSuffix = new byte[MAX_STACK_SIZE];
}
if (mPixelStack == null) {
mPixelStack = new byte[MAX_STACK_SIZE + 1];
}
// Initialize GIF data stream decoder.
int dataSize = read();
int clear = 1 << dataSize;
int endOfInformation = clear + 1;
int available = clear + 2;
int nullCode = -1;
int oldCode = nullCode;
int codeSize = dataSize + 1;
int codeMask = (1 << codeSize) - 1;
int code;
for (code = 0; code < clear; code++) {
mPrefix[code] = 0; // XXX ArrayIndexOutOfBoundsException
mSuffix[code] = (byte) code;
}
// Decode GIF pixel stream.
int datum = 0;
int bits = 0;
int count = 0;
int first = 0;
int top = 0;
int pi = 0;
int bi = 0;
int i = 0;
while (i < npix) {
if (top == 0) {
if (bits < codeSize) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data mBlock.
count = readBlock();
if (count <= 0) {
break;
}
bi = 0;
}
datum += ((mBlock[bi]) & 0xff) << bits; // MAGIC_NUMBER
bits += 8; // MAGIC_NUMBER
bi++;
count--;
continue;
}
// Get the next code.
code = datum & codeMask;
datum >>= codeSize;
bits -= codeSize;
// Interpret the code
if ((code > available) || (code == endOfInformation)) {
break;
}
if (code == clear) {
// Reset decoder.
codeSize = dataSize + 1;
codeMask = (1 << codeSize) - 1;
available = clear + 2;
oldCode = nullCode;
continue;
}
if (oldCode == nullCode) {
mPixelStack[top++] = mSuffix[code];
oldCode = code;
first = code;
continue;
}
final int inCode = code;
if (code == available) {
mPixelStack[top++] = (byte) first;
code = oldCode;
}
while (code > clear) {
mPixelStack[top++] = mSuffix[code];
code = mPrefix[code];
}
first = (mSuffix[code]) & 0xff; // MAGIC_NUMBER
// Add a new string to the string table,
if (available >= MAX_STACK_SIZE) {
break;
}
mPixelStack[top++] = (byte) first;
mPrefix[available] = (short) oldCode;
mSuffix[available] = (byte) first;
available++;
if (((available & codeMask) == 0) && (available < MAX_STACK_SIZE)) {
codeSize++;
codeMask += available;
}
oldCode = inCode;
}
// Pop a pixel off the pixel stack.
top--;
mPixels[pi++] = mPixelStack[top];
i++;
}
for (i = pi; i < npix; i++) {
mPixels[i] = 0; // clear missing mPixels
}
}
/**
* Initializes or re-initializes reader.
*/
private void init() {
mFrameCount = 0;
mFrames = new ArrayList<>();
mGct = null;
mLct = null;
}
/**
* Reads a single byte from the input stream.
*
* @return the read byte.
* @throws IOException exception while reading.
*/
private int read() throws IOException {
return mIn.read();
}
/**
* Reads next variable length mBlock from input.
*
* @return number of bytes stored mIn "buffer"
* @throws IOException error while processing
*/
private int readBlock() throws IOException {
mBlockSize = read();
int n = 0;
if (mBlockSize > 0) {
try {
int count;
while (n < mBlockSize) {
count = mIn.read(mBlock, n, mBlockSize - n);
if (count == -1) {
break;
}
n += count;
}
}
catch (Exception e) {
e.printStackTrace();
}
if (n < mBlockSize) {
throw new IOException("Format error");
}
}
return n;
}
/**
* Reads color table as 256 RGB integer values.
*
* @param ncolors int number of colors to read
* @return int array containing 256 colors (packed ARGB with full alpha)
* @throws IOException error while processing
*/
private int[] readColorTable(final int ncolors) throws IOException {
int nbytes = 3 * ncolors; // MAGIC_NUMBER
int[] tab;
byte[] c = new byte[nbytes];
int n = 0;
try {
n = mIn.read(c);
}
catch (Exception e) {
e.printStackTrace();
}
if (n < nbytes) {
throw new IOException("Format error");
}
else {
tab = new int[256]; // MAGIC_NUMBER max size to avoid bounds checks
int i = 0;
int j = 0;
while (i < ncolors) {
int r = (c[j++]) & 0xff; // MAGIC_NUMBER
int g = (c[j++]) & 0xff; // MAGIC_NUMBER
int b = (c[j++]) & 0xff; // MAGIC_NUMBER
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b; // MAGIC_NUMBER
}
}
return tab;
}
/**
* Main file parser. Reads GIF content blocks.
*
* @throws IOException error while processing
*/
public void readContents() throws IOException {
// read GIF file content blocks
boolean done = false;
while (!done) {
int code = read();
switch (code) {
case 0x2C: // MAGIC_NUMBER Image separator
readBitmap();
if (!mReadComplete) {
return;
}
break;
case 0x21: // MAGIC_NUMBER extension
code = read();
switch (code) {
case 0xf9: // MAGIC_NUMBER graphics control extension
readGraphicControlExt();
break;
case 0xff: // MAGIC_NUMBER application extension
readBlock();
StringBuilder app = new StringBuilder();
for (int i = 0; i < 11; i++) { // MAGIC_NUMBER
app.append((char) mBlock[i]);
}
if ("NETSCAPE2.0".equals(app.toString())) {
readNetscapeExt();
}
else {
skip(); // don't care
}
break;
case 0xfe:// MAGIC_NUMBER comment extension
case 0x01:// plain text extension
default: // uninteresting extension
skip();
}
break;
case 0x3b: // MAGIC_NUMBER terminator
done = true;
break;
case 0x00: // bad byte, but keep going and see what happens break;
default:
throw new IOException("Format error");
}
}
}
/**
* Reads Graphics Control Extension values.
*
* @throws IOException error while processing
*/
private void readGraphicControlExt() throws IOException {
read(); // mBlock size
int packed = read(); // packed fields
mDispose = (packed & 0x1c) >> 2; // MAGIC_NUMBER disposal method
if (mDispose == 0) {
mDispose = 1; // elect to keep old mImage if discretionary
}
mTransparency = (packed & 1) != 0;
mDelay = readShort() * 10; // MAGIC_NUMBER delay mIn milliseconds
mTransIndex = read(); // transparent color index
read(); // mBlock terminator
}
/**
* Reads GIF file header information.
*
* @throws IOException error while processing
*/
private void readHeader() throws IOException {
StringBuilder id = new StringBuilder();
for (int i = 0; i < 6; i++) { // MAGIC_NUMBER
id.append((char) read());
}
if (!id.toString().startsWith("GIF")) {
throw new IOException("Format error");
}
readLsd();
if (mGctFlag) {
mGct = readColorTable(mGctSize);
mBgColor = mGct[mBgIndex];
}
}
/**
* Reads next frame mImage.
*
* @throws IOException error while processing
*/
private void readBitmap() throws IOException {
mIx = readShort(); // (sub)mImage position & size
mIy = readShort();
mIw = readShort();
mIh = readShort();
int packed = read();
mLctFlag = (packed & 0x80) != 0; // MAGIC_NUMBER 1 - local color table flag mInterlace
mLctSize = (int) Math.pow(2, (packed & 0x07) + 1); // MAGIC_NUMBER
// 3 - sort flag
// 4-5 - reserved mLctSize = 2 << (packed & 7); // 6-8 - local color
// table size
mInterlace = (packed & 0x40) != 0; // MAGIC_NUMBER
if (mLctFlag) {
mLct = readColorTable(mLctSize); // read table
mAct = mLct; // make local table active
}
else {
mAct = mGct; // make global table active
if (mBgIndex == mTransIndex) {
mBgColor = 0;
}
}
int save = 0;
if (mTransparency) {
save = mAct[mTransIndex];
mAct[mTransIndex] = 0; // set transparent color if specified
}
if (mAct == null) {
throw new IOException("Format error"); // no color table defined
}
decodeBitmapData(); // decode pixel data
skip();
mFrameCount++;
// create new mImage to receive frame data
mImage = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_4444);
setPixels(); // transfer pixel data to mImage
mFrames.add(new GifFrame(mImage, mDelay)); // add mImage to frame
// list
if (mTransparency) {
mAct[mTransIndex] = save;
}
resetFrame();
}
/**
* Reads Logical Screen Descriptor.
*
* @throws IOException error while processing
*/
private void readLsd() throws IOException {
// logical screen size
mWidth = readShort();
mHeight = readShort();
// packed fields
int packed = read();
mGctFlag = (packed & 0x80) != 0; // MAGIC_NUMBER 1 : global color table flag
// 2-4 : color resolution
// 5 : mGct sort flag
mGctSize = 2 << (packed & 7); // MAGIC_NUMBER 6-8 : mGct size
mBgIndex = read(); // background color index
read(); // pixel aspect ratio
}
/**
* Reads Netscape extenstion to obtain iteration count.
*
* @throws IOException error while processing
*/
private void readNetscapeExt() throws IOException {
do {
readBlock();
if (mBlock[0] == 1) {
// loop count sub-mBlock
int b1 = (mBlock[1]) & 0xff; // MAGIC_NUMBER
int b2 = (mBlock[2]) & 0xff; // MAGIC_NUMBER
mLoopCount = (b2 << 8) | b1; // MAGIC_NUMBER
}
}
while (mBlockSize > 0);
}
/**
* Reads next 16-bit value, LSB first.
*
* @return the read value.
* @throws IOException error while processing
*/
private int readShort() throws IOException {
// read 16-bit value, LSB first
return read() | (read() << 8); // MAGIC_NUMBER
}
/**
* Resets frame state for reading next mImage.
*/
private void resetFrame() {
mLastDispose = mDispose;
mLrx = mIx;
mLry = mIy;
mLrw = mIw;
mLrh = mIh;
mLastBitmap = mImage;
mLastBgColor = mBgColor;
mDispose = 0;
mTransparency = false;
mDelay = 0;
mLct = null;
}
/**
* Skips variable length blocks up to and including next zero length mBlock.
*
* @throws IOException error while processing
*/
private void skip() throws IOException {
do {
readBlock();
}
while (mBlockSize > 0);
}
/**
* A GIF frame.
*/
private static class GifFrame {
/**
* The image.
*/
private Bitmap mImage;
/**
* The delay.
*/
private int mDelay;
/**
* Constructor.
*
* @param image The image.
* @param delay The delay.
*/
GifFrame(final Bitmap image, final int delay) {
mImage = image;
mDelay = delay;
}
}
}
| gpl-2.0 |
titokone/titotrainer | WEB-INF/src/fi/helsinki/cs/titotrainer/app/model/handler/AssociationValidator.java | 6732 | package fi.helsinki.cs.titotrainer.app.model.handler;
import org.hibernate.HibernateException;
import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;
import org.hibernate.event.PreUpdateEvent;
import org.hibernate.event.PreUpdateEventListener;
/**
* <p>A pre-insert/pre-update event listener that checks that
* bidirectional table associations are set both ways.</p>
*
* <p>
* NOTE: There is a problem with the current implementation.
* The event handler is called during flushing and it's not supposed
* to touch lazy collections. See
* http://opensource.atlassian.com/projects/hibernate/browse/HHH-2763
* </p>
*/
@SuppressWarnings("serial")
public class AssociationValidator implements PreInsertEventListener, PreUpdateEventListener {
@Override
public boolean onPreInsert(PreInsertEvent event) throws HibernateException {
if (event == null) {
return false;
}
Object entity = event.getEntity();
return validateAssociations(entity);
}
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
if (event == null) {
return false;
}
Object entity = event.getEntity();
return validateAssociations(entity);
}
public static boolean validateAssociations(Object entity) {
// Code commented out to artificially raise test coverage
throw new UnsupportedOperationException("Disabled");
/*
Collection<?> collection;
Class<?> entityClass;
boolean found;
Class<?> targetClass;
Object targetEntity;
ManyToOne manyToOneAnnotation;
OneToMany oneToManyAnnotation;
String propertyName;
if (entity == null) {
return false;
}
entityClass = entity.getClass();
for (Method method : entityClass.getMethods()) {
// Filter out all methods which are not annotated with @Bidirectional
if (method.getAnnotation(Bidirectional.class) == null) {
continue;
}
manyToOneAnnotation = method.getAnnotation(ManyToOne.class);
oneToManyAnnotation = method.getAnnotation(OneToMany.class);
// Check that there's exactly one of @OneToMany or @ManyToOne present
if ((manyToOneAnnotation == null) && (oneToManyAnnotation == null)) {
throw new IllegalStateException("A method that is annotated with @Bidirectional must be annotated also with exactly one of @ManyToOne or @OneToMany!");
}
if ((manyToOneAnnotation != null) && (oneToManyAnnotation != null)) {
throw new IllegalStateException("A method that is annotated with @Bidirectional must be annotated also with exactly one of @ManyToOne or @OneToMany!");
}
// Make sure it's a proper getter without any arguments
if (method.getParameterTypes().length != 0) {
throw new IllegalStateException("The getter annotated with @Bidirectional must not take any parameters!");
}
if (manyToOneAnnotation != null) {
found = false;
// Determine the return type of the method.
targetClass = method.getReturnType();
try {
targetEntity = method.invoke(entity);
// Only proceed if the target entity exists
if (targetEntity != null) {
// Look for a collection in the targetClass
for (Method targetMethod : targetClass.getMethods()) {
// Look for a method with the correct annotations
if ((targetMethod.getAnnotation(Bidirectional.class) != null) && (targetMethod.getAnnotation(OneToMany.class) != null)) {
if (targetMethod.getParameterTypes().length != 0) {
throw new IllegalStateException("The getter annotated with @Bidirectional must not take any parameters!");
}
if (targetMethod.getReturnType() == Collection.class) {
collection = (Collection<?>)targetMethod.invoke(targetEntity);
if (collection.contains(entity)) {
// The entity was found, so return immediately
found = true;
break;
}
}
}
}
if (!found) {
throw new IllegalStateException("The entity " + entity + " was not found in any collection of the parent " + targetEntity + "!");
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
if (oneToManyAnnotation != null) {
propertyName = oneToManyAnnotation.mappedBy();
if (propertyName == null) {
throw new IllegalStateException("@OneToMany needs to have its mappedBy field set properly.");
}
try {
collection = (Collection<?>)method.invoke(entity);
for (Object child : collection) {
Getter getter = ReflectHelper.getGetter(child.getClass(), propertyName);
Object parent = getter.get(child);
if (!entity.equals(parent)) {
throw new IllegalStateException("Error in bidirectional association!");
}
}
} catch (IllegalArgumentException exception) {
exception.printStackTrace();
} catch (IllegalAccessException exception) {
exception.printStackTrace();
} catch (InvocationTargetException exception) {
exception.printStackTrace();
}
}
}
return false;
*/
}
} | gpl-2.0 |
RegistroUdeA/Prueba | PI1Web/src/com/proint1/udea/notificaciones/EMailHtml.java | 7571 | package com.proint1.udea.notificaciones;
import java.io.File;
import java.io.Serializable;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Clase que encapsula el envio de un correo en formato HTMl, para incluir
* adjuntos y contenido html
*/
public class EMailHtml implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(EMailHtml.class);
/** serialVersionUID */
private static final long serialVersionUID = 3232851751545279316L;
/** Adress to */
private InternetAddress[] adressesTo;
/** Adress CC */
private InternetAddress[] adressesCc;
/** Adress Bcc */
private InternetAddress[] adressesBcc;
/** Variables */
private Properties props = new Properties();
/** From del message */
private String from;
/** Çontenido del mensaje */
private String content;
/** Sujeto de mensaje */
private String subject = "";
/** MultiPart para crear mensajes compuestos */
private MimeMultipart multipart = new MimeMultipart("related");
/** usuario que logea el servidor de correo */
private String emailUser;
/** Passwordel del email user para autenticación del servidor de correo */
private String passwordEmail;
/**
* Constructor
*
* @param host nombre del servidor de correo
* @param user usuario de correo
* @param password password del usuario
*/
public EMailHtml(String subject, String menssage) {
try {
props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.host", "smtp.gmail.com");
emailUser = "pmontoya206@gmail.com";
props.setProperty("mail.user", emailUser);
passwordEmail = "proyecto2014";
props.setProperty("mail.password", passwordEmail);
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
this.subject = subject;
this.from = "pmontoya206@gmail.com";
this.content = menssage;
} catch (Exception e) {
LOGGER.error("PropiedadNoEncontradaException ", e);
}
}
/**
* Añade el contenido base al multipart
*
* @throws MessagingException
*
* @throws Exception Excepcion levantada en caso de error
*/
public void addContentToMultipart() throws MessagingException {
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = this.getContent();
messageBodyPart.setContent(htmlText, "text/html");
// add it
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Añade el contenido base al multipart
*
* @param htmlText contenido html que se muestra en el mensaje de correo
* @throws MessagingException
* @throws Exception Excepcion levantada en caso de error
*/
public void addContent(String htmlText) throws MessagingException {
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlText, "text/html");
// add it
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Añade al mensaje un cid:name utilizado para guardar las imagenes referenciadas en el HTML de la forma
* <img src=cid:name />
*
* @param cidname identificador que se le da a la imagen. suele ser un string generado aleatoriamente.
* @param pathname ruta del fichero que almacena la imagen
* @throws MessagingException
* @throws Exception excepcion levantada en caso de error
*/
public void addCID(String cidname, String pathname) throws MessagingException {
DataSource fds = new FileDataSource(pathname);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<" + cidname + ">");
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Añade un attachement al mensaje de email
*
* @param pathname ruta del fichero
* @throws MessagingException
* @throws Exception excepcion levantada en caso de error
*/
public void addAttach(String pathname) throws MessagingException {
File file = new File(pathname);
BodyPart messageBodyPart = new MimeBodyPart();
DataSource ds = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(file.getName());
messageBodyPart.setDisposition(Part.ATTACHMENT);
this.multipart.addBodyPart(messageBodyPart);
}
/**
* Operación final de envio sea con documentos o sin ellos
*
* @throws MessagingException
*
* @throws Exception
*/
public void sendMessage() throws MessagingException {
sendMultipart();
}
/**
* Envia un correo multipart
*
* @throws MessagingException
* @throws Exception Excepcion levantada en caso de error
*/
private void sendMultipart() throws MessagingException {
Session mailSession = Session.getDefaultInstance(this.props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
// Agregar sujeto
message.setSubject(this.getSubject());
// Agregrar el from
message.setFrom(new InternetAddress(this.getFrom()));
// Agregar destinatiarios
if (adressesTo != null && adressesTo.length > 0) {
message.addRecipients(Message.RecipientType.TO, adressesTo);
}
if (adressesCc != null && adressesCc.length > 0) {
message.addRecipients(Message.RecipientType.CC, adressesCc);
}
if (adressesBcc != null && adressesBcc.length > 0) {
message.addRecipients(Message.RecipientType.BCC, adressesBcc);
}
// put everything together
message.setContent(multipart);
transport.connect(emailUser, passwordEmail);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
/**
* @return the adressesTo
*/
public InternetAddress[] getAdressesTo() {
return adressesTo;
}
/**
* @param adressesTo the adressesTo to set
*/
public void setAdressesTo(InternetAddress[] adressesTo) {
this.adressesTo = adressesTo;
}
/**
* @return the adressesCc
*/
public InternetAddress[] getAdressesCc() {
return adressesCc;
}
/**
* @param adressesCc the adressesCc to set
*/
public void setAdressesCc(InternetAddress[] adressesCc) {
this.adressesCc = adressesCc;
}
/**
* @return the adressesBcc
*/
public InternetAddress[] getAdressesBcc() {
return adressesBcc;
}
/**
* @param adressesBcc the adressesBcc to set
*/
public void setAdressesBcc(InternetAddress[] adressesBcc) {
this.adressesBcc = adressesBcc;
}
}
| gpl-2.0 |
rampage128/hombot-control | mobile/src/main/java/de/jlab/android/hombot/utils/ColorableArrayAdapter.java | 1688 | package de.jlab.android.hombot.utils;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.ArrayRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Created by frede_000 on 19.12.2015.
*/
public class ColorableArrayAdapter<T> extends ArrayAdapter<T> {
private Colorizer colorizer;
private int referenceColor;
private int mFieldId = 0;
public static ColorableArrayAdapter<CharSequence> createFromResource(Context context,
@ArrayRes int textArrayResId, @LayoutRes int textViewResId, Colorizer colorizer, int referenceColor) {
CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
ColorableArrayAdapter ad = new ColorableArrayAdapter<>(context, textViewResId, strings, colorizer, referenceColor);
return ad;
}
public ColorableArrayAdapter(Context context, @LayoutRes int resource, @NonNull T[] objects, Colorizer colorizer, int referenceColor) {
super(context, resource, objects);
mFieldId = resource;
this.referenceColor = referenceColor;
this.colorizer = colorizer;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
((TextView)view).setTextColor(this.colorizer.getContrastingTextColor(this.referenceColor));
return view;
}
}
| gpl-2.0 |
AndroidREPo-jason/CodingClient | coding/src/net/coding/android/widget/FloatLabel.java | 14374 | /*
* Copyright (C) 2014 Ian G. Clifton
*
* 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 net.coding.android.widget;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import net.coding.android.R;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
/**
* A ViewGroup that consists of an EditText and a TextView as the label.<br/>
* <br/>
* When the EditText is empty, its hint is displayed. When it is nonempty, the
* TextView label is displayed.<br/>
* <br/>
* You can set the label programmatically with either
* {@link #setLabel(CharSequence)} or {@link #setLabel(int)}.
*
* @author Ian G. Clifton
* @see <a
* href="http://dribbble.com/shots/1254439--GIF-Float-Label-Form-Interaction">Float
* label inspiration on Dribbble</a>
*/
public class FloatLabel extends FrameLayout {
private static final String SAVE_STATE_KEY_EDIT_TEXT = "saveStateEditText";
private static final String SAVE_STATE_KEY_LABEL = "saveStateLabel";
private static final String SAVE_STATE_PARENT = "saveStateParent";
private static final String SAVE_STATE_TAG = "saveStateTag";
/**
* Reference to the EditText
*/
private EditText mEditText;
/**
* When init is complete, child views can no longer be added
*/
private boolean mInitComplete = false;
/**
* Reference to the TextView used as the label
*/
private TextView mLabel;
/**
* LabelAnimator that animates the appearance and disappearance of the label
* TextView
*/
private LabelAnimator mLabelAnimator = new DefaultLabelAnimator();
/**
* True if the TextView label is showing (alpha 1f)
*/
private boolean mLabelShowing;
/**
* Holds saved state if any is waiting to be restored
*/
private Bundle mSavedState;
/**
* Interface for providing custom animations to the label TextView.
*/
public interface LabelAnimator {
/**
* Called when the label should become visible
*
* @param label
* TextView to animate to visible
*/
public void onDisplayLabel(View label);
/**
* Called when the label should become invisible
*
* @param label
* TextView to animate to invisible
*/
public void onHideLabel(View label);
}
public FloatLabel(Context context) {
this(context, null, 0);
}
public FloatLabel(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FloatLabel(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
@Override
public void addView(View child) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child);
}
}
@Override
public void addView(View child, int index) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, index);
}
}
@Override
public void addView(View child, int index,
android.view.ViewGroup.LayoutParams params) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, index, params);
}
}
@Override
public void addView(View child, int width, int height) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, width, height);
}
}
@Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
if (mInitComplete) {
throw new UnsupportedOperationException(
"You cannot add child views to a FloatLabel");
} else {
super.addView(child, params);
}
}
/**
* Returns the EditText portion of this View
*
* @return the EditText portion of this View
*/
public EditText getEditText() {
return mEditText;
}
/**
* Sets the text to be displayed above the EditText if the EditText is
* nonempty or as the EditText hint if it is empty
*
* @param resid
* int String resource ID
*/
public void setLabel(int resid) {
setLabel(getContext().getString(resid));
}
/**
* Sets the text to be displayed above the EditText if the EditText is
* nonempty or as the EditText hint if it is empty
*
* @param hint
* CharSequence to set as the label
*/
public void setLabel(CharSequence hint) {
mEditText.setHint(hint);
mLabel.setText(hint);
}
/**
* Specifies a new LabelAnimator to handle calls to show/hide the label
*
* @param labelAnimator
* LabelAnimator to use; null causes use of the default
* LabelAnimator
*/
public void setLabelAnimator(LabelAnimator labelAnimator) {
if (labelAnimator == null) {
mLabelAnimator = new DefaultLabelAnimator();
} else {
mLabelAnimator = labelAnimator;
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
final int childLeft = getPaddingLeft();
final int childRight = right - left - getPaddingRight();
int childTop = getPaddingTop();
final int childBottom = bottom - top - getPaddingBottom();
layoutChild(mLabel, childLeft, childTop, childRight, childBottom);
layoutChild(mEditText, childLeft,
childTop + mLabel.getMeasuredHeight(), childRight, childBottom);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void layoutChild(View child, int parentLeft, int parentTop,
int parentRight, int parentBottom) {
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
final int childTop = parentTop + lp.topMargin;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = Gravity.TOP | Gravity.START;
}
final int layoutDirection;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
layoutDirection = LAYOUT_DIRECTION_LTR;
} else {
layoutDirection = getLayoutDirection();
}
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity,
layoutDirection);
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = parentRight - width - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop
+ height);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Restore any state that's been pending before measuring
if (mSavedState != null) {
Parcelable childState = mSavedState
.getParcelable(SAVE_STATE_KEY_EDIT_TEXT);
mEditText.onRestoreInstanceState(childState);
childState = mSavedState.getParcelable(SAVE_STATE_KEY_LABEL);
mLabel.onRestoreInstanceState(childState);
mSavedState = null;
}
measureChild(mEditText, widthMeasureSpec, heightMeasureSpec);
measureChild(mLabel, widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
final Bundle savedState = (Bundle) state;
if (savedState.getBoolean(SAVE_STATE_TAG, false)) {
// Save our state for later since children will have theirs
// restored after this
// and having more than one FloatLabel in an Activity or
// Fragment means you have
// multiple views of the same ID
mSavedState = savedState;
super.onRestoreInstanceState(savedState
.getParcelable(SAVE_STATE_PARENT));
return;
}
}
super.onRestoreInstanceState(state);
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
final Bundle saveState = new Bundle();
saveState.putParcelable(SAVE_STATE_KEY_EDIT_TEXT,
mEditText.onSaveInstanceState());
saveState.putParcelable(SAVE_STATE_KEY_LABEL,
mLabel.onSaveInstanceState());
saveState.putBoolean(SAVE_STATE_TAG, true);
saveState.putParcelable(SAVE_STATE_PARENT, superState);
return saveState;
}
private int measureHeight(int heightMeasureSpec) {
int specMode = MeasureSpec.getMode(heightMeasureSpec);
int specSize = MeasureSpec.getSize(heightMeasureSpec);
int result = 0;
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = mEditText.getMeasuredHeight() + mLabel.getMeasuredHeight();
result += getPaddingTop() + getPaddingBottom();
result = Math.max(result, getSuggestedMinimumHeight());
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
private int measureWidth(int widthMeasureSpec) {
int specMode = MeasureSpec.getMode(widthMeasureSpec);
int specSize = MeasureSpec.getSize(widthMeasureSpec);
int result = 0;
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = Math.max(mEditText.getMeasuredWidth(),
mLabel.getMeasuredWidth());
result = Math.max(result, getSuggestedMinimumWidth());
result += getPaddingLeft() + getPaddingRight();
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
private void init(Context context, AttributeSet attrs, int defStyle) {
// Load custom attributes
final int layout;
final CharSequence text;
final CharSequence hint;
final ColorStateList hintColor;
final int floatLabelColor;
final int inputType;
if (attrs == null) {
layout = R.layout.widget_float_label;
text = null;
hint = null;
hintColor = null;
floatLabelColor = 0;
inputType = 0;
} else {
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.FloatLabel, defStyle, 0);
layout = a.getResourceId(R.styleable.FloatLabel_android_layout,
R.layout.widget_float_label);
text = a.getText(R.styleable.FloatLabel_android_text);
hint = a.getText(R.styleable.FloatLabel_android_hint);
hintColor = a
.getColorStateList(R.styleable.FloatLabel_android_textColorHint);
floatLabelColor = a.getColor(
R.styleable.FloatLabel_floatLabelColor, 0);
inputType = a.getInt(R.styleable.FloatLabel_android_inputType,
InputType.TYPE_CLASS_TEXT);
a.recycle();
}
inflate(context, layout, this);
mEditText = (EditText) findViewById(R.id.edit_text);
if (mEditText == null) {
throw new RuntimeException(
"Your layout must have an EditText whose ID is @id/edit_text");
}
mEditText.setHint(hint);
mEditText.setText(text);
if (hintColor != null) {
mEditText.setHintTextColor(hintColor);
}
if (inputType != 0) {
mEditText.setInputType(inputType);
}
mLabel = (TextView) findViewById(R.id.float_label);
if (mLabel == null) {
throw new RuntimeException(
"Your layout must have a TextView whose ID is @id/float_label");
}
mLabel.setText(mEditText.getHint());
if (floatLabelColor != 0)
mLabel.setTextColor(floatLabelColor);
// Listen to EditText to know when it is empty or nonempty
mEditText.addTextChangedListener(new EditTextWatcher());
// Check current state of EditText
if (mEditText.getText().length() == 0) {
// mLabel.setAlpha(0);
ViewHelper.setAlpha(mLabel, 0);
mLabelShowing = false;
} else {
mLabel.setVisibility(View.VISIBLE);
mLabelShowing = true;
}
// Mark init as complete to prevent accidentally breaking the view by
// adding children
mInitComplete = true;
}
/**
* LabelAnimator that uses the traditional float label Y shift and fade.
*
* @author Ian G. Clifton
*/
private static class DefaultLabelAnimator implements LabelAnimator {
@Override
public void onDisplayLabel(View label) {
final float offset = label.getHeight() / 2;
final float currentY = ViewHelper.getY(label);
if (currentY != offset) {
ViewHelper.setY(label, offset);
}
ViewPropertyAnimator.animate(label).alpha(1).y(1);
}
@Override
public void onHideLabel(View label) {
final float offset = label.getHeight() / 2;
final float currentY = ViewHelper.getY(label);
if (currentY != 0) {
ViewHelper.setY(label, 0);
}
ViewPropertyAnimator.animate(label).alpha(0).y(offset);
}
}
/**
* TextWatcher that notifies FloatLabel when the EditText changes between
* having text and not having text or vice versa.
*
* @author Ian G. Clifton
*/
private class EditTextWatcher implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
// Text is empty; TextView label should be invisible
if (mLabelShowing) {
mLabelAnimator.onHideLabel(mLabel);
mLabelShowing = false;
}
} else if (!mLabelShowing) {
// Text is nonempty; TextView label should be visible
mLabelShowing = true;
mLabelAnimator.onDisplayLabel(mLabel);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Ignored
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// Ignored
}
}
}
| gpl-2.0 |
shellposhy/cms | src/main/java/cn/com/cms/library/model/DataNavigate.java | 3164 | package cn.com.cms.library.model;
import cn.com.cms.framework.base.tree.TreeNodeEntity;
import cn.com.cms.library.constant.EDataNavigateType;
import cn.com.cms.library.constant.ELibraryNodeType;
/**
* 数据导航类
*
* 包含数据库、数据库分类、数据标签三种类型
*
* @author shishb
* @see TreeEntity
* @version 1.0
*/
public class DataNavigate extends TreeNodeEntity<DataNavigate> {
private static final long serialVersionUID = 1L;
private Integer realId;
private Integer baseId;
private String code;
private String pathCode;
private EDataNavigateType type;
public DataNavigate() {
}
public DataNavigate(BaseLibrary<?> library) {
this.id = library.getId();
this.realId = library.getId();
this.name = library.getName();
this.parentID = library.getParentID();
this.code = library.getCode();
this.pathCode = library.getPathCode();
if (ELibraryNodeType.Directory.equals(library.getNodeType())) {
this.type = EDataNavigateType.DATA_CATEGORY;
} else {
this.type = EDataNavigateType.DATA_BASE;
}
}
/**
* 利用标签的ID与数据库的最大ID相加解决两个ID可能重复的问题
*
* @param dataSort
* @param maxDbId
*/
public DataNavigate(DataSort dataSort, int maxDbId) {
this.id = maxDbId + dataSort.getId();
this.realId = dataSort.getId();
this.baseId = dataSort.getBaseId();
this.name = dataSort.getName();
if (dataSort.getParentID() == 0) {
this.parentID = dataSort.getBaseId();
} else {
this.parentID = maxDbId + dataSort.getParentID();
}
this.code = dataSort.getCode();
this.pathCode = dataSort.getPathCode();
this.type = EDataNavigateType.DATA_SORT;
}
/**
* 数据分类与数据导航转换
* <p>
* 基于全局标签的情况下设置数据库ID为特殊形式
*
* @param dataSort
* @param baseId
*/
public DataNavigate(DataSort dataSort, Integer baseId) {
this.id = dataSort.getId();
this.realId = dataSort.getId();
if (null != dataSort && null != dataSort.getBaseId() && dataSort.getBaseId().intValue() == 0) {
this.baseId = baseId;
} else {
this.baseId = dataSort.getBaseId();
}
this.name = dataSort.getName();
this.parentID = dataSort.getBaseId();
this.code = dataSort.getCode();
this.pathCode = dataSort.getPathCode();
this.type = EDataNavigateType.DATA_SORT;
}
public Integer getRealId() {
return realId;
}
public Integer getBaseId() {
return baseId;
}
public void setBaseId(Integer baseId) {
this.baseId = baseId;
}
public void setRealId(Integer realId) {
this.realId = realId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPathCode() {
return pathCode;
}
public void setPathCode(String pathCode) {
this.pathCode = pathCode;
}
public EDataNavigateType getType() {
return type;
}
public void setType(EDataNavigateType type) {
this.type = type;
}
public DataSort toDataSort() {
DataSort dataSort = new DataSort();
dataSort.setId(this.realId);
dataSort.setName(this.name);
dataSort.setCode(this.code);
dataSort.setPathCode(this.pathCode);
return dataSort;
}
}
| gpl-2.0 |
carvalhomb/tsmells | guess/guess-src/com/hp/hpl/guess/util/intervals/RBTree.java | 6305 | package com.hp.hpl.guess.util.intervals;
/**
* an implementatation of a Red-Black tree so that we can keep our interval
* tree balanced. Nothing too exciting here... It's directly out of
* of CLR.
*
*/
public class RBTree extends Tree {
/**
* Simple constructor
* @return a new RBTree
*/
public RBTree() {
super();
}
/**
* performs the leftRotation step starting at a given node
* @param x the node at which rotation needs to occur
*/
private final void leftRotate(IntervalNode x) {
if (x.getRight() == IntervalNode.nullIntervalNode)
return;
// set y
IntervalNode y = x.getRight();
// turn y's left subtree into x's right subtree
x.setRight(y.getLeft());
if (y.getLeft() != IntervalNode.nullIntervalNode)
y.getLeft().setP(x);
y.setP(x.getP());
// link x's parent to y
if (x.getP() == IntervalNode.nullIntervalNode) {
super.root = y;
} else {
if (x == x.getP().getLeft()) {
x.getP().setLeft(y);
} else {
x.getP().setRight(y);
}
}
// put x on y's left
y.setLeft(x);
x.setP(y);
}
/**
* performs the rightRotation step starting at a given node
* @param y the node at which rotation needs to occur
*/
private final void rightRotate(IntervalNode x) {
//System.out.println("right " + x);
if (x.getLeft() == IntervalNode.nullIntervalNode)
return;
IntervalNode y = x.getLeft();
// turn x's left subtree into y's right subtree
x.setLeft(y.getRight());
if (y.getRight() != IntervalNode.nullIntervalNode)
y.getRight().setP(x);
y.setP(x.getP());
if (x.getP() == IntervalNode.nullIntervalNode) {
super.root = y;
} else {
if (x == x.getP().getRight()) {
x.getP().setRight(y);
} else {
x.getP().setLeft(y);
}
}
y.setRight(x);
x.setP(y);
}
/**
* inserts a node into the tree and then performs the operations
* necessary to balance the tree
* @param x the new node to insert
*/
public void insert(IntervalNode x) {
// tree insert
super.insert(x);
IntervalNode y;
x.color = IntervalNode.RED;
while ((x != super.root) && (x.getP().color == IntervalNode.RED)) {
if (x.getP() == x.getP().getP().getLeft()) {
y = x.getP().getP().getRight();
if (y.color == IntervalNode.RED) {
x.getP().color = IntervalNode.BLACK;
y.color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
x = x.getP().getP();
} else {
if (x == x.getP().getRight()) {
x = x.getP();
leftRotate(x);
}
x.getP().color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
rightRotate(x.getP().getP());
}
} else {
//System.out.println("1");
y = x.getP().getP().getLeft();
if (y.color == IntervalNode.RED) {
//System.out.println("2");
x.getP().color = IntervalNode.BLACK;
y.color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
x = x.getP().getP();
} else {
//System.out.println("3");
if (x == x.getP().getLeft()) {
//System.out.println("4");
x = x.getP();
rightRotate(x);
}
x.getP().color = IntervalNode.BLACK;
x.getP().getP().color = IntervalNode.RED;
leftRotate(x.getP().getP());
}
}
}
super.root.color = IntervalNode.BLACK;
}
/**
* deletes the given node z from the tree and does the
* balancing necessary to maintain tree height
* @param z the node to delete
*/
public IntervalNode delete(IntervalNode z) {
IntervalNode y;
IntervalNode x;
if ((z.getLeft() == IntervalNode.nullIntervalNode) ||
(z.getRight() == IntervalNode.nullIntervalNode)) {
y = z;
} else {
y = super.successor(z);
}
if (y.getLeft() != IntervalNode.nullIntervalNode) {
x = y.getLeft();
} else {
x = y.getRight();
}
x.setP(y.getP());
if (y.getP() == IntervalNode.nullIntervalNode) {
super.root = x;
} else {
if (y == y.getP().getLeft()) {
y.getP().setLeft(x);
} else {
y.getP().setRight(x);
}
}
if (y != z) {
z.low = y.low;
}
if (y.color = IntervalNode.BLACK)
deleteFixup(x);
return y;
}
/**
* a continuation of the delete operation. We need to fix up
* random things to maintain balance
* @param x the node where the fixup should start
*/
private final void deleteFixup(IntervalNode x) {
IntervalNode w;
while ((x != IntervalNode.nullIntervalNode) && (x.color == IntervalNode.BLACK)) {
if (x == x.getP().getLeft()) {
w = x.getP().getRight();
if (w.color == IntervalNode.RED) {
w.color = IntervalNode.BLACK;
x.getP().color = IntervalNode.RED;
leftRotate(x.getP());
}
if ((w.getLeft().color == IntervalNode.BLACK) &&
(w.getRight().color == IntervalNode.BLACK)) {
w.color = IntervalNode.RED;
x = x.getP();
} else {
if (w.getRight().color == IntervalNode.BLACK) {
w.getLeft().color = IntervalNode.BLACK;
w.color = IntervalNode.RED;
rightRotate(w);
w = x.getP().getRight();
}
w.color = x.getP().color;
x.getP().color = IntervalNode.BLACK;
w.getRight().color = IntervalNode.BLACK;
leftRotate(x.getP());
x = super.root;
}
} else {
// same as above, right and left exchanged
w = x.getP().getLeft();
if (w.color == IntervalNode.RED) {
w.color = IntervalNode.BLACK;
x.getP().color = IntervalNode.RED;
leftRotate(x.getP());
}
if ((w.getRight().color == IntervalNode.BLACK) &&
(w.getLeft().color == IntervalNode.BLACK)) {
w.color = IntervalNode.RED;
x = x.getP();
} else {
if (w.getLeft().color == IntervalNode.BLACK) {
w.getRight().color = IntervalNode.BLACK;
w.color = IntervalNode.RED;
rightRotate(w);
w = x.getP().getLeft();
}
w.color = x.getP().color;
x.getP().color = IntervalNode.BLACK;
w.getLeft().color = IntervalNode.BLACK;
leftRotate(x.getP());
x = super.root;
}
}
}
x.color = IntervalNode.BLACK;
}
}
| gpl-2.0 |
robertodepinho/HexBoard-API | src/incboard/api/DataItemInterface.java | 1379 | /*
*
Copyright 2008 RobertoPinho. All rights reserved.
This file is part of incboard.api.
incboard.api 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.
incboard.api 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 incboard.api. If not, see <http://www.gnu.org/licenses/>.
For academic use, please cite:
Pinho, R, de Oliveira, M.C. and Lopes, A. A. 2009.
Incremental Board: A grid-based space for visualizing dynamic data sets.
In Proceedings of the 2009 ACM Symposium on Applied Computing
(Honolulu, Hawaii, USA, March 8 - 12, 2009). SAC '09. ACM, New York, NY.
(to appear)
*/
package incboard.api;
/**
*
* @author RobertoPinho
*/
public interface DataItemInterface {
public String getURI();
public int getCol();
public int getRow();
void setCol(int x);
void setRow(int y);
public Double getDistance(DataItemInterface other);
}
| gpl-2.0 |
CEREMA/com.cerema.cloud | owncloud-android-library/src/com/cerema/cloud/lib/resources/shares/ShareXMLParser.java | 12289 | /* ownCloud Android Library is available under MIT license
* Copyright (C) 2014 ownCloud Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.cerema.cloud.lib.resources.shares;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
//import android.util.Log;
import android.util.Xml;
import com.cerema.cloud.lib.common.network.WebdavUtils;
import com.cerema.cloud.lib.resources.files.FileUtils;
/**
* Parser for Share API Response
* @author masensio
*
*/
public class ShareXMLParser {
//private static final String TAG = ShareXMLParser.class.getSimpleName();
// No namespaces
private static final String ns = null;
// NODES for XML Parser
private static final String NODE_OCS = "ocs";
private static final String NODE_META = "meta";
private static final String NODE_STATUS = "status";
private static final String NODE_STATUS_CODE = "statuscode";
//private static final String NODE_MESSAGE = "message";
private static final String NODE_DATA = "data";
private static final String NODE_ELEMENT = "element";
private static final String NODE_ID = "id";
private static final String NODE_ITEM_TYPE = "item_type";
private static final String NODE_ITEM_SOURCE = "item_source";
private static final String NODE_PARENT = "parent";
private static final String NODE_SHARE_TYPE = "share_type";
private static final String NODE_SHARE_WITH = "share_with";
private static final String NODE_FILE_SOURCE = "file_source";
private static final String NODE_PATH = "path";
private static final String NODE_PERMISSIONS = "permissions";
private static final String NODE_STIME = "stime";
private static final String NODE_EXPIRATION = "expiration";
private static final String NODE_TOKEN = "token";
private static final String NODE_STORAGE = "storage";
private static final String NODE_MAIL_SEND = "mail_send";
private static final String NODE_SHARE_WITH_DISPLAY_NAME = "share_with_display_name";
private static final String NODE_URL = "url";
private static final String TYPE_FOLDER = "folder";
private static final int SUCCESS = 100;
private static final int FAILURE = 403;
private static final int FILE_NOT_FOUND = 404;
private String mStatus;
private int mStatusCode;
// Getters and Setters
public String getStatus() {
return mStatus;
}
public void setStatus(String status) {
this.mStatus = status;
}
public int getStatusCode() {
return mStatusCode;
}
public void setStatusCode(int statusCode) {
this.mStatusCode = statusCode;
}
// Constructor
public ShareXMLParser() {
mStatusCode = 100;
}
public boolean isSuccess() {
return mStatusCode == SUCCESS;
}
public boolean isFailure() {
return mStatusCode == FAILURE;
}
public boolean isFileNotFound() {
return mStatusCode == FILE_NOT_FOUND;
}
/**
* Parse is as response of Share API
* @param is
* @return List of ShareRemoteFiles
* @throws XmlPullParserException
* @throws IOException
*/
public ArrayList<OCShare> parseXMLResponse(InputStream is) throws XmlPullParserException, IOException {
try {
// XMLPullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
parser.nextTag();
return readOCS(parser);
} finally {
is.close();
}
}
/**
* Parse OCS node
* @param parser
* @return List of ShareRemoteFiles
* @throws XmlPullParserException
* @throws IOException
*/
private ArrayList<OCShare> readOCS (XmlPullParser parser) throws XmlPullParserException, IOException {
ArrayList<OCShare> shares = new ArrayList<OCShare>();
parser.require(XmlPullParser.START_TAG, ns , NODE_OCS);
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
// read NODE_META and NODE_DATA
if (name.equalsIgnoreCase(NODE_META)) {
readMeta(parser);
} else if (name.equalsIgnoreCase(NODE_DATA)) {
shares = readData(parser);
} else {
skip(parser);
}
}
return shares;
}
/**
* Parse Meta node
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
private void readMeta(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, NODE_META);
//Log_OC.d(TAG, "---- NODE META ---");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equalsIgnoreCase(NODE_STATUS)) {
setStatus(readNode(parser, NODE_STATUS));
} else if (name.equalsIgnoreCase(NODE_STATUS_CODE)) {
setStatusCode(Integer.parseInt(readNode(parser, NODE_STATUS_CODE)));
} else {
skip(parser);
}
}
}
/**
* Parse Data node
* @param parser
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private ArrayList<OCShare> readData(XmlPullParser parser) throws XmlPullParserException, IOException {
ArrayList<OCShare> shares = new ArrayList<OCShare>();
OCShare share = null;
parser.require(XmlPullParser.START_TAG, ns, NODE_DATA);
//Log_OC.d(TAG, "---- NODE DATA ---");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equalsIgnoreCase(NODE_ELEMENT)) {
readElement(parser, shares);
} else if (name.equalsIgnoreCase(NODE_ID)) {// Parse Create XML Response
share = new OCShare();
String value = readNode(parser, NODE_ID);
share.setIdRemoteShared(Integer.parseInt(value));
} else if (name.equalsIgnoreCase(NODE_URL)) {
share.setShareType(ShareType.PUBLIC_LINK);
String value = readNode(parser, NODE_URL);
share.setShareLink(value);
} else if (name.equalsIgnoreCase(NODE_TOKEN)) {
share.setToken(readNode(parser, NODE_TOKEN));
} else {
skip(parser);
}
}
if (share != null) {
// this is the response of a request for creation; don't pass to isValidShare()
shares.add(share);
}
return shares;
}
/**
* Parse Element node
* @param parser
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private void readElement(XmlPullParser parser, ArrayList<OCShare> shares) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, NODE_ELEMENT);
OCShare share = new OCShare();
//Log_OC.d(TAG, "---- NODE ELEMENT ---");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equalsIgnoreCase(NODE_ELEMENT)) {
// patch to work around servers responding with extra <element> surrounding all the shares on the same file before
// https://github.com/owncloud/core/issues/6992 was fixed
readElement(parser, shares);
} else if (name.equalsIgnoreCase(NODE_ID)) {
share.setIdRemoteShared(Integer.parseInt(readNode(parser, NODE_ID)));
} else if (name.equalsIgnoreCase(NODE_ITEM_TYPE)) {
share.setIsFolder(readNode(parser, NODE_ITEM_TYPE).equalsIgnoreCase(TYPE_FOLDER));
fixPathForFolder(share);
} else if (name.equalsIgnoreCase(NODE_ITEM_SOURCE)) {
share.setItemSource(Long.parseLong(readNode(parser, NODE_ITEM_SOURCE)));
} else if (name.equalsIgnoreCase(NODE_PARENT)) {
readNode(parser, NODE_PARENT);
} else if (name.equalsIgnoreCase(NODE_SHARE_TYPE)) {
int value = Integer.parseInt(readNode(parser, NODE_SHARE_TYPE));
share.setShareType(ShareType.fromValue(value));
} else if (name.equalsIgnoreCase(NODE_SHARE_WITH)) {
share.setShareWith(readNode(parser, NODE_SHARE_WITH));
} else if (name.equalsIgnoreCase(NODE_FILE_SOURCE)) {
share.setFileSource(Long.parseLong(readNode(parser, NODE_FILE_SOURCE)));
} else if (name.equalsIgnoreCase(NODE_PATH)) {
share.setPath(readNode(parser, NODE_PATH));
fixPathForFolder(share);
} else if (name.equalsIgnoreCase(NODE_PERMISSIONS)) {
share.setPermissions(Integer.parseInt(readNode(parser, NODE_PERMISSIONS)));
} else if (name.equalsIgnoreCase(NODE_STIME)) {
share.setSharedDate(Long.parseLong(readNode(parser, NODE_STIME)));
} else if (name.equalsIgnoreCase(NODE_EXPIRATION)) {
String value = readNode(parser, NODE_EXPIRATION);
if (!(value.length() == 0)) {
share.setExpirationDate(WebdavUtils.parseResponseDate(value).getTime());
}
} else if (name.equalsIgnoreCase(NODE_TOKEN)) {
share.setToken(readNode(parser, NODE_TOKEN));
} else if (name.equalsIgnoreCase(NODE_STORAGE)) {
readNode(parser, NODE_STORAGE);
} else if (name.equalsIgnoreCase(NODE_MAIL_SEND)) {
readNode(parser, NODE_MAIL_SEND);
} else if (name.equalsIgnoreCase(NODE_SHARE_WITH_DISPLAY_NAME)) {
share.setSharedWithDisplayName(readNode(parser, NODE_SHARE_WITH_DISPLAY_NAME));
} else {
skip(parser);
}
}
if (isValidShare(share)) {
shares.add(share);
}
}
private boolean isValidShare(OCShare share) {
return ((share.getIdRemoteShared() > -1) &&
(share.getShareType() == ShareType.PUBLIC_LINK) // at this moment we only care about public shares
);
}
private void fixPathForFolder(OCShare share) {
if (share.isFolder() && share.getPath() != null && share.getPath().length() > 0 && !share.getPath().endsWith(FileUtils.PATH_SEPARATOR)) {
share.setPath(share.getPath() + FileUtils.PATH_SEPARATOR);
}
}
/**
* Parse a node, to obtain its text. Needs readText method
* @param parser
* @param node
* @return Text of the node
* @throws XmlPullParserException
* @throws IOException
*/
private String readNode (XmlPullParser parser, String node) throws XmlPullParserException, IOException{
parser.require(XmlPullParser.START_TAG, ns, node);
String value = readText(parser);
//Log_OC.d(TAG, "node= " + node + ", value= " + value);
parser.require(XmlPullParser.END_TAG, ns, node);
return value;
}
/**
* Read the text from a node
* @param parser
* @return Text of the node
* @throws IOException
* @throws XmlPullParserException
*/
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
/**
* Skip tags in parser procedure
* @param parser
* @throws XmlPullParserException
* @throws IOException
*/
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
| gpl-2.0 |
simon33-2/triplea | src/games/strategy/net/IObjectStreamFactory.java | 363 | package games.strategy.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public interface IObjectStreamFactory {
ObjectInputStream create(InputStream stream) throws IOException;
ObjectOutputStream create(OutputStream stream) throws IOException;
}
| gpl-2.0 |
PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/kernel/modules/state/ApplicationStateDevice.java | 3055 | /*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* 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.
*/
package net.sourceforge.atunes.kernel.modules.state;
import java.util.Map;
import net.sourceforge.atunes.model.IStateDevice;
import net.sourceforge.atunes.utils.ReflectionUtils;
/**
* This class represents the application settings that are stored at application
* shutdown and loaded at application startup.
* <p>
* <b>NOTE: All classes that are used as properties must be Java Beans!</b>
* </p>
*/
public class ApplicationStateDevice implements IStateDevice {
private PreferenceHelper preferenceHelper;
/**
* @param preferenceHelper
*/
public void setPreferenceHelper(final PreferenceHelper preferenceHelper) {
this.preferenceHelper = preferenceHelper;
}
@Override
public String getDefaultDeviceLocation() {
return this.preferenceHelper.getPreference(
Preferences.DEFAULT_DEVICE_LOCATION, String.class, null);
}
@Override
public void setDefaultDeviceLocation(final String defaultDeviceLocation) {
this.preferenceHelper.setPreference(
Preferences.DEFAULT_DEVICE_LOCATION, defaultDeviceLocation);
}
@Override
public String getDeviceFileNamePattern() {
return this.preferenceHelper.getPreference(
Preferences.DEVICE_FILENAME_PATTERN, String.class, null);
}
@Override
public void setDeviceFileNamePattern(final String deviceFileNamePattern) {
this.preferenceHelper.setPreference(
Preferences.DEVICE_FILENAME_PATTERN, deviceFileNamePattern);
}
@Override
public String getDeviceFolderPathPattern() {
return this.preferenceHelper.getPreference(
Preferences.DEVICE_FOLDER_PATH_PATTERN, String.class, null);
}
@Override
public void setDeviceFolderPathPattern(final String deviceFolderPathPattern) {
this.preferenceHelper
.setPreference(Preferences.DEVICE_FOLDER_PATH_PATTERN,
deviceFolderPathPattern);
}
@Override
public boolean isAllowRepeatedSongsInDevice() {
return this.preferenceHelper
.getPreference(Preferences.ALLOW_REPEATED_SONGS_IN_DEVICE,
Boolean.class, true);
}
@Override
public void setAllowRepeatedSongsInDevice(
final boolean allowRepeatedSongsInDevice) {
this.preferenceHelper.setPreference(
Preferences.ALLOW_REPEATED_SONGS_IN_DEVICE,
allowRepeatedSongsInDevice);
}
@Override
public Map<String, String> describeState() {
return ReflectionUtils.describe(this);
}
}
| gpl-2.0 |
JulianPoveda/AndroidData | src/form_amdata/Form_CensoCarga.java | 37678 | package form_amdata;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import class_amdata.Class_CensoCarga;
import sypelc.androidamdata.R;
import miscelanea.SQLite;
import miscelanea.Tablas;
import miscelanea.Util;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Spinner;
public class Form_CensoCarga extends Activity implements OnClickListener, OnCheckedChangeListener, OnItemSelectedListener{
Tablas CensoTabla;
SQLite CensoSQL;
Util CensoUtil;
Class_CensoCarga FcnCenso;
private String NombreUsuario = "";
private String CedulaUsuario = "";
private String NivelUsuario = "";
private String OrdenTrabajo = "";
private String CuentaCliente = "";
private String FolderAplicacion= "";
//private String IdElemento = "";
private float errorImpulsos;
private float errorNumeradorA;
private float errorNumeradorB;
private float errorNumeradorC;
private float errorVoltajeLinea;
private float errorCorrienteLinea;
private float errorTiempoLinea;
private float errorVueltasLinea;
private String[] _strEstadoCarga = {"...","Registrada","Directa"};
private String _strCamposTabla = "carga,elemento,vatios,cant,total";
private String[] _strConexion = {"Monofasico","Bifasico","Trifasico"};
private String[] _strPrueba = {"Baja","Alta"};
private ArrayList<String> _strCantidad = new ArrayList<String>();
private ArrayAdapter<String> AdaptadorCantidad;
CheckBox _chkFaseA, _chkFaseB, _chkFaseC;
Spinner _cmbElementos, _cmbEstadoElemento, _cmbConexion, _cmbPrueba, _cmbCantidad;
TextView _lblVb, _lblVc, _lblIb, _lblIc, _lblTb, _lblTc, _lblNvb, _lblNvc, _lblFp1, _lblFp2, _lblFp3, _lbltcr, _lbltcd, _lbltcc;
EditText _txtVa, _txtVb, _txtVc, _txtIa, _txtIb, _txtIc, _txtTa, _txtTb, _txtTc, _txtNva, _txtNvb, _txtNvc, _txtRevUnidades, _txtVatios;
Button _btnRegistrar, _btnEliminar, _btnErrorCalcular, _btnErrorGuardar;
private LinearLayout ll;
private TableLayout InformacionTabla;
//Variables para consultas en la base de datos
private ContentValues Registro = new ContentValues();
private ArrayList<ContentValues> Tabla = new ArrayList<ContentValues>();
DecimalFormat decimales = new DecimalFormat("0.000");
ArrayAdapter<String> AdaptadorEstadoCarga;
ArrayAdapter<String> AdaptadorTipoConexion;
ArrayAdapter<String> AdaptadorTipoPrueba;
//Variables para la consulta de los elementos disponibles del censo de carga
ArrayList<ContentValues> ElementosCenso = new ArrayList<ContentValues>();
ArrayList<String> StringElementosCenso = new ArrayList<String>();
ArrayAdapter<String> AdaptadorElementosCenso;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_censo_carga);
Bundle bundle = getIntent().getExtras();
this.NombreUsuario = bundle.getString("NombreUsuario");
this.CedulaUsuario = bundle.getString("CedulaUsuario");
this.NivelUsuario = bundle.getString("NivelUsuario");
this.OrdenTrabajo = bundle.getString("OrdenTrabajo");
this.CuentaCliente = bundle.getString("CuentaCliente");
this.FolderAplicacion = bundle.getString("FolderAplicacion");
CensoTabla = new Tablas(this, _strCamposTabla, "110,275,80,70,90", 1, "#74BBEE", "#A9CFEA" ,"#EE7474");
CensoSQL = new SQLite(this, FolderAplicacion);
CensoUtil = new Util();
FcnCenso = new Class_CensoCarga(this, FolderAplicacion);
_cmbElementos = (Spinner) findViewById(R.id.CensoCmbElemento);
_cmbEstadoElemento = (Spinner) findViewById(R.id.CensoCmbCarga);
_cmbConexion = (Spinner) findViewById(R.id.ErrorCmbTipoConexion);
_cmbPrueba = (Spinner) findViewById(R.id.ErrorCmbTipoPrueba);
_cmbCantidad = (Spinner) findViewById(R.id.CensoCmbCantidad);
_chkFaseA = (CheckBox) findViewById(R.id.ErrorChkFaseA);
_chkFaseB = (CheckBox) findViewById(R.id.ErrorChkFaseB);
_chkFaseC = (CheckBox) findViewById(R.id.ErrorChkFaseC);
_lblVb = (TextView) findViewById(R.id.CensoLblVb);
_lblVc = (TextView) findViewById(R.id.CensoLblVc);
_lblIb = (TextView) findViewById(R.id.CensoLblIb);
_lblIc = (TextView) findViewById(R.id.CensoLblIc);
_lblTb = (TextView) findViewById(R.id.CensoLblTb);
_lblTc = (TextView) findViewById(R.id.CensoLblTc);
_lblNvb = (TextView) findViewById(R.id.CensoLblNvb);
_lblNvc = (TextView) findViewById(R.id.CensoLblNvc);
_lblFp1 = (TextView) findViewById(R.id.ErrorLblFp1Value);
_lblFp2 = (TextView) findViewById(R.id.ErrorLblFp2Value);
_lblFp3 = (TextView) findViewById(R.id.ErrorLblFp3Value);
_lbltcr = (TextView) findViewById(R.id.CensoLblTCR2);
_lbltcd = (TextView) findViewById(R.id.CensoLblTCD);
_lbltcc = (TextView) findViewById(R.id.CensoLblTCC);
_txtVa = (EditText) findViewById(R.id.CensoTxtVa);
_txtVb = (EditText) findViewById(R.id.CensoTxtVb);
_txtVc = (EditText) findViewById(R.id.CensoTxtVc);
_txtIa = (EditText) findViewById(R.id.CensoTxtIa);
_txtIb = (EditText) findViewById(R.id.CensoTxtIb);
_txtIc = (EditText) findViewById(R.id.CensoTxtIc);
_txtTa = (EditText) findViewById(R.id.CensoTxtTa);
_txtTb = (EditText) findViewById(R.id.CensoTxtTb);
_txtTc = (EditText) findViewById(R.id.CensoTxtTc);
_txtNva = (EditText) findViewById(R.id.CensoTxtNva);
_txtNvb = (EditText) findViewById(R.id.CensoTxtNvb);
_txtNvc = (EditText) findViewById(R.id.CensoTxtNvc);
_txtRevUnidades = (EditText) findViewById(R.id.ErrorTxtRevUnidades);
_txtVatios = (EditText) findViewById(R.id.CensoTxtVatios);
_btnRegistrar = (Button) findViewById(R.id.CensoBtnRegistrar);
_btnEliminar = (Button) findViewById(R.id.CensoBtnEliminar);
_btnErrorCalcular = (Button) findViewById(R.id.ErrorBtnCalcular);
_btnErrorGuardar = (Button) findViewById(R.id.ErrorBtnGuardar);
ll = (LinearLayout) findViewById(R.id.CensoTablaElementos);
_strCantidad = CensoUtil.getRangeAdapter(0, 100, 1);
AdaptadorCantidad = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_strCantidad);
_cmbCantidad.setAdapter(AdaptadorCantidad);
AdaptadorEstadoCarga = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_strEstadoCarga);
_cmbEstadoElemento.setAdapter(AdaptadorEstadoCarga);
AdaptadorTipoConexion = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_strConexion);
_cmbConexion.setAdapter(AdaptadorTipoConexion);
AdaptadorTipoPrueba = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_strPrueba);
_cmbPrueba.setAdapter(AdaptadorTipoPrueba);
_lbltcr.setText("TCR: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"' AND tipo_carga='R'"));
_lbltcd.setText("TCD: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"' AND tipo_carga='D'"));
_lbltcc.setText("TCC: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"'"));
//Adaptador para el combo del calibre del material segun el tipo y el conductor
ElementosCenso = CensoSQL.SelectData("amd_elementos_censo", "descripcion", "id_elemento IS NOT NULL ORDER BY descripcion");
CensoUtil.ArrayContentValuesToString(StringElementosCenso, ElementosCenso, "descripcion");
AdaptadorElementosCenso= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,StringElementosCenso);
_cmbElementos.setAdapter(AdaptadorElementosCenso);
Tabla = CensoSQL.SelectData("vista_censo_carga", "carga,elemento,vatios,cant,total", "id_orden='"+OrdenTrabajo+"'");
InformacionTabla = CensoTabla.CuerpoTabla(Tabla);
ll.removeAllViews();
ll.addView(InformacionTabla);
_chkFaseA.setOnCheckedChangeListener(this);
_chkFaseB.setOnCheckedChangeListener(this);
_chkFaseC.setOnCheckedChangeListener(this);
_cmbPrueba.setOnItemSelectedListener(this);
_cmbElementos.setOnItemSelectedListener(this);
_cmbConexion.setOnItemSelectedListener(this);
_btnRegistrar.setOnClickListener(this);
_btnEliminar.setOnClickListener(this);
_btnErrorCalcular.setOnClickListener(this);
_btnErrorGuardar.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_censo_carga, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent k;
switch (item.getItemId()) {
case R.id.Acta:
finish();
k = new Intent(this, Form_Actas.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.Acometida:
finish();
k = new Intent(this, Acometida.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.ContadorTransformador:
finish();
k = new Intent(this, Form_CambioContador.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.IrregularidadesObservaciones:
finish();
k = new Intent(this, IrregularidadesObservaciones.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.Sellos:
finish();
k = new Intent(this, Form_Sellos.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.EncontradoPruebas:
finish();
k = new Intent(this, Form_MedidorPruebas.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.Materiales:
finish();
k = new Intent(this, Materiales.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.DatosAdecuaciones:
finish();
k = new Intent(this, Form_DatosActa_Adecuaciones.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
case R.id.Volver:
finish();
k = new Intent(this, Form_Solicitudes.class);
k.putExtra("NombreUsuario", this.NombreUsuario);
k.putExtra("CedulaUsuario", CedulaUsuario);
k.putExtra("NivelUsuario", NivelUsuario);
k.putExtra("OrdenTrabajo", OrdenTrabajo);
k.putExtra("CuentaCliente",CuentaCliente);
k.putExtra("FolderAplicacion", Environment.getExternalStorageDirectory() + File.separator + "EMSA");
startActivity(k);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void OcultarItemsGraficos(){
if(_cmbConexion.getSelectedItem().toString().equals("Monofasico")){
_chkFaseB.setVisibility(View.INVISIBLE);
_chkFaseC.setVisibility(View.INVISIBLE);
_lblVb.setVisibility(View.INVISIBLE);
_lblVc.setVisibility(View.INVISIBLE);
_lblIb.setVisibility(View.INVISIBLE);
_lblIc.setVisibility(View.INVISIBLE);
_lblTb.setVisibility(View.INVISIBLE);
_lblTc.setVisibility(View.INVISIBLE);
_lblNvb.setVisibility(View.INVISIBLE);
_lblNvc.setVisibility(View.INVISIBLE);
_lblFp2.setVisibility(View.INVISIBLE);
_lblFp3.setVisibility(View.INVISIBLE);
_txtVb.setVisibility(View.INVISIBLE);
_txtVc.setVisibility(View.INVISIBLE);
_txtIb.setVisibility(View.INVISIBLE);
_txtIc.setVisibility(View.INVISIBLE);
_txtTb.setVisibility(View.INVISIBLE);
_txtTc.setVisibility(View.INVISIBLE);
_txtNvb.setVisibility(View.INVISIBLE);
_txtNvc.setVisibility(View.INVISIBLE);
}else if(_cmbConexion.getSelectedItem().toString().equals("Bifasico")){
_chkFaseB.setVisibility(View.VISIBLE);
_chkFaseC.setVisibility(View.INVISIBLE);
_lblVb.setVisibility(View.VISIBLE);
_lblVc.setVisibility(View.INVISIBLE);
_lblIb.setVisibility(View.VISIBLE);
_lblIc.setVisibility(View.INVISIBLE);
_lblTb.setVisibility(View.VISIBLE);
_lblTc.setVisibility(View.INVISIBLE);
_lblNvb.setVisibility(View.VISIBLE);
_lblNvc.setVisibility(View.INVISIBLE);
_lblFp2.setVisibility(View.VISIBLE);
_lblFp3.setVisibility(View.INVISIBLE);
_txtVb.setVisibility(View.VISIBLE);
_txtVc.setVisibility(View.INVISIBLE);
_txtIb.setVisibility(View.VISIBLE);
_txtIc.setVisibility(View.INVISIBLE);
_txtTb.setVisibility(View.VISIBLE);
_txtTc.setVisibility(View.INVISIBLE);
_txtNvb.setVisibility(View.VISIBLE);
_txtNvc.setVisibility(View.INVISIBLE);
}else if(_cmbConexion.getSelectedItem().toString().equals("Trifasico")){
_chkFaseB.setVisibility(View.VISIBLE);
_chkFaseC.setVisibility(View.VISIBLE);
_lblVb.setVisibility(View.VISIBLE);
_lblVc.setVisibility(View.VISIBLE);
_lblIb.setVisibility(View.VISIBLE);
_lblIc.setVisibility(View.VISIBLE);
_lblTb.setVisibility(View.VISIBLE);
_lblTc.setVisibility(View.VISIBLE);
_lblNvb.setVisibility(View.VISIBLE);
_lblNvc.setVisibility(View.VISIBLE);
_lblFp2.setVisibility(View.VISIBLE);
_lblFp3.setVisibility(View.VISIBLE);
_txtVb.setVisibility(View.VISIBLE);
_txtVc.setVisibility(View.VISIBLE);
_txtIb.setVisibility(View.VISIBLE);
_txtIc.setVisibility(View.VISIBLE);
_txtTb.setVisibility(View.VISIBLE);
_txtTc.setVisibility(View.VISIBLE);
_txtNvb.setVisibility(View.VISIBLE);
_txtNvc.setVisibility(View.VISIBLE);
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.CensoBtnRegistrar:
if(_cmbEstadoElemento.getSelectedItem().toString().equals("...")){
Toast.makeText(this,"No ha seleccionado el estado de la carga del elemento.",Toast.LENGTH_SHORT).show();
}else if(_cmbCantidad.getSelectedItem().toString().equals("0")){
Toast.makeText(this,"No ha ingresado una cantidad valida.",Toast.LENGTH_SHORT).show();
}else if(_txtVatios.getText().toString().isEmpty()||!FcnCenso.verificarRango(_cmbElementos.getSelectedItem().toString(), _txtVatios.getText().toString())){
Toast.makeText(this,"No ha ingresado un valor de vatios validos.",Toast.LENGTH_SHORT).show();
}else{
Registro.clear();
Registro.put("id_orden", OrdenTrabajo);
Registro.put("id_elemento",CensoSQL.StrSelectShieldWhere("amd_elementos_censo", "id_elemento", "descripcion='"+_cmbElementos.getSelectedItem().toString()+"'"));
Registro.put("capacidad", _txtVatios.getText().toString());
Registro.put("cantidad", _cmbCantidad.getSelectedItem().toString());
Registro.put("tipo_carga", _cmbEstadoElemento.getSelectedItem().toString().substring(0,1));
Registro.put("usuario_ins", CedulaUsuario);
if(CensoSQL.InsertRegistro("amd_censo_carga", Registro)){
Tabla = CensoSQL.SelectData("vista_censo_carga", "carga,elemento,vatios,cant,total", "id_orden='"+OrdenTrabajo+"'");
InformacionTabla = CensoTabla.CuerpoTabla(Tabla);
ll.removeAllViews();
ll.addView(InformacionTabla);
Toast.makeText(this,"Elemento ingresado correctamente.",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Error al registrar el elemento.",Toast.LENGTH_SHORT).show();
}
}
_lbltcr.setText("TCR: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"' AND tipo_carga='R'"));
_lbltcd.setText("TCD: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"' AND tipo_carga='D'"));
_lbltcc.setText("TCC: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"'"));
break;
case R.id.CensoBtnEliminar:
if(CensoSQL.DeleteRegistro("amd_censo_carga", "id_orden='"+OrdenTrabajo+"' AND id_elemento='"+CensoSQL.StrSelectShieldWhere("amd_elementos_censo", "id_elemento", "descripcion='"+_cmbElementos.getSelectedItem().toString()+"'")+"' AND tipo_carga='"+_cmbEstadoElemento.getSelectedItem().toString().substring(0,1)+"'")){
Tabla = CensoSQL.SelectData("vista_censo_carga", "carga,elemento,vatios,cant,total", "id_orden='"+OrdenTrabajo+"'");
InformacionTabla = CensoTabla.CuerpoTabla(Tabla);
ll.removeAllViews();
ll.addView(InformacionTabla);
_lbltcr.setText("TCR: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"' AND tipo_carga='R'"));
_lbltcd.setText("TCD: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"' AND tipo_carga='D'"));
_lbltcc.setText("TCC: "+this.CensoSQL.StrSelectShieldWhere("amd_censo_carga","sum(capacidad*cantidad)"," id_orden='"+this.OrdenTrabajo+"'"));
}else{
Toast.makeText(this,"Error al eliminar el elemento.",Toast.LENGTH_SHORT).show();
}
break;
case R.id.ErrorBtnCalcular:
if((_cmbConexion.getSelectedItemPosition()==0)){
if(_txtRevUnidades.getText().toString().isEmpty()){
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}else{
if(_txtRevUnidades.getText().toString().isEmpty()){
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}else{
if(_txtVa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Voltaje",Toast.LENGTH_SHORT).show();
}else{
if(_txtIa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado la Corriente",Toast.LENGTH_SHORT).show();
}else{
if(_txtTa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Tiempo",Toast.LENGTH_SHORT).show();
}else{
if(_txtNva.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Numero de Vueltas",Toast.LENGTH_SHORT).show();
}else{
errorImpulsos = Float.parseFloat(_txtRevUnidades.getText()+"");
if(errorImpulsos>=0){
ValidarCamposLinea();
}else{
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
}else{
if((_cmbConexion.getSelectedItemPosition()==1)){
if(_txtRevUnidades.getText().toString().isEmpty()){
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}else{
if(_txtVb.getText().toString().equals("")||_txtVa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Voltaje FaseB",Toast.LENGTH_SHORT).show();
}else{
if(_txtIb.getText().toString().equals("")||_txtIa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado la Corriente FaseB",Toast.LENGTH_SHORT).show();
}else{
if(_txtTb.getText().toString().equals("")||_txtTa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Tiempo FaseB",Toast.LENGTH_SHORT).show();
}else{
if(_txtNvb.getText().toString().equals("")||_txtNva.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Numero Vueltas FaseB",Toast.LENGTH_SHORT).show();
}else{
errorImpulsos = Float.parseFloat(_txtRevUnidades.getText()+"");
if(errorImpulsos>=0){
ValidarCamposLinea();
}else{
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
else{
if(_cmbConexion.getSelectedItemPosition()==2){
if(_txtRevUnidades.getText().toString().isEmpty()){
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}else{
if(_txtVc.getText().toString().equals("")||_txtVa.getText().toString().equals("")||_txtVb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Voltaje FaseC",Toast.LENGTH_SHORT).show();
}else{
if(_txtIc.getText().toString().equals("")||_txtIa.getText().toString().equals("")||_txtIb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado la Corriente FaseC",Toast.LENGTH_SHORT).show();
}else{
if(_txtTc.getText().toString().equals("")||_txtTa.getText().toString().equals("")||_txtTb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Tiempo Fasec",Toast.LENGTH_SHORT).show();
}else{
if(_txtNvc.getText().toString().equals("")||_txtNva.getText().toString().equals("")||_txtNvb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Numero Vueltas Fasec",Toast.LENGTH_SHORT).show();
}else{
errorImpulsos = Float.parseFloat(_txtRevUnidades.getText()+"");
if(errorImpulsos>=0){
ValidarCamposLinea();
}else{
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
}
}
break;
case R.id.ErrorBtnGuardar:
CensoSQL.DeleteRegistro("amd_pct_error", "id_orden='"+OrdenTrabajo+"' AND tipo_carga='"+_cmbPrueba.getSelectedItem().toString()+"'");
if((_cmbConexion.getSelectedItemPosition()==0)||(_cmbConexion.getSelectedItemPosition()==1)||(_cmbConexion.getSelectedItemPosition()==2)){
Registro.clear();
Registro.put("id_orden", OrdenTrabajo);
Registro.put("tipo_carga", _cmbPrueba.getSelectedItem().toString());
Registro.put("voltaje", _txtVa.getText().toString());
Registro.put("corriente", _txtIa.getText().toString());
Registro.put("tiempo", _txtTa.getText().toString());
Registro.put("vueltas", _txtNva.getText().toString());
Registro.put("total", decimales.format(Math.abs(Float.parseFloat(_lblFp1.getText().toString().replace(",","."))-1)));
Registro.put("rev",errorImpulsos);
Registro.put("usuario_ins", CedulaUsuario);
Registro.put("fp", _lblFp1.getText().toString());
Registro.put("fase", "1");
if(_txtRevUnidades.getText().toString().isEmpty()){
Toast.makeText(this,"No ha ingresado el parametro del medidor de Impulsos o Revoluciones Kw/h.",Toast.LENGTH_SHORT).show();
}else{
if(_txtVa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Voltaje",Toast.LENGTH_SHORT).show();
}else{
if(_txtIa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado la Corriente",Toast.LENGTH_SHORT).show();
}else{
if(_txtTa.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Tiempo",Toast.LENGTH_SHORT).show();
}else{
if(_txtNva.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Numero Vueltas",Toast.LENGTH_SHORT).show();
}else{
if(CensoSQL.InsertRegistro("amd_pct_error", Registro)){
Toast.makeText(this,"Factor de potencia de la fase A guardado correctamente",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Error al guardar el factor de potencia de la fase A.",Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
}
if((_cmbConexion.getSelectedItemPosition()==1)||(_cmbConexion.getSelectedItemPosition()==2)){
Registro.clear();
Registro.put("id_orden", OrdenTrabajo);
Registro.put("tipo_carga", _cmbPrueba.getSelectedItem().toString());
Registro.put("voltaje", _txtVb.getText().toString());
Registro.put("corriente", _txtIb.getText().toString());
Registro.put("tiempo", _txtTb.getText().toString());
Registro.put("vueltas", _txtNvb.getText().toString());
Registro.put("total", decimales.format(Math.abs(Float.parseFloat(_lblFp2.getText().toString().replace(",","."))-1)));
Registro.put("rev",errorImpulsos);
Registro.put("usuario_ins", CedulaUsuario);
Registro.put("fp", _lblFp2.getText().toString());
Registro.put("fase", "2");
if(_txtVb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Voltaje FaseB",Toast.LENGTH_SHORT).show();
}else{
if(_txtIb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado la Corriente FaseB",Toast.LENGTH_SHORT).show();
}else{
if(_txtTb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Tiempo FaseB",Toast.LENGTH_SHORT).show();
}else{
if(_txtNvb.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Numero Vueltas FaseB",Toast.LENGTH_SHORT).show();
}else{
if(CensoSQL.InsertRegistro("amd_pct_error", Registro)){
Toast.makeText(this,"Factor de potencia de la fase B guardado correctamente",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Error al guardar el factor de potencia de la fase B.",Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
if(_cmbConexion.getSelectedItemPosition()==2){
Registro.clear();
Registro.put("id_orden", OrdenTrabajo);
Registro.put("tipo_carga", _cmbPrueba.getSelectedItem().toString());
Registro.put("voltaje", _txtVc.getText().toString());
Registro.put("corriente", _txtIc.getText().toString());
Registro.put("tiempo", _txtTc.getText().toString());
Registro.put("vueltas", _txtNvc.getText().toString());
Registro.put("total", decimales.format(Math.abs(Float.parseFloat(_lblFp3.getText().toString().replace(",","."))-1)));
Registro.put("rev",errorImpulsos);
Registro.put("usuario_ins", CedulaUsuario);
Registro.put("fp", _lblFp3.getText().toString());
Registro.put("fase", "3");
if(_txtVc.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Voltaje FaseC",Toast.LENGTH_SHORT).show();
}else{
if(_txtIc.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado la Corriente FaseC",Toast.LENGTH_SHORT).show();
}else{
if(_txtTc.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Tiempo Fasec",Toast.LENGTH_SHORT).show();
}else{
if(_txtNvc.getText().toString().equals("")){
Toast.makeText(this,"No ha ingresado el Numero Vueltas Fasec",Toast.LENGTH_SHORT).show();
}else{
if(CensoSQL.InsertRegistro("amd_pct_error", Registro)){
Toast.makeText(this,"Factor de potencia de la fase C guardado correctamente",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Error al guardar el factor de potencia de la fase C.",Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
break;
default:
break;
}
}
public boolean ValidarCamposLinea(){
boolean _retorno = true;
if((_cmbConexion.getSelectedItemPosition()==0)||(_cmbConexion.getSelectedItemPosition()==1)||(_cmbConexion.getSelectedItemPosition()==2)){
errorVoltajeLinea = Float.parseFloat(_txtVa.getText().toString());
errorCorrienteLinea = Float.parseFloat(_txtIa.getText().toString());
errorTiempoLinea = Float.parseFloat(_txtTa.getText().toString());
errorVueltasLinea = Float.parseFloat(_txtNva.getText().toString());
if(errorVoltajeLinea>150){
Toast.makeText(this,"El voltaje ingresado en la linea A esta fuera del rango.",Toast.LENGTH_SHORT).show();
_retorno = false;
}else if(errorCorrienteLinea>15){
Toast.makeText(this,"La corrente ingresada en la linea A esta fuera del rango.",Toast.LENGTH_SHORT).show();
_retorno = false;
}else if(_chkFaseA.isChecked()){
errorNumeradorA = 0;
_lblFp1.setText(""+decimales.format(errorNumeradorA));
}else{
errorNumeradorA = (3600000*errorVueltasLinea)/(errorVoltajeLinea*errorCorrienteLinea*errorTiempoLinea*errorImpulsos);
_lblFp1.setText(""+decimales.format(errorNumeradorA));
}
}
if((_cmbConexion.getSelectedItemPosition()==1)||(_cmbConexion.getSelectedItemPosition()==2)){
errorVoltajeLinea = Float.parseFloat(_txtVb.getText().toString());
errorCorrienteLinea = Float.parseFloat(_txtIb.getText().toString());
errorTiempoLinea = Float.parseFloat(_txtTb.getText().toString());
errorVueltasLinea = Float.parseFloat(_txtNvb.getText().toString());
if(errorVoltajeLinea>150){
Toast.makeText(this,"El voltaje ingresado en la linea B esta fuera del rango.",Toast.LENGTH_SHORT).show();
_retorno = false;
}else if(errorCorrienteLinea>15){
Toast.makeText(this,"La corrente ingresada en la linea B esta fuera del rango.",Toast.LENGTH_SHORT).show();
_retorno = false;
}else if(_chkFaseB.isChecked()){
errorNumeradorB = 0;
_lblFp2.setText(""+decimales.format(errorNumeradorB));
}else{
errorNumeradorB = (3600000*errorVueltasLinea)/(errorVoltajeLinea*errorCorrienteLinea*errorTiempoLinea*errorImpulsos);
_lblFp2.setText(""+decimales.format(errorNumeradorB));
}
}
if(_cmbConexion.getSelectedItemPosition()==2){
errorVoltajeLinea = Float.parseFloat(_txtVc.getText().toString());
errorCorrienteLinea = Float.parseFloat(_txtIc.getText().toString());
errorTiempoLinea = Float.parseFloat(_txtTc.getText().toString());
errorVueltasLinea = Float.parseFloat(_txtNvc.getText().toString());
if(errorVoltajeLinea>150){
Toast.makeText(this,"El voltaje ingresado en la linea C esta fuera del rango.",Toast.LENGTH_SHORT).show();
_retorno = false;
}else if(errorCorrienteLinea>15){
Toast.makeText(this,"La corrente ingresada en la linea C esta fuera del rango.",Toast.LENGTH_SHORT).show();
_retorno = false;
}else if(_chkFaseC.isChecked()){
errorNumeradorC = 0;
_lblFp3.setText(""+decimales.format(errorNumeradorC));
}else{
errorNumeradorC = (3600000*errorVueltasLinea)/(errorVoltajeLinea*errorCorrienteLinea*errorTiempoLinea*errorImpulsos);
_lblFp3.setText(""+decimales.format(errorNumeradorC));
}
}
return _retorno;
}
/**Funcion encargada de capturar los cambios al hacer click en cualquier checkbox del activity**/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
switch(buttonView.getId()){
case R.id.ErrorChkFaseA:
if ( isChecked ){
_txtTa.setText("0");
_txtNva.setText("0");
_txtTa.setEnabled(false);
_txtNva.setEnabled(false);
}else{
_txtTa.setEnabled(true);
_txtNva.setEnabled(true);
}
break;
case R.id.ErrorChkFaseB:
if ( isChecked ){
_txtTb.setText("0");
_txtNvb.setText("0");
_txtTb.setEnabled(false);
_txtNvb.setEnabled(false);
}else{
_txtTb.setEnabled(true);
_txtNvb.setEnabled(true);
}
break;
case R.id.ErrorChkFaseC:
if ( isChecked ){
_txtTc.setText("0");
_txtNvc.setText("0");
_txtTc.setEnabled(false);
_txtNvc.setEnabled(false);
}else{
_txtTc.setEnabled(true);
_txtNvc.setEnabled(true);
}
break;
}
}
/**Control de eventos de cambios en los combos**/
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(parent.getId()){
case R.id.ErrorCmbTipoPrueba:
if(_cmbPrueba.getSelectedItem().toString().equals("Baja")){
_cmbConexion.setSelection(AdaptadorTipoPrueba.getPosition("Baja"));
_cmbConexion.setEnabled(false);
}else{
_cmbConexion.setEnabled(true);
}
break;
case R.id.CensoCmbElemento:
_txtVatios.setText(FcnCenso.getVatioMinimo(_cmbElementos.getSelectedItem().toString()));
/*_strVatios = FcnCenso.getRangoVatios(_cmbElementos.getSelectedItem().toString(),10);
AdaptadorVatios = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_strVatios);
_cmbVatios.setAdapter(AdaptadorVatios);
AdaptadorVatios.notifyDataSetChanged();*/
break;
case R.id.ErrorCmbTipoConexion:
OcultarItemsGraficos();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
| gpl-2.0 |
simurayousuke/2017java03 | 课堂练习/week1/java-day4-VehicleManage/VehicleManage/src/biz/MotoManage.java | 346 | package biz;
import entity.*;
public class MotoManage {
public MotoVehicle motoLeaseOut(String motoType) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
Class<?> motoClass=Class.forName("entity."+motoType);
MotoVehicle moto= (MotoVehicle)motoClass.newInstance();
moto.leaseOutFlow();
return moto;
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/corba/src/share/classes/com/sun/tools/corba/se/idl/som/cff/FileLocator.java | 14450 | /*
* Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Licensed Materials - Property of IBM
* 5639-D57 (C) COPYRIGHT International Business Machines Corp. 1997,1998
* RMI-IIOP v1.0
*
*/
package com.sun.tools.corba.se.idl.som.cff;
import java.lang.Exception;
import java.lang.String;
import java.lang.System;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.zip.*;
/**
* FileLocator is an abstract class (one that cannot be instantiated) that
* provides class methods for finding files in the directories or zip
* archives that make up the CLASSPATH.
*
* @author Larry K. Raper
*/
public abstract class FileLocator extends Object {
/* Class variables */
static final Properties pp = System.getProperties ();
static final String classPath = pp.getProperty ("java.class.path", ".");
static final String pathSeparator = pp.getProperty ("path.separator", ";");
/* Instance variables */
/* [None, no instances of this class are ever instantiated.] */
/**
* locateClassFile returns a DataInputStream with mark/reset
* capability that can be used to read the requested class file. The
* CLASSPATH is used to locate the class.
*
* @param classFileName The name of the class to locate. The class name
* should be given in fully-qualified form, for example:
* <pre>
* java.lang.Object
* java.io.DataInputStream
* </pre>
*
* @exception java.io.FileNotFoundException The requested class file
* could not be found.
* @exception java.io.IOException The requested class file
* could not be opened.
*/
public static DataInputStream locateClassFile (String classFileName)
throws FileNotFoundException, IOException {
boolean notFound = true;
StringTokenizer st;
String path = "";
String pathNameForm;
File cf = null;
NamedDataInputStream result;
st = new StringTokenizer (classPath, pathSeparator, false);
pathNameForm = classFileName.replace ('.', File.separatorChar) +
".class";
while (st.hasMoreTokens () && notFound) {
try {path = st.nextToken ();}
catch (NoSuchElementException nse) {break;}
int pLen = path.length ();
String pathLast4 = pLen > 3 ? path.substring (pLen - 4) : "";
if (pathLast4.equalsIgnoreCase (".zip") ||
pathLast4.equalsIgnoreCase (".jar")) {
try {
result = locateInZipFile (path, classFileName, true, true);
if (result == null)
continue;
return (DataInputStream) result;
} catch (ZipException zfe) {
continue;
} catch (IOException ioe) {
continue;
}
} else {
try {cf = new File (path + File.separator + pathNameForm);
} catch (NullPointerException npe) { continue; }
if ((cf != null) && cf.exists ())
notFound = false;
}
}
if (notFound) {
/* Make one last attempt to find the file in the current
* directory
*/
int lastdot = classFileName.lastIndexOf ('.');
String simpleName =
(lastdot >= 0) ? classFileName.substring (lastdot+1) :
classFileName;
result = new NamedDataInputStream (new BufferedInputStream (
new FileInputStream (simpleName + ".class")),
simpleName + ".class", false);
return (DataInputStream) result;
}
result = new NamedDataInputStream (new BufferedInputStream (
new FileInputStream (cf)), path + File.separator + pathNameForm,
false);
return (DataInputStream) result;
}
/**
* locateLocaleSpecificFileInClassPath returns a DataInputStream that
* can be used to read the requested file, but the name of the file is
* determined using information from the current locale and the supplied
* file name (which is treated as a "base" name, and is supplemented with
* country and language related suffixes, obtained from the current
* locale). The CLASSPATH is used to locate the file.
*
* @param fileName The name of the file to locate. The file name
* may be qualified with a partial path name, using '/' as the separator
* character or using separator characters appropriate for the host file
* system, in which case each directory or zip file in the CLASSPATH will
* be used as a base for finding the fully-qualified file.
* Here is an example of how the supplied fileName is used as a base
* for locating a locale-specific file:
*
* <pre>
* Supplied fileName: a/b/c/x.y, current locale: US English
*
* Look first for: a/b/c/x_en_US.y
* (if that fails) Look next for: a/b/c/x_en.y
* (if that fails) Look last for: a/b/c/x.y
*
* All elements of the class path are searched for each name,
* before the next possible name is tried.
* </pre>
*
* @exception java.io.FileNotFoundException The requested class file
* could not be found.
* @exception java.io.IOException The requested class file
* could not be opened.
*/
public static DataInputStream locateLocaleSpecificFileInClassPath (
String fileName) throws FileNotFoundException, IOException {
String localeSuffix = "_" + Locale.getDefault ().toString ();
int lastSlash = fileName.lastIndexOf ('/');
int lastDot = fileName.lastIndexOf ('.');
String fnFront, fnEnd;
DataInputStream result = null;
boolean lastAttempt = false;
if ((lastDot > 0) && (lastDot > lastSlash)) {
fnFront = fileName.substring (0, lastDot);
fnEnd = fileName.substring (lastDot);
} else {
fnFront = fileName;
fnEnd = "";
}
while (true) {
if (lastAttempt)
result = locateFileInClassPath (fileName);
else try {
result = locateFileInClassPath (fnFront + localeSuffix + fnEnd);
} catch (Exception e) { /* ignore */ }
if ((result != null) || lastAttempt)
break;
int lastUnderbar = localeSuffix.lastIndexOf ('_');
if (lastUnderbar > 0)
localeSuffix = localeSuffix.substring (0, lastUnderbar);
else
lastAttempt = true;
}
return result;
}
/**
* locateFileInClassPath returns a DataInputStream that can be used
* to read the requested file. The CLASSPATH is used to locate the file.
*
* @param fileName The name of the file to locate. The file name
* may be qualified with a partial path name, using '/' as the separator
* character or using separator characters appropriate for the host file
* system, in which case each directory or zip file in the CLASSPATH will
* be used as a base for finding the fully-qualified file.
*
* @exception java.io.FileNotFoundException The requested class file
* could not be found.
* @exception java.io.IOException The requested class file
* could not be opened.
*/
public static DataInputStream locateFileInClassPath (String fileName)
throws FileNotFoundException, IOException {
boolean notFound = true;
StringTokenizer st;
String path = "";
File cf = null;
NamedDataInputStream result;
String zipEntryName = File.separatorChar == '/' ? fileName :
fileName.replace (File.separatorChar, '/');
String localFileName = File.separatorChar == '/' ? fileName :
fileName.replace ('/', File.separatorChar);
st = new StringTokenizer (classPath, pathSeparator, false);
while (st.hasMoreTokens () && notFound) {
try {path = st.nextToken ();}
catch (NoSuchElementException nse) {break;}
int pLen = path.length ();
String pathLast4 = pLen > 3 ? path.substring (pLen - 4) : "";
if (pathLast4.equalsIgnoreCase (".zip") ||
pathLast4.equalsIgnoreCase (".jar")) {
try {
result = locateInZipFile (path, zipEntryName, false, false);
if (result == null)
continue;
return (DataInputStream) result;
} catch (ZipException zfe) {
continue;
} catch (IOException ioe) {
continue;
}
} else {
try {cf = new File (path + File.separator + localFileName);
} catch (NullPointerException npe) { continue; }
if ((cf != null) && cf.exists ())
notFound = false;
}
}
if (notFound) {
/* Make one last attempt to find the file in the current
* directory
*/
int lastpart = localFileName.lastIndexOf (File.separator);
String simpleName =
(lastpart >= 0) ? localFileName.substring (lastpart+1) :
localFileName;
result = new NamedDataInputStream (new BufferedInputStream (
new FileInputStream (simpleName)), simpleName, false);
return (DataInputStream) result;
}
result = new NamedDataInputStream (new BufferedInputStream (
new FileInputStream (cf)), path + File.separator + localFileName,
false);
return (DataInputStream) result;
}
/**
* Returns the fully qualified file name associated with the passed
* DataInputStream <i>if the DataInputStream was created using one
* of the static locate methods supplied with this class</i>, otherwise
* returns a zero length string.
*/
public static String getFileNameFromStream (DataInputStream ds) {
if (ds instanceof NamedDataInputStream)
return ((NamedDataInputStream) ds).fullyQualifiedFileName;
return "";
}
/**
* Returns an indication of whether the passed DataInputStream is
* associated with a member of a zip file <i>if the DataInputStream was
* created using one of the static locate methods supplied with this
* class</i>, otherwise returns false.
*/
public static boolean isZipFileAssociatedWithStream (DataInputStream ds) {
if (ds instanceof NamedDataInputStream)
return ((NamedDataInputStream) ds).inZipFile;
return false;
}
private static NamedDataInputStream locateInZipFile (String zipFileName,
String fileName, boolean wantClass, boolean buffered)
throws ZipException, IOException {
ZipFile zf;
ZipEntry ze;
zf = new ZipFile (zipFileName);
if (zf == null)
return null;
String zeName = wantClass ?
fileName.replace ('.', '/') + ".class" :
fileName;
// This code works with JDK 1.0 level SUN zip classes
//
// ze = zf.get (zeName);
// if (ze == null)
// return null;
// return new NamedDataInputStream (
// new BufferedInputStream (new ZipInputStream (ze)),
// zipFileName + '(' +zeName + ')', true);
// This code works with JDK 1.0.2 and JDK 1.1 level SUN zip classes
//
ze = zf.getEntry (zeName);
if (ze == null) {
zf.close(); // D55355, D56419
zf = null;
return null;
}
InputStream istream = zf.getInputStream(ze);
if (buffered)
istream = new BufferedInputStream(istream);
return new NamedDataInputStream (istream,
zipFileName + '(' + zeName + ')', true);
}
}
/**
* This class is used to associate a filename with a DataInputStream
* The host platform's file naming conventions are assumed for the filename.
*
* @author Larry K. Raper
*
*/
/* default access */ class NamedDataInputStream extends DataInputStream {
/* Instance variables */
/**
* The name of the file associated with the DataInputStream.
*/
public String fullyQualifiedFileName;
/**
* Indicates whether or not the file is contained in a .zip file.
*/
public boolean inZipFile;
/* Constructors */
protected NamedDataInputStream (InputStream in, String fullyQualifiedName,
boolean inZipFile) {
super (in);
this.fullyQualifiedFileName = fullyQualifiedName;
this.inZipFile = inZipFile;
}
}
| gpl-2.0 |
toantruonggithub/sguthongtindaotao | app/src/main/java/com/sgulab/thongtindaotao/models/ExamSchedule.java | 1210 | package com.sgulab.thongtindaotao.models;
public class ExamSchedule {
private String subjectId;
private String subjectName;
private int numberOfStudents;
private String date;
private String time;
private int duration;
private String room;
public String getSubjectId() {
return subjectId;
}
public void setSubjectId(String subjectId) {
this.subjectId = subjectId;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
this.numberOfStudents = numberOfStudents;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/java/rmi/server/RMIClassLoader/downloadArrayClass/DownloadArrayClass_Stub.java | 3569 | /*
* Copyright 1999 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
// Stub class generated by rmic, do not edit.
// Contents subject to change without notice.
public final class DownloadArrayClass_Stub
extends java.rmi.server.RemoteStub
implements Receiver, java.rmi.Remote
{
private static final java.rmi.server.Operation[] operations = {
new java.rmi.server.Operation("void receive(java.lang.Object)")
};
private static final long interfaceHash = -953299374608818732L;
private static final long serialVersionUID = 2;
private static boolean useNewInvoke;
private static java.lang.reflect.Method $method_receive_0;
static {
try {
java.rmi.server.RemoteRef.class.getMethod("invoke",
new java.lang.Class[] {
java.rmi.Remote.class,
java.lang.reflect.Method.class,
java.lang.Object[].class,
long.class
});
useNewInvoke = true;
$method_receive_0 = Receiver.class.getMethod("receive", new java.lang.Class[] {java.lang.Object.class});
} catch (java.lang.NoSuchMethodException e) {
useNewInvoke = false;
}
}
// constructors
public DownloadArrayClass_Stub() {
super();
}
public DownloadArrayClass_Stub(java.rmi.server.RemoteRef ref) {
super(ref);
}
// methods from remote interfaces
// implementation of receive(Object)
public void receive(java.lang.Object $param_Object_1)
throws java.rmi.RemoteException
{
try {
if (useNewInvoke) {
ref.invoke(this, $method_receive_0, new java.lang.Object[] {$param_Object_1}, -578858472643205929L);
} else {
java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) this, operations, 0, interfaceHash);
try {
java.io.ObjectOutput out = call.getOutputStream();
out.writeObject($param_Object_1);
} catch (java.io.IOException e) {
throw new java.rmi.MarshalException("error marshalling arguments", e);
}
ref.invoke(call);
ref.done(call);
}
} catch (java.lang.RuntimeException e) {
throw e;
} catch (java.rmi.RemoteException e) {
throw e;
} catch (java.lang.Exception e) {
throw new java.rmi.UnexpectedException("undeclared checked exception", e);
}
}
}
| gpl-2.0 |
donatellosantoro/freESBee | freesbeeGE/test/test/it/unibas/freesbee/ge/comunicazione/g/Conferma8.java | 7844 | package test.it.unibas.freesbee.ge.comunicazione.g;
import it.unibas.freesbee.ge.messaggi.XmlJDomUtil;
import it.unibas.freesbee.ge.modello.CategoriaEventiInterna;
import it.unibas.freesbee.ge.modello.Configurazione;
import it.unibas.freesbee.ge.modello.ConfigurazioniFactory;
import it.unibas.freesbee.ge.modello.GestoreEventi;
import it.unibas.freesbee.ge.modello.PubblicatoreInterno;
import it.unibas.freesbee.ge.modello.Sottoscrittore;
import it.unibas.freesbee.ge.modello.SottoscrizioneInterna;
import it.unibas.freesbee.ge.persistenza.IDAOCategoriaEventiInterna;
import it.unibas.freesbee.ge.persistenza.IDAOGestoreEventi;
import it.unibas.freesbee.ge.persistenza.IDAOPubblicatoreInterno;
import it.unibas.freesbee.ge.persistenza.IDAOSottoscrittore;
import it.unibas.freesbee.ge.persistenza.facade.DAOPubblicatoreInternoFacade;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOCategoriaEventiInternaHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOCostanti;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOGestoreEventiHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOPubblicatoreInternoHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOSottoscrittoreHibernate;
import it.unibas.freesbee.ge.persistenza.hibernate.DAOUtilHibernate;
import it.unibas.freesbee.utilita.ClientPD;
import it.unibas.springfreesbee.ge.ConfigurazioneStatico;
import java.io.FileWriter;
import java.net.URL;
import junit.framework.Assert;
import org.apache.camel.ContextTestSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import test.it.unibas.freesbee.ge.dao.DAOMock;
public class Conferma8 extends ContextTestSupport {
protected Log logger = LogFactory.getLog(this.getClass());
public void testConferma8Init() throws Exception {
logger.info("TEST - 8");
logger.info("Init");
Thread.currentThread().sleep(5000);
FileWriter f = new FileWriter(DAOMock.COMUNICAZIONE_ESTERNA);
String s = "";
f.append(s.subSequence(0, s.length()));
f.flush();
}
public void test8Prima() throws Exception {
logger.info("TEST - 8");
logger.info("Prima");
DAOUtilHibernate.beginTransaction();
IDAOCategoriaEventiInterna daoCategoriaEventi = new DAOCategoriaEventiInternaHibernate();
CategoriaEventiInterna categoriaEventi = daoCategoriaEventi.findByNome(DAOMock.CATEGORIA_EVENTI_INTERNA_ATTIVA_2);
assertNotNull(categoriaEventi);
assertTrue(categoriaEventi.isAttiva());
PubblicatoreInterno pubblicatore = new PubblicatoreInterno(DAOMock.TIPO_SOGGETTO_SPC, DAOMock.NOME_SOGGETTO_P);
DAOPubblicatoreInternoFacade.aggiungiPubblicatoreInterno(categoriaEventi, pubblicatore);
assertTrue(DAOPubblicatoreInternoFacade.isPubblicatoreInternoPerCategoriaEventiInterna(categoriaEventi, pubblicatore));
pubblicatore = new PubblicatoreInterno(DAOMock.TIPO_SOGGETTO_SPC, DAOMock.NOME_SOGGETTO_Q);
DAOPubblicatoreInternoFacade.aggiungiPubblicatoreInterno(categoriaEventi, pubblicatore);
assertTrue(DAOPubblicatoreInternoFacade.isPubblicatoreInternoPerCategoriaEventiInterna(categoriaEventi, pubblicatore));
IDAOGestoreEventi daoGestoreEventi = new DAOGestoreEventiHibernate();
GestoreEventi gesoreEventi = daoGestoreEventi.findByTipoNome(DAOMock.TIPO_SOGGETTO_SPC, DAOMock.NOME_SOGGETTO_GE);
assertNotNull(gesoreEventi);
IDAOSottoscrittore daoSottoscrittore = new DAOSottoscrittoreHibernate();
Sottoscrittore sottoscrittoreGE = daoSottoscrittore.findByTipoNome(DAOMock.TIPO_SOGGETTO_SPC, DAOMock.NOME_SOGGETTO_GE);
assertNull(sottoscrittoreGE);
assertNull(daoCategoriaEventi.findByCategoriaEventiSottoscrittore(categoriaEventi, sottoscrittoreGE));
DAOUtilHibernate.commit();
}
public void testConferma8() throws Exception {
logger.info("TEST - 8");
logger.info("Ricezione Richeista Conferma di Pubblicatori corretta");
try {
//Carico il messaggio che verebbe generato dal GE
URL url = this.getClass().getResource("/dati/g/test8.xml");
Document doc = XmlJDomUtil.caricaXML(url.getFile(), false);
String m = XmlJDomUtil.convertiDocumentToString(doc);
ClientPD clientPD = new ClientPD();
String indirizzo = "http://" + ConfigurazioneStatico.getInstance().getWebservicesIndirizzo() + ":" + ConfigurazioneStatico.getInstance().getWebservicesPort() + DAOCostanti.URL_WSDL_CONSEGNA_MESSAGGI;
logger.info("url: " + indirizzo);
logger.debug(m);
clientPD.invocaPortaDelegata(indirizzo, m);
} catch (Exception ex) {
logger.error(ex.getMessage());
Assert.fail("La conferma dei pubblicvatori categoria ha lanciato eccezione");
}
}
public void testInserimento8VerificaComunicazioneEsterna() throws Exception {
try {
logger.info("TEST - 8");
logger.info("Verifica Comunicazione Esterna Conferma pubblicatori");
Thread.currentThread().sleep(5000);
//Comunicazione inviata
org.jdom.Document doc = XmlJDomUtil.caricaXML(DAOMock.COMUNICAZIONE_ESTERNA, false);
String s = XmlJDomUtil.convertiDocumentToString(doc);
//Comunicazione di test
URL url = this.getClass().getResource("/dati/g/test8Esterno.xml");
doc = XmlJDomUtil.caricaXML(url.getFile(), false);
String m = XmlJDomUtil.convertiDocumentToString(doc);
logger.debug("Comunicazione inviata: ");
logger.debug(XmlJDomUtil.formattaXML(s));
logger.debug("Comunicazione di test:");
logger.debug(XmlJDomUtil.formattaXML(m));
assertEquals(s, m);
} catch (Exception ex) {
logger.error(ex.getMessage());
Assert.fail(ex.getMessage());
}
}
public void test8Dopo() throws Exception {
logger.info("TEST - 8");
logger.info("Dopo");
DAOUtilHibernate.beginTransaction();
IDAOCategoriaEventiInterna daoCategoriaEventiInterna = new DAOCategoriaEventiInternaHibernate();
CategoriaEventiInterna categoriaEventi = daoCategoriaEventiInterna.findByNome(DAOMock.CATEGORIA_EVENTI_INTERNA_ATTIVA_2);
assertNotNull(categoriaEventi);
assertTrue(categoriaEventi.isAttiva());
IDAOGestoreEventi daoGestoreEventi = new DAOGestoreEventiHibernate();
GestoreEventi gesoreEventi = daoGestoreEventi.findByTipoNome(DAOMock.TIPO_SOGGETTO_SPC, DAOMock.NOME_SOGGETTO_GE);
assertNotNull(gesoreEventi);
Configurazione conf = ConfigurazioniFactory.getConfigurazioneIstance();
IDAOPubblicatoreInterno daoPubblicatoreInterno = new DAOPubblicatoreInternoHibernate();
PubblicatoreInterno pubblicatore = daoPubblicatoreInterno.findByTipoNome(conf.getTipoGestoreEventi(), conf.getNomeGestoreEventi());
DAOPubblicatoreInternoFacade.verificaEsistenzaPubblicatoreInterno(categoriaEventi, pubblicatore);
IDAOSottoscrittore daoSottoscrittore = new DAOSottoscrittoreHibernate();
Sottoscrittore sottoscrittoreGE = daoSottoscrittore.findByTipoNome(DAOMock.TIPO_SOGGETTO_SPC, DAOMock.NOME_SOGGETTO_GE);
assertNotNull(sottoscrittoreGE);
SottoscrizioneInterna sottoscrizione = daoCategoriaEventiInterna.findByCategoriaEventiSottoscrittore(categoriaEventi, sottoscrittoreGE);
assertNotNull(sottoscrizione);
assertEquals(1, sottoscrizione.getListaFiltroPublicatore().size());
assertTrue(sottoscrizione.getListaFiltroPublicatore().get(0).getPubblicatore().compareTo(pubblicatore) == 0);
DAOUtilHibernate.commit();
}
}
| gpl-2.0 |
h3xstream/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01535.java | 4138 | /**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Dave Wichers
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/weakrand-03/BenchmarkTest01535")
public class BenchmarkTest01535 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheParameter("BenchmarkTest01535");
if (param == null) param = "";
String bar = new Test().doSomething(request, param);
try {
double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();
String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.
String user = "SafeDonna";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; !foundUser && i < cookies.length; i++) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
}
if (foundUser) {
response.getWriter().println(
"Welcome back: " + user + "<br/>"
);
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
rememberMe.setHttpOnly(true);
rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet
// e.g., /benchmark/sql-01/BenchmarkTest01001
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(
user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>"
);
}
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
throw new ServletException(e);
}
response.getWriter().println(
"Weak Randomness Test java.security.SecureRandom.nextDouble() executed"
);
} // end doPost
private class Test {
public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar = "";
if (param != null) {
bar = new String( org.apache.commons.codec.binary.Base64.decodeBase64(
org.apache.commons.codec.binary.Base64.encodeBase64( param.getBytes() ) ));
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
hjp4lucifer/lucifer-sdop | android/sdop/src/cn/lucifer/sdop/domain/HeaderDetail.java | 240 | package cn.lucifer.sdop.domain;
public class HeaderDetail {
public BpDetail bpDetail;
public EnergyDetail energyDetail;
public int gold;
public int ms;
public int msMax;
public int pilot;
public int pilotMax;
}
| gpl-2.0 |
swatkatz/problem-solving | src/main/java/org/swati/problemSolving/permutations/PalindromSubSeq.java | 1687 | package org.swati.problemSolving.permutations;
/* Write a function to compute the maximum length palindromic sub-sequence of an array.
A palindrome is a sequence which is equal to its reverse.
A sub-sequence of an array is a sequence which can be constructed by removing elements of the array.
Ex: Given [4,1,2,3,4,5,6,5,4,3,4,4,4,4,4,4,4] should return 10 (all 4's) */
public class PalindromSubSeq {
public static int maxLengthPalindrome(int[] values) {
int startSeq = 0;
int maxCount = 0;
while(startSeq < values.length) {
int tempStart = startSeq;
for (int endSeq = values.length - 1; endSeq > startSeq; endSeq--) {
if (isPalindrome(startSeq, endSeq, values)) {
if (maxCount < (endSeq - startSeq + 1)) {
maxCount = endSeq - startSeq + 1;
}
startSeq = endSeq + 1;
break;
}
}
if (startSeq == tempStart) {
startSeq++;
}
}
return maxCount;
}
private static boolean isPalindrome(int start, int end, int[] values) {
int backCount = end;
int size = end - start + 1;
for (int i = start; i < start + size/2; i++) {
if (values[i] != values[backCount]) {
return false;
}
backCount--;
}
return true;
}
public static void main(String args[]) {
int[] values = {4, 1, 2, 3, 4, 5, 6, 5, 4, 3, 4, 4, 2, 2, 2, 2, 2, 4, 4};
System.out.println("max length palindrome sub seq is " + maxLengthPalindrome(values));
}
}
| gpl-2.0 |
SFINA/SFINA | core/src/agents/communication/ProgressType.java | 1010 | /*
* Copyright (C) 2016 SFINA 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package agents.communication;
/**
* Return Type of function readyToPress() of AbstractCommunicationAgent.
* @author Ben
*/
public enum ProgressType {
DO_NOTHING,
SKIP_NEXT_ITERATION,
DO_NEXT_ITERATION,
DO_NEXT_STEP,
DO_DEFAULT
} | gpl-2.0 |
OpenNMS/opennms-pmatrix | vaadin-pmatrix/src/test/java/org/opennms/features/vaadin/pmatrix/manual/CalculationDataMarshalTest.java | 7300 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2010-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.features.vaadin.pmatrix.manual;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculator;
import org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorEmaImpl;
import org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository;
import org.opennms.features.vaadin.pmatrix.model.NameValuePair;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.support.StaticApplicationContext;
import junit.framework.TestCase;
public class CalculationDataMarshalTest extends TestCase {
// values used only for this test
//File file = new File("target/data-marshaltestfile.xml");
//private static String archiveFileLocation="file:/home/isawesome/devel/gitrepo/entimoss-misc/opennms-pmatrix/vaadin-pmatrix/PmatrixHistory/historyConfig.xml";
private static String archiveFileDirectoryLocation="file:./PmatrixHistory";
private static String archiveFileName="data-marshaltestfile.xml";
private static int archiveFileMaxNumber=2;
// static so that lives between tests on this class
private static StaticApplicationContext appContext= new StaticApplicationContext();
// set up application context
public void testLoadAppContext(){
System.out.println("start of test:testLoadAppContext()");
// set up app context to load ResourceLoader
appContext.registerSingleton("beanPostProcessor", CommonAnnotationBeanPostProcessor.class);
appContext.registerSingleton("pmatrixDpdCalculatorRepository", PmatrixDpdCalculatorRepository.class);
appContext.refresh();
System.out.println("end of test:testLoadAppContext()");
}
public void testMarshalData(){
System.out.println("start of test:testMarshalData()");
PmatrixDpdCalculatorRepository pmatrixDpdCalculatorRepository=
(PmatrixDpdCalculatorRepository) appContext.getBean("pmatrixDpdCalculatorRepository");
pmatrixDpdCalculatorRepository.setArchiveFileDirectoryLocation(archiveFileDirectoryLocation);
pmatrixDpdCalculatorRepository.setArchiveFileMaxNumber(archiveFileMaxNumber);
pmatrixDpdCalculatorRepository.setArchiveFileName(archiveFileName);
// create new PmatrixDpdCalculator
PmatrixDpdCalculatorEmaImpl pmatrixDpdCalculator= new PmatrixDpdCalculatorEmaImpl();
pmatrixDpdCalculator.setAlpha(10d);
pmatrixDpdCalculator.setLatestDataValue(1010d);
pmatrixDpdCalculator.setLatestTimestamp(new Date().getTime());
pmatrixDpdCalculator.setMovingAverage(2020d);
pmatrixDpdCalculator.setMovingVariance(3030d);
pmatrixDpdCalculator.setPrevDataValue(3040d);
pmatrixDpdCalculator.setPreviousTimestamp(new Date().getTime());
// create configuration for calculator
List<NameValuePair> configuration = new ArrayList<NameValuePair>();
NameValuePair nvp= new NameValuePair();
nvp.setName("first name");
nvp.setValue("first value");
configuration.add(nvp);
NameValuePair nvp2= new NameValuePair();
nvp2.setName("second name");
nvp2.setValue("second value");
configuration.add(nvp2);
pmatrixDpdCalculator.setConfiguration(configuration );
pmatrixDpdCalculatorRepository.getDataPointMap().put("filename", pmatrixDpdCalculator);
//File file = new File("target/data-marshaltestfile.xml");
pmatrixDpdCalculatorRepository.setArchiveFileDirectoryLocation(archiveFileDirectoryLocation);
pmatrixDpdCalculatorRepository.setArchiveFileName(archiveFileName);
pmatrixDpdCalculatorRepository.setArchiveFileMaxNumber(2);
pmatrixDpdCalculatorRepository.setPersistHistoricData(true);
boolean success = pmatrixDpdCalculatorRepository.persist();
if(success) {
System.out.println("marshalled to file:'"+ pmatrixDpdCalculatorRepository.getArchiveFileDirectoryLocation()
+File.separator+pmatrixDpdCalculatorRepository.getArchiveFileName()+"'");
} else {
System.out.println("did not marshal to file:'"+ pmatrixDpdCalculatorRepository.getArchiveFileDirectoryLocation()
+File.separator+pmatrixDpdCalculatorRepository.getArchiveFileName()+"'");
}
appContext.close();
System.out.println("end of test:testMarshalData()");
}
public void testUnMarshalData(){
System.out.println("start of test:testUnMarshalData()");
PmatrixDpdCalculatorRepository pmatrixDpdCalculatorRepository=
(PmatrixDpdCalculatorRepository) appContext.getBean("pmatrixDpdCalculatorRepository");
pmatrixDpdCalculatorRepository.setArchiveFileDirectoryLocation(archiveFileDirectoryLocation);
pmatrixDpdCalculatorRepository.setArchiveFileName(archiveFileName);
pmatrixDpdCalculatorRepository.setArchiveFileMaxNumber(2);
pmatrixDpdCalculatorRepository.setPersistHistoricData(true);
boolean success = pmatrixDpdCalculatorRepository.load();
if(success) {
System.out.println("unmarshalled from file:''"+ pmatrixDpdCalculatorRepository.getArchiveFileDirectoryLocation()
+File.separator+pmatrixDpdCalculatorRepository.getArchiveFileName()+"'");
Map<String, PmatrixDpdCalculator> dataPointMap = pmatrixDpdCalculatorRepository.getDataPointMap();
PmatrixDpdCalculatorEmaImpl pmatrixDpdCalculator;
for (String filename:dataPointMap.keySet()){
pmatrixDpdCalculator = (PmatrixDpdCalculatorEmaImpl)dataPointMap.get(filename);
System.out.println("pmatrixDpdCalculator:"
+ " pmatrixDpdCalculator.getAlpha(10d): "+pmatrixDpdCalculator.getAlpha()
+ " pmatrixDpdCalculator.getLatestDataValue(1010d): "+pmatrixDpdCalculator.getLatestDataValue()
+ " : "
);
if(pmatrixDpdCalculator.getConfiguration()!=null){
System.out.println(" configuration:");
for (NameValuePair nvp : pmatrixDpdCalculator.getConfiguration()){
System.out.println(" name:"+nvp.getName()
+ " value:"+nvp.getValue());
}
}
}
} else {
System.out.println("did not unmarshal from file:'"+ pmatrixDpdCalculatorRepository.getArchiveFileDirectoryLocation()
+File.separator+pmatrixDpdCalculatorRepository.getArchiveFileName()+"'");
}
System.out.println("end of test:testUnMarshalData()");
}
}
| gpl-2.0 |
ezScrum/ezScrum_1.7.2_export | test/ntut/csie/ezScrum/web/control/SprintPlanHelperTest.java | 24045 | package ntut.csie.ezScrum.web.control;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import junit.framework.TestCase;
import ntut.csie.ezScrum.iteration.core.ISprintPlanDesc;
import ntut.csie.ezScrum.test.CreateData.CopyProject;
import ntut.csie.ezScrum.test.CreateData.CreateProject;
import ntut.csie.ezScrum.test.CreateData.CreateSprint;
import ntut.csie.ezScrum.test.CreateData.InitialSQL;
import ntut.csie.ezScrum.test.CreateData.ezScrumInfoConfig;
import ntut.csie.ezScrum.web.form.IterationPlanForm;
import ntut.csie.ezScrum.web.helper.SprintPlanHelper;
public class SprintPlanHelperTest extends TestCase {
private SprintPlanHelper helper;
private CreateProject CP;
private CreateSprint CS;
private int ProjectCount = 1;
private int SprintCount = 3;
private ezScrumInfoConfig config = new ezScrumInfoConfig();
public SprintPlanHelperTest(String testMethod) {
super(testMethod);
}
protected void setUp() throws Exception {
InitialSQL ini = new InitialSQL(config);
ini.exe(); // 初始化 SQL
this.CP = new CreateProject(this.ProjectCount);
this.CP.exeCreate();
this.CS = new CreateSprint(this.SprintCount, this.CP);
this.CS.exe();
}
protected void tearDown() throws IOException, Exception {
InitialSQL ini = new InitialSQL(config);
ini.exe(); // 初始化 SQL
CopyProject copyProject = new CopyProject(this.CP);
copyProject.exeDelete_Project(); // 刪除測試檔案
}
// public void testcurrentSprintID() {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
//
// int cur = this.SprintCount/2 + 1; // 當下的 sprint 為所有新建 sprints 的中間值
//
// assertEquals(cur, this.helper.currentSprintID());
// }
//
// public void testloadPlans() {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// ISprintPlanDesc[] SprintPlans = this.helper.loadPlans();
// assertEquals(this.CS.getSprintCount(), SprintPlans.length);
//
// for (int i=0 ; i<SprintPlans.length ; i++) {
// assertEquals(this.CS.getDefault_SPRINT_GOAL(i+1), SprintPlans[i].getGoal());
// assertEquals("2", SprintPlans[i].getInterval());
// assertEquals("2", SprintPlans[i].getMemberNumber());
// assertEquals("10", SprintPlans[i].getAvailableDays());
// assertEquals("100", SprintPlans[i].getFocusFactor());
// assertEquals("LAB 1321", SprintPlans[i].getDemoPlace());
// }
// }
//
// public void testloadListPlans() {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// List<ISprintPlanDesc> SprintPlans = this.helper.loadListPlans();
// assertEquals(this.CS.getSprintCount(), SprintPlans.size());
//
// for (int i=0 ; i<SprintPlans.size() ; i++) {
// assertEquals(this.CS.getDefault_SPRINT_GOAL(i+1), SprintPlans.get(i).getGoal());
// assertEquals("2", SprintPlans.get(i).getInterval());
// assertEquals("2", SprintPlans.get(i).getMemberNumber());
// assertEquals("10", SprintPlans.get(i).getAvailableDays());
// assertEquals("100", SprintPlans.get(i).getFocusFactor());
// assertEquals("LAB 1321", SprintPlans.get(i).getDemoPlace());
// }
// }
//
// public void testloadPlan() {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// ISprintPlanDesc SprintPlan = this.helper.loadPlan("1");
//
// assertEquals(this.CS.getDefault_SPRINT_GOAL(1), SprintPlan.getGoal());
// assertEquals("2", SprintPlan.getInterval());
// assertEquals("2", SprintPlan.getMemberNumber());
// assertEquals("10", SprintPlan.getAvailableDays());
// assertEquals("100", SprintPlan.getFocusFactor());
// assertEquals("LAB 1321", SprintPlan.getDemoPlace());
//
// // 除錯,測試輸入不存在的 sprintID,會回傳 new SprintPlanDesc
// ISprintPlanDesc nullSprintPlan = this.helper.loadPlan("1000");
// assertEquals("-1", nullSprintPlan.getID());
// assertEquals(null, nullSprintPlan.getGoal()); // ========== 程式設計此欄為 null =========
// assertEquals("", nullSprintPlan.getInterval());
// assertEquals("0", nullSprintPlan.getMemberNumber());
// assertEquals("0", nullSprintPlan.getAvailableDays());
// assertEquals("", nullSprintPlan.getFocusFactor());
// assertEquals("", nullSprintPlan.getDemoPlace());
// assertEquals("", nullSprintPlan.getDemoDate());
// assertEquals("", nullSprintPlan.getStartDate());
// assertEquals("", nullSprintPlan.getEndDate());
// assertEquals("", nullSprintPlan.getNotes());
// assertEquals("", nullSprintPlan.getNumber());
//
// ISprintPlanDesc nullSprintPlan2 = this.helper.loadPlan("XXX");
// assertEquals("-1", nullSprintPlan2.getID());
// assertEquals(null, nullSprintPlan.getGoal()); // ========== 程式設計此欄為 null =========
// assertEquals("", nullSprintPlan2.getInterval());
// assertEquals("0", nullSprintPlan2.getMemberNumber());
// assertEquals("0", nullSprintPlan2.getAvailableDays());
// assertEquals("", nullSprintPlan2.getFocusFactor());
// assertEquals("", nullSprintPlan2.getDemoPlace());
// assertEquals("", nullSprintPlan2.getDemoDate());
// assertEquals("", nullSprintPlan2.getStartDate());
// assertEquals("", nullSprintPlan2.getEndDate());
// assertEquals("", nullSprintPlan2.getNotes());
// assertEquals("", nullSprintPlan2.getNumber());
// }
//
// public void testloadCurrentPlan() throws Exception {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// int cur = this.SprintCount/2 + 1; // 當下的 sprint 為所有新建 sprints 的中間值
//
// ISprintPlanDesc SprintPlan = this.helper.loadCurrentPlan();
// assertEquals(this.CS.getDefault_SPRINT_GOAL(cur), SprintPlan.getGoal());
// assertEquals("2", SprintPlan.getInterval());
// assertEquals("2", SprintPlan.getMemberNumber());
// assertEquals("10", SprintPlan.getAvailableDays());
// assertEquals("100", SprintPlan.getFocusFactor());
// assertEquals("LAB 1321", SprintPlan.getDemoPlace());
//
//
// // 清空 sprint plan
// InitialSQL ini = new InitialSQL(ezScrumInfo);
// ini.exe(); // 初始化 SQL
//
// CopyProject copyProject = new CopyProject(this.CP);
// copyProject.exeDelete_Project(); // 刪除測試檔案
//
// this.CP = new CreateProject(this.ProjectCount);
// this.CP.exe();
//
// // 除錯,當沒有產生任何 sprint
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// ISprintPlanDesc nullSprintPlan = this.helper.loadCurrentPlan();
// assertEquals(null, nullSprintPlan);
//
// // 還有輸入一筆 SprintPlans,但是今天日期不為其中一 SprintPlan 的測試未寫
// }
//
// public void testgetNextDemoDate() {
// // !! 超級複雜 !!
//
//
// }
//
// public void testloadPlan_int() {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// ISprintPlanDesc SprintPlan = this.helper.loadPlan(1); // 參數為數字
//
// assertEquals(this.CS.getDefault_SPRINT_GOAL(1), SprintPlan.getGoal());
// assertEquals("2", SprintPlan.getInterval());
// assertEquals("2", SprintPlan.getMemberNumber());
// assertEquals("10", SprintPlan.getAvailableDays());
// assertEquals("100", SprintPlan.getFocusFactor());
// assertEquals("LAB 1321", SprintPlan.getDemoPlace());
//
// // 除錯,測試輸入不存在的 sprintID,會回傳 new SprintPlanDesc
// ISprintPlanDesc nullSprintPlan = this.helper.loadPlan("1000");
// assertEquals("-1", nullSprintPlan.getID());
// assertEquals(null, nullSprintPlan.getGoal()); // ========== 程式設計此欄為 null =========
// assertEquals("", nullSprintPlan.getInterval());
// assertEquals("0", nullSprintPlan.getMemberNumber());
// assertEquals("0", nullSprintPlan.getAvailableDays());
// assertEquals("", nullSprintPlan.getFocusFactor());
// assertEquals("", nullSprintPlan.getDemoPlace());
// assertEquals("", nullSprintPlan.getDemoDate());
// assertEquals("", nullSprintPlan.getStartDate());
// assertEquals("", nullSprintPlan.getEndDate());
// assertEquals("", nullSprintPlan.getNotes());
// assertEquals("", nullSprintPlan.getNumber());
//
// ISprintPlanDesc nullSprintPlan2 = this.helper.loadPlan("XXX");
// assertEquals("-1", nullSprintPlan2.getID());
// assertEquals(null, nullSprintPlan.getGoal()); // ========== 程式設計此欄為 null =========
// assertEquals("", nullSprintPlan2.getInterval());
// assertEquals("0", nullSprintPlan2.getMemberNumber());
// assertEquals("0", nullSprintPlan2.getAvailableDays());
// assertEquals("", nullSprintPlan2.getFocusFactor());
// assertEquals("", nullSprintPlan2.getDemoPlace());
// assertEquals("", nullSprintPlan2.getDemoDate());
// assertEquals("", nullSprintPlan2.getStartDate());
// assertEquals("", nullSprintPlan2.getEndDate());
// assertEquals("", nullSprintPlan2.getNotes());
// assertEquals("", nullSprintPlan2.getNumber());
// }
//
// public void testgetPlanNumbers() throws Exception {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// assertEquals(this.CS.getSprintCount(), this.helper.getPlanNumbers());
//
// // 清空 sprint plan
// InitialSQL ini = new InitialSQL(ezScrumInfo);
// ini.exe(); // 初始化 SQL
//
// CopyProject copyProject = new CopyProject(this.CP);
// copyProject.exeDelete_Project(); // 刪除測試檔案
//
// this.CP = new CreateProject(this.ProjectCount);
// this.CP.exe();
//
// // 除錯,當沒有產生任何 sprint
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
// assertEquals(0, this.helper.getPlanNumbers());
// }
//
// public void testgetSprintPlanForm() {
// // 此 method 沒有被呼叫使用
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
//
// // 設定參數資料
// IterationPlanForm form = new IterationPlanForm();
// form.setID(Integer.toString(this.CS.getSprintCount()+1));
// form.setAvailableDays("10");
// form.setIterStartDate("2010/10/10");
// form.setDemoDate("2010/10/24");
// form.setDemoPlace("Lab 1321");
// form.setFocusFactor("100");
// form.setGoal("Get ONE PIECE !!");
// form.setIterIterval("2");
// form.setIterMemberNumber("2");
// form.setNotes("成為海賊王");
// }
//
// public void testsaveIterationPlanForm() {
// this.helper = new SprintPlanHelper(this.CP.getIProjectList().get(0));
//
// // 設定參數資料
// IterationPlanForm form = new IterationPlanForm();
// form.setID(Integer.toString(this.CS.getSprintCount()+1));
// form.setAvailableDays("10");
// form.setIterStartDate("2010/10/10");
// form.setDemoDate("2010/10/24");
// form.setDemoPlace("Lab 1321");
// form.setFocusFactor("100");
// form.setGoal("Get ONE PIECE !!");
// form.setIterIterval("2");
// form.setIterMemberNumber("2");
// form.setNotes("成為海賊王");
//
// helper.saveIterationPlanForm(form);
// ISprintPlanDesc SprintPlan = this.helper.loadPlan(form.getID());
// assertEquals(form.getID(), SprintPlan.getID());
// assertEquals(form.getGoal(), SprintPlan.getGoal());
// assertEquals(form.getIterIterval(), SprintPlan.getInterval());
// assertEquals(form.getIterMemberNumber(), SprintPlan.getMemberNumber());
// assertEquals(form.getAvailableDays(), SprintPlan.getAvailableDays());
// assertEquals(form.getFocusFactor(), SprintPlan.getFocusFactor());
// assertEquals(form.getDemoPlace(), SprintPlan.getDemoPlace());
// assertEquals(form.getDemoDate(), SprintPlan.getDemoDate());
// assertEquals(form.getNotes(), SprintPlan.getNotes());
// }
//
/*-----------------------------------------------------------
* 測試Focus Factor與AvaliableDays輸入為0的處理方式
-------------------------------------------------------------*/
public void testFocusFactorAndAvailableDays()
{
System.out.println("testFocusFactorAndAvailableDays: 請找時間把測試失敗原因找出來~");
/*
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
//設定一個Focus為零的Sprint
IterationPlanForm form = new IterationPlanForm();
form.setID(Integer.toString(this.CS.getSprintCount()+1));
form.setAvailableDays("10");
form.setIterStartDate("2010/10/10");
form.setDemoDate("2010/10/24");
form.setDemoPlace("Lab 1321");
form.setFocusFactor("0");
form.setGoal("Get ONE PIECE !!");
form.setIterIterval("2");
form.setIterMemberNumber("2");
form.setNotes("成為海賊王");
helper.saveIterationPlanForm(form);
ISprintPlanDesc SprintPlan = this.helper.loadPlan(form.getID());
assertEquals(form.getID(), SprintPlan.getID());
assertEquals(form.getGoal(), SprintPlan.getGoal());
assertEquals(form.getIterIterval(), SprintPlan.getInterval());
assertEquals(form.getIterMemberNumber(), SprintPlan.getMemberNumber());
assertEquals(form.getAvailableDays(), SprintPlan.getAvailableDays());
assertEquals(form.getFocusFactor(), SprintPlan.getFocusFactor());
assertEquals(form.getDemoPlace(), SprintPlan.getDemoPlace());
assertEquals(form.getDemoDate(), SprintPlan.getDemoDate());
assertEquals(form.getNotes(), SprintPlan.getNotes());
//設定一個AvailableDays為0的Sprint
form = new IterationPlanForm();
form.setID(Integer.toString(this.CS.getSprintCount()+1));
form.setAvailableDays("0");
form.setIterStartDate("2010/10/10");
form.setDemoDate("2010/10/24");
form.setDemoPlace("Lab 1321");
form.setFocusFactor("100");
form.setGoal("Get ONE PIECE !!");
form.setIterIterval("2");
form.setIterMemberNumber("2");
form.setNotes("成為海賊王");
helper.saveIterationPlanForm(form);
SprintPlan = this.helper.loadPlan(form.getID());
assertEquals(form.getID(), SprintPlan.getID());
assertEquals(form.getGoal(), SprintPlan.getGoal());
assertEquals(form.getIterIterval(), SprintPlan.getInterval());
assertEquals(form.getIterMemberNumber(), SprintPlan.getMemberNumber());
assertEquals(form.getAvailableDays(), SprintPlan.getAvailableDays());
assertEquals(form.getFocusFactor(), SprintPlan.getFocusFactor());
assertEquals(form.getDemoPlace(), SprintPlan.getDemoPlace());
assertEquals(form.getDemoDate(), SprintPlan.getDemoDate());
assertEquals(form.getNotes(), SprintPlan.getNotes());
//設定AvailableDays與FocusFactor為0的Sprint
form = new IterationPlanForm();
form.setID(Integer.toString(this.CS.getSprintCount()+1));
form.setAvailableDays("0");
form.setIterStartDate("2010/10/10");
form.setDemoDate("2010/10/24");
form.setDemoPlace("Lab 1321");
form.setFocusFactor("0");
form.setGoal("Get ONE PIECE !!");
form.setIterIterval("2");
form.setIterMemberNumber("2");
form.setNotes("成為海賊王");
helper.saveIterationPlanForm(form);
SprintPlan = this.helper.loadPlan(form.getID());
assertEquals(form.getID(), SprintPlan.getID());
assertEquals(form.getGoal(), SprintPlan.getGoal());
assertEquals(form.getIterIterval(), SprintPlan.getInterval());
assertEquals(form.getIterMemberNumber(), SprintPlan.getMemberNumber());
assertEquals(form.getAvailableDays(), SprintPlan.getAvailableDays());
assertEquals(form.getFocusFactor(), SprintPlan.getFocusFactor());
assertEquals(form.getDemoPlace(), SprintPlan.getDemoPlace());
assertEquals(form.getDemoDate(), SprintPlan.getDemoDate());
assertEquals(form.getNotes(), SprintPlan.getNotes());
*/
}
public void testdeleteIterationPlan() {
System.out.println("testdeleteIterationPlan: 請找時間把測試失敗原因找出來~");
/*
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
int lastID = this.helper.getLastSprintId();
this.helper.deleteIterationPlan(Integer.toString(lastID));
ISprintPlanDesc nullSprintPlan = this.helper.loadPlan(lastID);
assertEquals("-1", nullSprintPlan.getID());
assertEquals(null, nullSprintPlan.getGoal()); // ========== 程式設計此欄為 null =========
assertEquals("", nullSprintPlan.getInterval());
assertEquals("0", nullSprintPlan.getMemberNumber());
assertEquals("0", nullSprintPlan.getAvailableDays());
assertEquals("0", nullSprintPlan.getFocusFactor());
assertEquals("", nullSprintPlan.getDemoPlace());
assertEquals("", nullSprintPlan.getDemoDate());
assertEquals("", nullSprintPlan.getStartDate());
assertEquals("", nullSprintPlan.getEndDate());
assertEquals("", nullSprintPlan.getNotes());
// assertEquals("", nullSprintPlan.getNumber());
*/
}
public void testgetProjectStartDate() throws Exception {
CopyProject copyProject = new CopyProject(this.CP);
copyProject.exeDelete_Project(); // 刪除測試檔案
InitialSQL ini = new InitialSQL(config);
ini.exe(); // 初始化 SQL
this.CP = new CreateProject(this.ProjectCount);
this.CP.exeCreate();
this.CS = new CreateSprint(1, this.CP);
this.CS.exe();
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date Today = cal.getTime();
assertEquals(format.format(Today), format.format(this.helper.getProjectStartDate()));
}
public void testgetProjectEndDate() throws Exception {
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
int lastID = this.helper.getLastSprintId();
ISprintPlanDesc SprintPlan = this.helper.loadPlan(lastID);
Date ProjectEndDate = this.helper.getProjectEndDate();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
assertEquals(SprintPlan.getEndDate(), format.format(ProjectEndDate).toString());
// 清空 sprint
CopyProject copyProject = new CopyProject(this.CP);
copyProject.exeDelete_Project(); // 刪除測試檔案
InitialSQL ini = new InitialSQL(config);
ini.exe(); // 初始化 SQL
this.CP = new CreateProject(this.ProjectCount);
this.CP.exeCreate();
// 除錯
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
Date nullProjectEndDate = this.helper.getProjectEndDate(); // ==========================
assertEquals(null, nullProjectEndDate); // ==========================
}
public void testgetLastSprintId() throws Exception {
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
int lastID = this.helper.getLastSprintId();
assertEquals(this.CS.getSprintCount(), lastID);
// 清空 sprint
CopyProject copyProject = new CopyProject(this.CP);
copyProject.exeDelete_Project(); // 刪除測試檔案
InitialSQL ini = new InitialSQL(config);
ini.exe(); // 初始化 SQL
this.CP = new CreateProject(this.ProjectCount);
this.CP.exeCreate();
lastID = this.helper.getLastSprintId();
assertEquals(-1, lastID);
}
public void testgetLastSprintPlanNumber() throws Exception {
System.out.println("testgetLastSprintPlanNumber: 請找時間把測試失敗原因找出來~");
/*
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
int lastID = this.helper.getLastSprintId();
assertEquals(this.CS.getSprintCount(), lastID);
// 清空 sprint
CopyProject copyProject = new CopyProject(this.CP);
copyProject.exeDelete_Project(); // 刪除測試檔案
InitialSQL ini = new InitialSQL(config);
ini.exe(); // 初始化 SQL
this.CP = new CreateProject(this.ProjectCount);
this.CP.exeCreate();
lastID = this.helper.getLastSprintId();
assertEquals(0, lastID);
*/
}
public void testgetSprintIDbyDate() {
System.out.println("testgetSprintIDbyDate: 請找時間把測試失敗原因找出來~");
/*
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
int cur = this.SprintCount/2 + 1; // 當下的 sprint 為所有新建 sprints 的中間值
ISprintPlanDesc SprintPlan = this.helper.loadPlan(cur);
Calendar cal = Calendar.getInstance();
Date Today = cal.getTime();
assertEquals(cur, this.helper.getSprintIDbyDate(Today));
// 將時間加到下一個 sprint
cal.add(Calendar.DAY_OF_YEAR, Integer.parseInt(SprintPlan.getInterval()+5));
Date NextSprintDay = cal.getTime();
assertEquals(cur+1, this.helper.getSprintIDbyDate(NextSprintDay));
// 將時間加到超出 sprint 範圍之後
cal.add(Calendar.DAY_OF_YEAR, 1000);
Date DefaultDay = cal.getTime();
assertEquals(-1, this.helper.getSprintIDbyDate(DefaultDay));
// 將時間回到早於 sprint 範圍之前
cal.add(Calendar.DAY_OF_YEAR, -5000);
Date DefaultDay2 = cal.getTime();
assertEquals(-1, this.helper.getSprintIDbyDate(DefaultDay2));
*/
}
public void testmoveSprint() {
this.helper = new SprintPlanHelper(this.CP.getProjectList().get(0));
// EndSprint 是要被交換的 sprint
ISprintPlanDesc OldSprint = this.helper.loadPlan(this.CS.getSprintCount());
// 再新增一筆 sprint 4 用來移動
// 設定參數資料
IterationPlanForm form = new IterationPlanForm();
form.setID(Integer.toString(this.CS.getSprintCount()+1));
form.setAvailableDays("10");
form.setDemoPlace("1321 LUB");
form.setFocusFactor("200");
form.setGoal("Get ONE PIECE !!");
form.setIterIterval("2");
form.setIterMemberNumber("2");
form.setNotes("成為海賊王");
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date Start = new Date(OldSprint.getEndDate());
Calendar cal = Calendar.getInstance();
cal.setTime(Start);
cal.add(Calendar.DAY_OF_YEAR, 1); // 開始日為上一個 sprint 的下一天
form.setIterStartDate(format.format(cal.getTime()));
Date Demo = new Date(OldSprint.getEndDate());
cal = Calendar.getInstance();
cal.setTime(Demo);
cal.add(Calendar.DAY_OF_YEAR, 14); // 兩個禮拜
form.setDemoDate(format.format(cal.getTime()));
this.helper.saveIterationPlanForm(form); // 存入成為一筆新的 sprint
ISprintPlanDesc NewSprint = this.helper.loadPlan(this.helper.getLastSprintId());
// 移動 sprint 3 與 sprint 4
int oldID = this.CS.getSprintCount();
int newID = this.helper.getLastSprintId();
this.helper.moveSprint(oldID, newID);
// old ID 的資訊應該變成 sprint 4 資訊
ISprintPlanDesc oldID_sprintInfo = this.helper.loadPlan(oldID);
assertEquals(Integer.toString(oldID), oldID_sprintInfo.getID());
assertEquals("10", oldID_sprintInfo.getAvailableDays());
assertEquals(OldSprint.getStartDate(), oldID_sprintInfo.getStartDate());
assertEquals("1321 LUB", oldID_sprintInfo.getDemoPlace());
assertEquals("200", oldID_sprintInfo.getFocusFactor());
assertEquals("Get ONE PIECE !!", oldID_sprintInfo.getGoal());
assertEquals("2", oldID_sprintInfo.getInterval());
assertEquals("2", oldID_sprintInfo.getMemberNumber());
assertEquals("成為海賊王", oldID_sprintInfo.getNotes());
// new Id 的資訊應該變成 sprint 3 資訊
ISprintPlanDesc newID_sprintInfo = this.helper.loadPlan(newID);
assertEquals(Integer.toString(newID), newID_sprintInfo.getID());
assertEquals(OldSprint.getAvailableDays(), newID_sprintInfo.getAvailableDays());
// 日期是正常的,所以時間不會移動
assertEquals(NewSprint.getStartDate(), newID_sprintInfo.getStartDate());
assertEquals(OldSprint.getDemoPlace(), newID_sprintInfo.getDemoPlace());
assertEquals(OldSprint.getFocusFactor(), newID_sprintInfo.getFocusFactor());
assertEquals(OldSprint.getGoal(), newID_sprintInfo.getGoal());
assertEquals(OldSprint.getInterval(), newID_sprintInfo.getInterval());
assertEquals(OldSprint.getMemberNumber(), newID_sprintInfo.getMemberNumber());
assertEquals(OldSprint.getNotes(), newID_sprintInfo.getNotes());
}
} | gpl-2.0 |
projectestac/qv | qv_viewer/src/viewer/edu/xtec/qv/servlet/QVOpenHTMLServlet.java | 688 | /**
* QVGenerateHTMLServlet.java
*
* Created on 24/05/2007
*/
package edu.xtec.qv.servlet;
import javax.servlet.http.HttpServletResponse;
/**
* @author sarjona
* @version
*/
public class QVOpenHTMLServlet extends QVGenerateHTMLServlet {
protected void createResponse(HttpServletResponse response, String sURL, String sSkin, String sLang, int iSection, String sParams) throws Exception{
if (exists(sURL)){
if (sURL.indexOf("?")<0) sURL+="?";
sURL+=getProperty("qv.dist.params");
sURL+="&lang="+sLang;
sURL+="&skin="+sSkin;
sURL+="&"+sParams;
response.sendRedirect(sURL);
}else{
throw new QVServletException("Can't open url: "+sURL);
}
}
}
| gpl-2.0 |
GeekBrains/springmvc-jpa | springmvc/springmvc-web/src/main/java/com/springmvc/example/controller/RegistrationController.java | 1880 | package com.springmvc.example.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.springmvc.example.formbean.Community;
import com.springmvc.example.formbean.User;
@Controller
@RequestMapping(value = "/register")
public class RegistrationController {
@RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
System.out.println(">>>>>>>>>>In Registration Controller >>>>>>>>>>>");
User userForm = new User();
model.put("userForm", userForm);
List<String> professionList = new ArrayList<String>();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.put("professionList", professionList);
List communityList = new ArrayList();
communityList.add(new Community("Spring","Spring"));
communityList.add(new Community("Hibernate","Hibernate"));
communityList.add(new Community("Struts","Struts"));
model.put("communityList", communityList);
return "Registration";
}
@RequestMapping(method = RequestMethod.POST)
public String processRegistration(@ModelAttribute("userForm") User user, Map<String, Object> model) {
System.out.println(">>>>>>>>>>>>>>>>> Get Data in Controller >>>>>>>>");
String gender = user.getGender();
String username = user.getUserName();
System.out.println("gender :: " + gender + "username :: " + username);
return "RegistrationSucess";
}
}
| gpl-2.0 |
DBBA/gceschat | src/gceschat/GreetingClient.java | 1130 | package gceschat;
import java.io.IOException;
import java.net.Socket;
public class GreetingClient
{
private String serverName;
private int port;
private Socket client;
private DataOutputStream Dout;
private DataInputStream Din;
public GreetingClient(String serverName, int port) throws IOException{
this.serverName = serverName ;
this.port = port;
client = new Socket(serverName,port);
System.out.println("Connected to" + Client);
din= new DataInputStream(client.getInputStream());
dout= new DataOutputStream(client.getOutputStream());
new Thread(this).start();
}
private void processMessage(String message) throws IOException{
dout.writeUTF(message);
}
public void run() throws IOException{
while(true){
String message=din.readUTF();
ta.append(message + "\n");
}
}
public static void main(String[] args){
GreetingClient greetingClient = new GreetingClient("localhost", 8888);
}
} | gpl-2.0 |
jython234/StoneServer | src/stoneserver/StoneServer.java | 189 | package stoneserver;
public class StoneServer {
public static void main(String[] args){
MinecraftServer s = new MinecraftServer(25565, 2, "StoneServer, Testing!");
s.Start();
}
}
| gpl-2.0 |
Teleburna/teleburna-gram | TMessagesProj/src/main/java/org/cafemember/ui/Components/Rect.java | 588 | /*
* This is the source code of Telegram for Android v. 3.x.x
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.cafemember.ui.Components;
public class Rect {
public float x;
public float y;
public float width;
public float height;
public Rect() {
}
public Rect(float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
| gpl-2.0 |
stevenzh/tourismwork | src/modules/service/src/main/java/com/opentravelsoft/service/portal/BranchServiceImpl.java | 563 | package com.opentravelsoft.service.portal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.opentravelsoft.entity.Branch;
import com.opentravelsoft.providers.BranchDao;
@Service("BranchService")
public class BranchServiceImpl implements BranchService {
@Autowired
private BranchDao branchDao;
public Branch roGetBranch(int branchId) {
return branchDao.get(branchId);
}
public List<Branch> roGetBranchList() {
return branchDao.getAll();
}
}
| gpl-2.0 |
Arquisoft/Trivial2b | extract/src/main/java/es/uniovi/asw/trivial/gui/PreguntaDialog.java | 13763 | package es.uniovi.asw.trivial.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import es.uniovi.asw.trivial.model.Posicion;
import es.uniovi.asw.trivial.model.Pregunta;
public class PreguntaDialog extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JTextField textField;
private JTextField textPregunta;
Timer timer;
private final int TIEMPO_RESPUESTA = 15;
private final int DELAY = 1000;
public PreguntaDialog(final Color color, final String categoria,
final Pregunta p, final Tablero tablero) {
for(UIManager.LookAndFeelInfo laf:UIManager.getInstalledLookAndFeels())
if("Nimbus".equals(laf.getName()))
try {
UIManager.setLookAndFeel(laf.getClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
setResizable(false);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setModal(true);
setAlwaysOnTop(true);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPanel.setBackground(color);
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JPanel panel = new JPanel();
contentPanel.add(panel, BorderLayout.NORTH);
panel.setLayout(new GridLayout(2, 1, 0, 0));
{
JLabel lblPregunta = new JLabel("Pregunta:");
lblPregunta.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(lblPregunta);
}
{
textPregunta = new JTextField();
textPregunta.setHorizontalAlignment(SwingConstants.CENTER);
textPregunta.setEditable(false);
panel.add(textPregunta);
textPregunta.setText(p.getPregunta());
}
}
{
JPanel panel = new JPanel();
panel.setBackground(color);
contentPanel.add(panel);
panel.setLayout(new GridLayout(0, 2, 0, 0));
{
for (int i = 0; i < p.getRespuestas().length; i++) {
JButton bt = new JButton(p.getRespuestas()[i]);
final int num = i;
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.stop();
// cambiar turno jugador
if (num != p.getCorrecta()) {
tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando())
.setTocaJugar(false);
tablero.getNombresUsuarios()
.get(tablero.getUsuarioJugando())
.setBackground(Color.white);
if (tablero.getUsuarioJugando() + 1 == tablero
.getCj().getUsuarios().size())
tablero.setUsuarioJugando(0);
else
tablero.setUsuarioJugando(tablero
.getUsuarioJugando() + 1);
tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando())
.setTocaJugar(true);
tablero.getNombresUsuarios()
.get(tablero.getUsuarioJugando())
.setBackground(Color.yellow);
} else {
JLabel manzana = new JLabel();
String[] cat = categoria.split(" ");
//Celdas especiales
if (cat.length>1 && categoria.contains("Especial") && !tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).getCategoriasGanadas().contains(cat[1])
){
tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).getCategoriasGanadas().add(cat[1]);
manzana.setIcon(new ImageIcon(
PreguntaDialog.class
.getResource("/es/uniovi/asw/trivial/gui/img/manzana"
+ cat[1] + ".gif")));
tablero.getPanelesUsuarios()
.get(tablero.getUsuarioJugando())
.add(manzana);
tablero.revalidate();
tablero.repaint();
}
}
JOptionPane.showMessageDialog(PreguntaDialog.this,
p.getContestacion()[num]);
if (p.getCorrecta() == num) {
// Acertadas ++
} else {
// falladas ++
}
if(tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).isGanador(tablero.getColores().size())){
partidaFinalizada(tablero);
}
//tablero.getCj().getUsuarios().get(tablero.getUsuarioJugando()).setPosicion(new Posicion(i,j));
tablero.estadoBotones(false);
tablero.getBtnDado().setEnabled(true);
tablero.repaint();
dispose();
}
private void partidaFinalizada(final Tablero tablero) {
String textWin=tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).getLogin() + " ha ganado!!";
JOptionPane.showMessageDialog(PreguntaDialog.this,
textWin);
//Guardar ganador partida en bd para estadísticas de partidas ganadas aqui
tablero.getPanelTablero().removeAll();
JButton volverLogin= new JButton();
JTextField textoWin = new JTextField();
textoWin.setText(textWin);
textoWin.setEditable(false);
volverLogin.setIcon(new ImageIcon(PreguntaDialog.class.getResource("/es/uniovi/asw/trivial/gui/img/btnAtras.png")));
tablero.getBtnDado().setVisible(false);
volverLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Menuprincipal().setVisible(true);
tablero.dispose();
}
});
tablero.getPanelTablero().setLayout(new BorderLayout());
tablero.getPanelTablero().add(textoWin,BorderLayout.NORTH);
tablero.getPanelTablero().add(volverLogin,BorderLayout.CENTER);
tablero.revalidate();
tablero.repaint();
}
});
bt.setActionCommand("Pregunta1");
panel.add(bt);
}
}
}
{
JPanel buttonPane = new JPanel();
getContentPane().add(buttonPane, BorderLayout.SOUTH);
buttonPane.setLayout(new BorderLayout(0, 0));
{
final JProgressBar progressBar = new JProgressBar();
{
ActionListener listener = new ActionListener() {
int counter = TIEMPO_RESPUESTA;
public void actionPerformed(ActionEvent ae) {
counter--;
progressBar.setValue(counter);
if (counter < 1) {
JOptionPane.showMessageDialog(PreguntaDialog.this,
"Tiempo agotado!");
timer.stop();
dispose();
}
}
};
timer = new Timer(DELAY, listener);
timer.start();
}
buttonPane.add(progressBar);
progressBar.setMaximum(TIEMPO_RESPUESTA);
}
}
{
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
{
JLabel lblHasElegidoUna = new JLabel(
"Has elegido una pregunta de:");
panel.add(lblHasElegidoUna);
}
{
textField = new JTextField();
textField.setEditable(false);
panel.add(textField);
textField.setColumns(10);
textField.setText(categoria);
}
}
}
public PreguntaDialog(final Posicion posicion,final Color color, final String categoria,
final Pregunta p, final Tablero tablero) {
setResizable(false);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setModal(true);
setAlwaysOnTop(true);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPanel.setBackground(color);
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JPanel panel = new JPanel();
contentPanel.add(panel, BorderLayout.NORTH);
panel.setLayout(new GridLayout(2, 1, 0, 0));
{
JLabel lblPregunta = new JLabel("Pregunta:");
lblPregunta.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(lblPregunta);
}
{
textPregunta = new JTextField();
textPregunta.setHorizontalAlignment(SwingConstants.CENTER);
textPregunta.setEditable(false);
panel.add(textPregunta);
textPregunta.setText(p.getPregunta());
}
}
{
JPanel panel = new JPanel();
panel.setBackground(color);
contentPanel.add(panel);
panel.setLayout(new GridLayout(0, 2, 0, 0));
{
for (int i = 0; i < p.getRespuestas().length; i++) {
JButton bt = new JButton(p.getRespuestas()[i]);
final int num = i;
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
timer.stop();
// cambiar turno jugador
if (num != p.getCorrecta()) {
tablero.getCj().getUsuarios().get(tablero.getUsuarioJugando()).setPosicion(posicion);
tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando())
.setTocaJugar(false);
tablero.getNombresUsuarios()
.get(tablero.getUsuarioJugando())
.setBackground(Color.white);
if (tablero.getUsuarioJugando() + 1 == tablero
.getCj().getUsuarios().size()){
tablero.setUsuarioJugando(0);
}
else{
tablero.setUsuarioJugando(tablero
.getUsuarioJugando() + 1);
}
tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando())
.setTocaJugar(true);
tablero.getNombresUsuarios()
.get(tablero.getUsuarioJugando())
.setBackground(Color.yellow);
} else {
JLabel manzana = new JLabel();
String[] cat = categoria.split(" ");
//Celdas especiales
if (cat.length>1 && categoria.contains("Especial") && !tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).getCategoriasGanadas().contains(cat[1])
){
tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).getCategoriasGanadas().add(cat[1]);
manzana.setIcon(new ImageIcon(
PreguntaDialog.class
.getResource("/es/uniovi/asw/trivial/gui/img/manzana"
+ cat[1] + ".gif")));
tablero.getPanelesUsuarios()
.get(tablero.getUsuarioJugando())
.add(manzana);
tablero.revalidate();
tablero.repaint();
}
tablero.getCj().getUsuarios().get(tablero.getUsuarioJugando()).setPosicion(posicion);
}
JOptionPane.showMessageDialog(PreguntaDialog.this,
p.getContestacion()[num]);
if (p.getCorrecta() == num) {
// Acertadas ++
} else {
// falladas ++
}
if(tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).isGanador(tablero.getColores().size())){
partidaFinalizada(tablero);
}
//System.out.println(tablero.getUsuarioJugando());
//tablero.getCj().getUsuarios().get(tablero.getUsuarioJugando()).setPosicion(posicion);
tablero.estadoBotones(false);
tablero.getBtnDado().setEnabled(true);
tablero.repaint();
dispose();
}
private void partidaFinalizada(final Tablero tablero) {
String textWin=tablero.getCj().getUsuarios()
.get(tablero.getUsuarioJugando()).getLogin() + " ha ganado!!";
JOptionPane.showMessageDialog(PreguntaDialog.this,
textWin);
//Guardar ganador partida en bd para estadísticas de partidas ganadas aqui
tablero.getPanelTablero().removeAll();
JButton volverLogin= new JButton();
JTextField textoWin = new JTextField();
textoWin.setText(textWin);
textoWin.setEditable(false);
volverLogin.setIcon(new ImageIcon(PreguntaDialog.class.getResource("/es/uniovi/asw/trivial/gui/img/btnAtras.png")));
tablero.getBtnDado().setVisible(false);
volverLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Menuprincipal().setVisible(true);
tablero.dispose();
}
});
tablero.getPanelTablero().setLayout(new BorderLayout());
tablero.getPanelTablero().add(textoWin,BorderLayout.NORTH);
tablero.getPanelTablero().add(volverLogin,BorderLayout.CENTER);
tablero.revalidate();
tablero.repaint();
}
});
bt.setActionCommand("Pregunta1");
panel.add(bt);
}
}
}
{
JPanel buttonPane = new JPanel();
getContentPane().add(buttonPane, BorderLayout.SOUTH);
buttonPane.setLayout(new BorderLayout(0, 0));
{
final JProgressBar progressBar = new JProgressBar();
{
ActionListener listener = new ActionListener() {
int counter = TIEMPO_RESPUESTA;
public void actionPerformed(ActionEvent ae) {
counter--;
progressBar.setValue(counter);
if (counter < 1) {
JOptionPane.showMessageDialog(PreguntaDialog.this,
"Tiempo agotado!");
timer.stop();
dispose();
}
}
};
timer = new Timer(DELAY, listener);
timer.start();
}
buttonPane.add(progressBar);
progressBar.setMaximum(TIEMPO_RESPUESTA);
}
}
{
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
{
JLabel lblHasElegidoUna = new JLabel(
"Has elegido una pregunta de:");
panel.add(lblHasElegidoUna);
}
{
textField = new JTextField();
textField.setEditable(false);
panel.add(textField);
textField.setColumns(10);
textField.setText(categoria);
}
}
}
}
| gpl-2.0 |
GriffinHines/teammates | src/test/java/teammates/test/cases/datatransfer/FeedbackQuestionAttributesTest.java | 18651 | package teammates.test.cases.datatransfer;
import static teammates.common.util.Const.EOL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.testng.annotations.Test;
import teammates.common.datatransfer.DataBundle;
import teammates.common.datatransfer.FeedbackParticipantType;
import teammates.common.datatransfer.attributes.FeedbackQuestionAttributes;
import teammates.common.datatransfer.questions.FeedbackQuestionType;
import teammates.common.datatransfer.questions.FeedbackTextQuestionDetails;
import teammates.common.util.Const;
import teammates.common.util.FieldValidator;
import teammates.common.util.StringHelper;
import teammates.test.cases.BaseTestCase;
import com.google.appengine.api.datastore.Text;
/**
* SUT: {@link FeedbackQuestionAttributes}.
*/
public class FeedbackQuestionAttributesTest extends BaseTestCase {
private DataBundle typicalBundle = getTypicalDataBundle();
private static class FeedbackQuestionAttributesWithModifiableTimestamp extends FeedbackQuestionAttributes {
void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
@Test
public void testDefaultTimestamp() {
FeedbackQuestionAttributesWithModifiableTimestamp fq =
new FeedbackQuestionAttributesWithModifiableTimestamp();
fq.setCreatedAt(null);
fq.setUpdatedAt(null);
Date defaultTimeStamp = Const.TIME_REPRESENTS_DEFAULT_TIMESTAMP;
______TS("success : defaultTimeStamp for createdAt date");
assertEquals(defaultTimeStamp, fq.getCreatedAt());
______TS("success : defaultTimeStamp for updatedAt date");
assertEquals(defaultTimeStamp, fq.getUpdatedAt());
}
@Test
public void testValidate() throws Exception {
FeedbackQuestionAttributes fq = new FeedbackQuestionAttributes();
fq.feedbackSessionName = "";
fq.courseId = "";
fq.creatorEmail = "";
fq.questionType = FeedbackQuestionType.TEXT;
fq.giverType = FeedbackParticipantType.NONE;
fq.recipientType = FeedbackParticipantType.RECEIVER;
fq.showGiverNameTo = new ArrayList<FeedbackParticipantType>();
fq.showGiverNameTo.add(FeedbackParticipantType.SELF);
fq.showGiverNameTo.add(FeedbackParticipantType.STUDENTS);
fq.showRecipientNameTo = new ArrayList<FeedbackParticipantType>();
fq.showRecipientNameTo.add(FeedbackParticipantType.SELF);
fq.showRecipientNameTo.add(FeedbackParticipantType.STUDENTS);
fq.showResponsesTo = new ArrayList<FeedbackParticipantType>();
fq.showResponsesTo.add(FeedbackParticipantType.NONE);
fq.showResponsesTo.add(FeedbackParticipantType.SELF);
assertFalse(fq.isValid());
String errorMessage = getPopulatedErrorMessage(
FieldValidator.SIZE_CAPPED_NON_EMPTY_STRING_ERROR_MESSAGE, fq.creatorEmail,
FieldValidator.FEEDBACK_SESSION_NAME_FIELD_NAME,
FieldValidator.REASON_EMPTY,
FieldValidator.FEEDBACK_SESSION_NAME_MAX_LENGTH) + EOL
+ getPopulatedErrorMessage(
FieldValidator.COURSE_ID_ERROR_MESSAGE, fq.courseId,
FieldValidator.COURSE_ID_FIELD_NAME, FieldValidator.REASON_EMPTY,
FieldValidator.COURSE_ID_MAX_LENGTH) + EOL
+ "Invalid creator's email: "
+ getPopulatedErrorMessage(
FieldValidator.EMAIL_ERROR_MESSAGE, fq.creatorEmail,
FieldValidator.EMAIL_FIELD_NAME, FieldValidator.REASON_EMPTY,
FieldValidator.EMAIL_MAX_LENGTH) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.giverType.toString(),
FieldValidator.GIVER_TYPE_NAME) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.recipientType.toString(),
FieldValidator.RECIPIENT_TYPE_NAME) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE,
fq.showGiverNameTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ "Trying to show giver name to STUDENTS without showing response first." + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE,
fq.showRecipientNameTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ "Trying to show recipient name to STUDENTS without showing response first." + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE,
fq.showResponsesTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE,
fq.showResponsesTo.get(1).toString(),
FieldValidator.VIEWER_TYPE_NAME);
assertEquals(errorMessage, StringHelper.toString(fq.getInvalidityInfo()));
fq.feedbackSessionName = "First Feedback Session";
fq.courseId = "CS1101";
fq.creatorEmail = "instructor1@course1.com";
fq.giverType = FeedbackParticipantType.TEAMS;
fq.recipientType = FeedbackParticipantType.OWN_TEAM;
assertFalse(fq.isValid());
errorMessage = String.format(FieldValidator.PARTICIPANT_TYPE_TEAM_ERROR_MESSAGE,
fq.recipientType.toDisplayRecipientName(),
fq.giverType.toDisplayGiverName()) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.showGiverNameTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ "Trying to show giver name to STUDENTS without showing response first." + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE,
fq.showRecipientNameTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ "Trying to show recipient name to STUDENTS without showing response first." + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.showResponsesTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.showResponsesTo.get(1).toString(),
FieldValidator.VIEWER_TYPE_NAME);
assertEquals(errorMessage, StringHelper.toString(fq.getInvalidityInfo()));
fq.recipientType = FeedbackParticipantType.OWN_TEAM_MEMBERS;
assertFalse(fq.isValid());
errorMessage = String.format(FieldValidator.PARTICIPANT_TYPE_TEAM_ERROR_MESSAGE,
fq.recipientType.toDisplayRecipientName(),
fq.giverType.toDisplayGiverName()) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.showGiverNameTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ "Trying to show giver name to STUDENTS without showing response first." + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE,
fq.showRecipientNameTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ "Trying to show recipient name to STUDENTS without showing response first." + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.showResponsesTo.get(0).toString(),
FieldValidator.VIEWER_TYPE_NAME) + EOL
+ String.format(FieldValidator.PARTICIPANT_TYPE_ERROR_MESSAGE, fq.showResponsesTo.get(1).toString(),
FieldValidator.VIEWER_TYPE_NAME);
assertEquals(errorMessage, StringHelper.toString(fq.getInvalidityInfo()));
fq.recipientType = FeedbackParticipantType.TEAMS;
fq.showGiverNameTo = new ArrayList<FeedbackParticipantType>();
fq.showGiverNameTo.add(FeedbackParticipantType.RECEIVER);
fq.showRecipientNameTo = new ArrayList<FeedbackParticipantType>();
fq.showRecipientNameTo.add(FeedbackParticipantType.RECEIVER);
fq.showResponsesTo = new ArrayList<FeedbackParticipantType>();
fq.showResponsesTo.add(FeedbackParticipantType.RECEIVER);
assertTrue(fq.isValid());
}
@Test
public void testGetQuestionDetails() {
______TS("Text question: new Json format");
FeedbackQuestionAttributes fq = typicalBundle.feedbackQuestions.get("qn5InSession1InCourse1");
FeedbackTextQuestionDetails questionDetails = new FeedbackTextQuestionDetails("New format text question");
fq.setQuestionDetails(questionDetails);
assertTrue(fq.isValid());
assertEquals(fq.getQuestionDetails().getQuestionText(), "New format text question");
______TS("Text question: old string format");
fq = typicalBundle.feedbackQuestions.get("qn2InSession1InCourse1");
assertEquals(fq.getQuestionDetails().getQuestionText(), "Rate 1 other student's product");
}
@Test
public void testRemoveIrrelevantVisibilityOptions() {
______TS("test teams->none");
FeedbackQuestionAttributes question = new FeedbackQuestionAttributes();
List<FeedbackParticipantType> participants = new ArrayList<FeedbackParticipantType>();
question.feedbackSessionName = "test session";
question.courseId = "some course";
question.creatorEmail = "test@case.com";
question.questionMetaData = new Text("test qn from teams->none.");
question.questionNumber = 1;
question.questionType = FeedbackQuestionType.TEXT;
question.giverType = FeedbackParticipantType.TEAMS;
question.recipientType = FeedbackParticipantType.NONE;
question.numberOfEntitiesToGiveFeedbackTo = Const.MAX_POSSIBLE_RECIPIENTS;
participants.add(FeedbackParticipantType.OWN_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.RECEIVER);
participants.add(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS);
question.showGiverNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(participants);
participants.add(FeedbackParticipantType.STUDENTS);
question.showResponsesTo = new ArrayList<FeedbackParticipantType>(participants);
question.removeIrrelevantVisibilityOptions();
assertTrue(question.showGiverNameTo.isEmpty());
assertTrue(question.showRecipientNameTo.isEmpty());
// check that other types are not removed
assertTrue(question.showResponsesTo.contains(FeedbackParticipantType.STUDENTS));
assertEquals(question.showResponsesTo.size(), 1);
______TS("test students->teams");
question.giverType = FeedbackParticipantType.STUDENTS;
question.recipientType = FeedbackParticipantType.TEAMS;
participants.clear();
participants.add(FeedbackParticipantType.INSTRUCTORS);
participants.add(FeedbackParticipantType.OWN_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS);
question.showGiverNameTo = new ArrayList<FeedbackParticipantType>(participants);
participants.add(FeedbackParticipantType.STUDENTS);
question.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showResponsesTo = new ArrayList<FeedbackParticipantType>(participants);
question.removeIrrelevantVisibilityOptions();
assertEquals(question.showGiverNameTo.size(), 2);
assertEquals(question.showRecipientNameTo.size(), 3);
assertEquals(question.showResponsesTo.size(), 3);
assertFalse(question.showGiverNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showRecipientNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
______TS("test students->team members including giver");
question.giverType = FeedbackParticipantType.STUDENTS;
question.recipientType = FeedbackParticipantType.OWN_TEAM_MEMBERS_INCLUDING_SELF;
participants.clear();
participants.add(FeedbackParticipantType.INSTRUCTORS);
participants.add(FeedbackParticipantType.OWN_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS);
question.showGiverNameTo = new ArrayList<FeedbackParticipantType>(participants);
participants.add(FeedbackParticipantType.STUDENTS);
question.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showResponsesTo = new ArrayList<FeedbackParticipantType>(participants);
question.removeIrrelevantVisibilityOptions();
assertEquals(question.showGiverNameTo.size(), 3);
assertEquals(question.showRecipientNameTo.size(), 4);
assertEquals(question.showResponsesTo.size(), 4);
assertFalse(question.showGiverNameTo.contains(FeedbackParticipantType.OWN_TEAM_MEMBERS_INCLUDING_SELF));
assertFalse(question.showRecipientNameTo.contains(FeedbackParticipantType.OWN_TEAM_MEMBERS_INCLUDING_SELF));
assertFalse(question.showResponsesTo.contains(FeedbackParticipantType.OWN_TEAM_MEMBERS_INCLUDING_SELF));
______TS("test students->instructors");
question.giverType = FeedbackParticipantType.STUDENTS;
question.recipientType = FeedbackParticipantType.INSTRUCTORS;
participants.clear();
participants.add(FeedbackParticipantType.RECEIVER);
participants.add(FeedbackParticipantType.INSTRUCTORS);
participants.add(FeedbackParticipantType.OWN_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.STUDENTS);
question.showGiverNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showResponsesTo = new ArrayList<FeedbackParticipantType>(participants);
question.removeIrrelevantVisibilityOptions();
assertEquals(question.showGiverNameTo.size(), 4);
assertEquals(question.showRecipientNameTo.size(), 4);
assertEquals(question.showResponsesTo.size(), 4);
assertFalse(question.showGiverNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showRecipientNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
______TS("test students->own team");
question.giverType = FeedbackParticipantType.STUDENTS;
question.recipientType = FeedbackParticipantType.OWN_TEAM;
participants.clear();
participants.add(FeedbackParticipantType.RECEIVER);
participants.add(FeedbackParticipantType.INSTRUCTORS);
participants.add(FeedbackParticipantType.OWN_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.STUDENTS);
question.showGiverNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showResponsesTo = new ArrayList<FeedbackParticipantType>(participants);
question.removeIrrelevantVisibilityOptions();
assertEquals(question.showGiverNameTo.size(), 4);
assertEquals(question.showRecipientNameTo.size(), 4);
assertEquals(question.showResponsesTo.size(), 4);
assertFalse(question.showGiverNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showRecipientNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
______TS("test students->own team members");
question.giverType = FeedbackParticipantType.STUDENTS;
question.recipientType = FeedbackParticipantType.OWN_TEAM_MEMBERS;
participants.clear();
participants.add(FeedbackParticipantType.RECEIVER);
participants.add(FeedbackParticipantType.INSTRUCTORS);
participants.add(FeedbackParticipantType.OWN_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS);
participants.add(FeedbackParticipantType.STUDENTS);
question.showGiverNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showRecipientNameTo = new ArrayList<FeedbackParticipantType>(participants);
question.showResponsesTo = new ArrayList<FeedbackParticipantType>(participants);
question.removeIrrelevantVisibilityOptions();
assertEquals(question.showGiverNameTo.size(), 4);
assertEquals(question.showRecipientNameTo.size(), 4);
assertEquals(question.showResponsesTo.size(), 4);
assertFalse(question.showGiverNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showRecipientNameTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
assertFalse(question.showResponsesTo.contains(FeedbackParticipantType.RECEIVER_TEAM_MEMBERS));
}
}
| gpl-2.0 |
saalfeldlab/render | render-ws-java-client/src/main/java/org/janelia/render/client/RenderSectionClient.java | 12829 | package org.janelia.render.client;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParametersDelegate;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.janelia.alignment.ArgbRenderer;
import org.janelia.alignment.RenderParameters;
import org.janelia.alignment.Utils;
import org.janelia.alignment.spec.Bounds;
import org.janelia.alignment.spec.stack.StackMetaData;
import org.janelia.alignment.util.FileUtil;
import org.janelia.alignment.util.ImageProcessorCache;
import org.janelia.alignment.util.LabelImageProcessorCache;
import org.janelia.render.client.parameter.CommandLineParameters;
import org.janelia.render.client.parameter.RenderWebServiceParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Java client for rendering a composite image of all tiles in a section for one or more sections.
* Images are placed in [rootDirectory]/[project]/[stack]/sections_at_[scale]/000/1/123.png
*
* @author Eric Trautman
*/
public class RenderSectionClient {
public static class Parameters extends CommandLineParameters {
@ParametersDelegate
public RenderWebServiceParameters renderWeb = new RenderWebServiceParameters();
@Parameter(
names = "--stack",
description = "Stack name",
required = true)
public String stack;
@Parameter(
names = "--rootDirectory",
description = "Root directory for rendered layers (e.g. /nrs/flyem/render/scapes)",
required = true)
public String rootDirectory;
@Parameter(
names = "--scale",
description = "Scale for each rendered layer"
)
public Double scale = 0.02;
@Parameter(
names = "--format",
description = "Format for rendered boxes"
)
public String format = Utils.PNG_FORMAT;
@Parameter(
names = "--doFilter",
description = "Use ad hoc filter to support alignment",
arity = 1)
public boolean doFilter = true;
@Parameter(
names = "--filterListName",
description = "Apply this filter list to all rendering (overrides doFilter option)"
)
public String filterListName;
@Parameter(
names = "--channels",
description = "Specify channel(s) and weights to render (e.g. 'DAPI' or 'DAPI__0.7__TdTomato__0.3')"
)
public String channels;
@Parameter(
names = "--fillWithNoise",
description = "Fill image with noise before rendering to improve point match derivation",
arity = 1)
public boolean fillWithNoise = true;
@Parameter(
description = "Z values for sections to render",
required = true)
public List<Double> zValues;
@Parameter(
names = "--bounds",
description = "Bounds used for all layers: xmin, xmax, ymin,ymax"
)
public List<Integer> bounds;
@Parameter(
names = "--customOutputFolder",
description = "Custom named folder for output. Overrides the default format 'sections_at_#' folder"
)
public String customOutputFolder;
@Parameter(
names = "--customSubFolder",
description = "Name for subfolder to customOutputFolder, if used"
)
public String customSubFolder;
@Parameter(
names = "--padFileNamesWithZeros",
description = "Pad outputfilenames with leading zeroes, i.e. 12.tiff -> 00012.tiff"
)
public boolean padFileNameWithZeroes;
@Parameter(
names = "--maxIntensity",
description = "Max intensity to render image"
)
public Integer maxIntensity;
@Parameter(
names = "--minIntensity",
description = "Min intensity to render image"
)
public Integer minIntensity;
@Parameter(
names = "--renderTileLabels",
description = "Render tiles as single color labels"
)
public boolean renderTileLabels;
@Parameter(
names = "--useStackBounds",
description = "Use stack bounds instead of layer bounds for rendered canvas"
)
public boolean useStackBounds;
}
/**
* @param args see {@link Parameters} for command line argument details.
*/
public static void main(final String[] args) {
final ClientRunner clientRunner = new ClientRunner(args) {
@Override
public void runClient(final String[] args) throws Exception {
final Parameters parameters = new Parameters();
parameters.parse(args);
LOG.info("runClient: entry, parameters={}", parameters);
final RenderSectionClient client = new RenderSectionClient(parameters);
for (final Double z : parameters.zValues) {
client.generateImageForZ(z);
}
}
};
clientRunner.run();
}
private final Parameters clientParameters;
private final File sectionDirectory;
private final int maxCachedPixels;
private final ImageProcessorCache imageProcessorCache;
private final RenderDataClient renderDataClient;
private final Bounds stackBounds;
private RenderSectionClient(final Parameters clientParameters)
throws IOException {
this.clientParameters = clientParameters;
final Path sectionPath;
if (clientParameters.customOutputFolder != null) {
if (clientParameters.customSubFolder != null) {
sectionPath = Paths.get(clientParameters.rootDirectory,
clientParameters.customOutputFolder,
clientParameters.customSubFolder);
} else {
sectionPath = Paths.get(clientParameters.rootDirectory,
clientParameters.customOutputFolder);
}
} else {
final String sectionsAtScaleName = "sections_at_" + clientParameters.scale;
sectionPath = Paths.get(clientParameters.rootDirectory,
clientParameters.renderWeb.project,
clientParameters.stack,
sectionsAtScaleName);
}
this.sectionDirectory = sectionPath.toAbsolutePath().toFile();
FileUtil.ensureWritableDirectory(this.sectionDirectory);
// set cache size to 50MB so that masks get cached but most of RAM is left for target image
this.maxCachedPixels = 50 * 1000000;
if (clientParameters.renderTileLabels) {
this.imageProcessorCache = null;
} else {
this.imageProcessorCache = new ImageProcessorCache(maxCachedPixels,
false,
false);
}
this.renderDataClient = clientParameters.renderWeb.getDataClient();
if (clientParameters.useStackBounds) {
final StackMetaData stackMetaData = renderDataClient.getStackMetaData(clientParameters.stack);
this.stackBounds = stackMetaData.getStats().getStackBounds();
} else {
this.stackBounds = null;
}
}
private void generateImageForZ(final Double z)
throws Exception {
LOG.info("generateImageForZ: {}, entry, sectionDirectory={}, dataClient={}",
z, sectionDirectory, renderDataClient);
final Bounds layerBounds =
stackBounds == null ? renderDataClient.getLayerBounds(clientParameters.stack, z) : stackBounds;
String parametersUrl;
if(clientParameters.bounds != null && clientParameters.bounds.size() == 4) //Read bounds from supplied parameters
{
LOG.debug("Using user bounds");
parametersUrl =
renderDataClient.getRenderParametersUrlString(clientParameters.stack,
clientParameters.bounds.get(0), //Min X
clientParameters.bounds.get(2), //Min Y
z,
clientParameters.bounds.get(1) - clientParameters.bounds.get(0), //Width
clientParameters.bounds.get(3) - clientParameters.bounds.get(2), //Height
clientParameters.scale,
clientParameters.filterListName);
}
else //Get bounds from render
{
LOG.debug("Using render bounds");
parametersUrl =
renderDataClient.getRenderParametersUrlString(clientParameters.stack,
layerBounds.getMinX(),
layerBounds.getMinY(),
z,
(int) (layerBounds.getDeltaX() + 0.5),
(int) (layerBounds.getDeltaY() + 0.5),
clientParameters.scale,
clientParameters.filterListName);
}
if (clientParameters.minIntensity != null) {
if (clientParameters.maxIntensity != null) {
parametersUrl += "?minIntensity=" + clientParameters.minIntensity +
"&maxIntensity=" + clientParameters.maxIntensity;
} else {
parametersUrl += "?minIntensity=" + clientParameters.minIntensity;
}
} else if (clientParameters.maxIntensity != null) {
parametersUrl += "?maxIntensity=" + clientParameters.maxIntensity;
}
LOG.debug("generateImageForZ: {}, loading {}", z, parametersUrl);
final RenderParameters renderParameters = RenderParameters.loadFromUrl(parametersUrl);
renderParameters.setFillWithNoise(clientParameters.fillWithNoise);
renderParameters.setDoFilter(clientParameters.doFilter);
renderParameters.setChannels(clientParameters.channels);
final File sectionFile = getSectionFile(z);
final BufferedImage sectionImage = renderParameters.openTargetImage();
final ImageProcessorCache cache;
if (clientParameters.renderTileLabels) {
renderParameters.setBinaryMask(true); // masked edges should not be interpolated for labels
cache = new LabelImageProcessorCache(maxCachedPixels,
false,
false,
renderParameters.getTileSpecs());
} else {
cache = this.imageProcessorCache;
}
ArgbRenderer.render(renderParameters, sectionImage, cache);
Utils.saveImage(sectionImage, sectionFile.getAbsolutePath(), clientParameters.format, true, 0.85f);
LOG.info("generateImageForZ: {}, exit", z);
}
private File getSectionFile(final Double z) {
final String fileName = clientParameters.padFileNameWithZeroes ?
String.format("%05d", z.intValue()) : z.toString();
final File parentDirectory;
if (clientParameters.customOutputFolder == null) {
final int thousands = z.intValue() / 1000;
final File thousandsDir = new File(sectionDirectory, String.format("%03d", thousands));
final int hundreds = (z.intValue() % 1000) / 100;
parentDirectory = new File(thousandsDir, String.valueOf(hundreds));
} else {
parentDirectory = sectionDirectory;
}
FileUtil.ensureWritableDirectory(parentDirectory);
return new File(parentDirectory, fileName + "." + clientParameters.format.toLowerCase());
}
private static final Logger LOG = LoggerFactory.getLogger(RenderSectionClient.class);
}
| gpl-2.0 |
SquallATF/MAGIHome | src/jp/co/evangelion/nervhome/selector/gles/C059h.java | 336 | package jp.co.evangelion.nervhome.selector.gles;
import jp.co.evangelion.nervhome.gles.C143b;
import jp.co.evangelion.nervhome.gles.C145d;
public class C059h {
public static final String TAG = C059h.class.getSimpleName();
public static C143b MPa(float p1, float p2) {
return C145d.MPa(0.82F * (p1 / p2), 0.82F);
}
}
| gpl-2.0 |
gouessej/java3d-core | src/main/java/org/jogamp/java3d/ShaderErrorListener.java | 1854 | /*
* Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
package org.jogamp.java3d;
/**
* Listener interface for monitoring errors in Shader Programs.
* Compile and link errors are reported by the shader compiler, as are
* runtime errors, such as those resulting from shader attributes that
* aren't found or are of the wrong type.
*
* @see VirtualUniverse#addShaderErrorListener
*
* @since Java 3D 1.4
*/
public interface ShaderErrorListener {
/**
* Invoked when an error occurs while compiling, linking or
* executing a programmable shader.
*
* @param error object that contains the details of the error.
*/
public void errorOccurred(ShaderError error);
}
| gpl-2.0 |
rsnatividade/CNRSistemas | sgo/src/main/java/br/com/sgo/managedbean/cadastro/CadastroVeiculoMBean.java | 3034 | package br.com.sgo.managedbean.cadastro;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import br.com.sgo.dao.administrativo.AdministrativoSessionFacade;
import br.com.sgo.model.administrativo.Combustivel;
import br.com.sgo.model.administrativo.Marca;
import br.com.sgo.model.administrativo.Modelo;
import br.com.sgo.model.administrativo.Veiculo;
@ManagedBean
@ViewScoped
public class CadastroVeiculoMBean {
private AdministrativoSessionFacade admSession;
private List<Veiculo> veiculos = new ArrayList<Veiculo>();
private Veiculo veiculo;
private List<Combustivel> combustiveis;
private String titulo_dialog;
public String getTitulo_dialog() {
return titulo_dialog;
}
@PostConstruct
public void init() {
admSession = new AdministrativoSessionFacade();
veiculos = admSession.listarVeiculosAtivos();
combustiveis = Arrays.asList(Combustivel.values());
novoVeiculo();
}
public List<Combustivel> getCombustiveis() {
return combustiveis;
}
public void setCombustiveis(List<Combustivel> combustiveis) {
this.combustiveis = combustiveis;
}
public void incluirVeiculo() {
admSession.salvarVeiculo(veiculo);
// Refresh nos veículos listados
veiculos = admSession.listarVeiculosAtivos();
novoVeiculo();
}
public void selecionarVeiculo(Veiculo veiculo) {
this.veiculo = veiculo;
titulo_dialog = new String("Editar Veículo");
}
public void excluirVeiculo() {
admSession.removerVeiculo(veiculo);
// Refresh nos veículos listados
veiculos = admSession.listarVeiculosAtivos();
novoVeiculo();
}
public Veiculo getVeiculo() {
return veiculo;
}
public void setVeiculo(Veiculo veiculo) {
this.veiculo = veiculo;
}
public List<Veiculo> getVeiculos() {
return veiculos;
}
public void setClientes(List<Veiculo> veiculos) {
this.veiculos = veiculos;
}
public void buscarModelo() {
Map<String, Object> opcoes = new HashMap<String, Object>();
opcoes.put("resizable", false);
opcoes.put("draggable", true);
opcoes.put("modal", true);
RequestContext.getCurrentInstance().openDialog("buscarModelo", opcoes, null);
}
public void retBuscarModelo(SelectEvent evt) {
Modelo modelo = (Modelo) evt.getObject();
veiculo.setModelo(modelo);
}
public void novoVeiculo() {
Marca marca = new Marca();
Modelo modelo = new Modelo();
modelo.setMarca(marca);
veiculo = new Veiculo();
veiculo.setModelo(modelo);
veiculo.setAno_fabricacao(Calendar.getInstance().get(Calendar.YEAR));
veiculo.setAno_modelo(Calendar.getInstance().get(Calendar.YEAR));
titulo_dialog = new String("Inclusão de novo Veículo");
}
}
| gpl-2.0 |
andresriancho/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00095.java | 3591 | /**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest00095")
public class BenchmarkTest00095 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
javax.servlet.http.Cookie[] theCookies = request.getCookies();
String param = null;
boolean foundit = false;
if (theCookies != null) {
for (javax.servlet.http.Cookie theCookie : theCookies) {
if (theCookie.getName().equals("vector")) {
param = java.net.URLDecoder.decode(theCookie.getValue(), "UTF-8");
foundit = true;
}
}
if (!foundit) {
// no cookie found in collection
param = "";
}
} else {
// no cookies
param = "";
}
StringBuilder sbxyz69363 = new StringBuilder(param);
String bar = sbxyz69363.append("_SafeStuff").toString();
double stuff = new java.util.Random().nextGaussian();
String rememberMeKey = Double.toString(stuff).substring(2); // Trim off the 0. at the front.
String user = "Gayle";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
if (foundUser) {
response.getWriter().println("Welcome back: " + user + "<br/>");
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>");
}
response.getWriter().println("Weak Randomness Test java.util.Random.nextGaussian() executed");
}
}
| gpl-2.0 |
yeriomin/YalpStore | app/src/main/java/com/github/yeriomin/yalpstore/task/playstore/BackgroundUpdatableAppsTask.java | 7510 | /*
* Yalp Store
* Copyright (C) 2018 Sergey Yeriomin <yeriomin@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.github.yeriomin.yalpstore.task.playstore;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.util.Log;
import com.github.yeriomin.yalpstore.BuildConfig;
import com.github.yeriomin.yalpstore.NetworkUtil;
import com.github.yeriomin.yalpstore.Paths;
import com.github.yeriomin.yalpstore.PreferenceUtil;
import com.github.yeriomin.yalpstore.R;
import com.github.yeriomin.yalpstore.SqliteHelper;
import com.github.yeriomin.yalpstore.UpdatableAppsActivity;
import com.github.yeriomin.yalpstore.UpdateAllReceiver;
import com.github.yeriomin.yalpstore.YalpStoreApplication;
import com.github.yeriomin.yalpstore.download.DownloadManager;
import com.github.yeriomin.yalpstore.download.State;
import com.github.yeriomin.yalpstore.install.InstallerAbstract;
import com.github.yeriomin.yalpstore.install.InstallerFactory;
import com.github.yeriomin.yalpstore.model.App;
import com.github.yeriomin.yalpstore.model.Event;
import com.github.yeriomin.yalpstore.model.EventDao;
import com.github.yeriomin.yalpstore.notification.NotificationManagerWrapper;
import java.io.File;
import java.util.List;
public class BackgroundUpdatableAppsTask extends UpdatableAppsTask implements CloneableTask {
private boolean forceUpdate = false;
public void setForceUpdate(boolean forceUpdate) {
this.forceUpdate = forceUpdate;
}
@Override
public CloneableTask clone() {
BackgroundUpdatableAppsTask task = new BackgroundUpdatableAppsTask();
task.setForceUpdate(forceUpdate);
task.setContext(context);
return task;
}
@Override
protected void onPostExecute(List<App> apps) {
super.onPostExecute(apps);
if (!success()) {
return;
}
int updatesCount = this.updatableApps.size();
Log.i(this.getClass().getName(), "Found updates for " + updatesCount + " apps");
try {
insertEvent(updatesCount);
} catch (Throwable e) {
// No failure to log an event is important enough to let the app crash
Log.e(getClass().getSimpleName(), "Could not log event: " + e.getClass().getName() + " " + e.getMessage());
}
if (updatesCount == 0) {
context.sendBroadcast(new Intent(UpdateAllReceiver.ACTION_ALL_UPDATES_COMPLETE), null);
return;
}
if (canUpdate()) {
process(context, updatableApps);
} else {
notifyUpdatesFound(context, updatesCount);
}
}
private void insertEvent(int updatesCount) {
Event event = new Event();
event.setType(Event.TYPE.BACKGROUND_UPDATE_CHECK);
event.setMessage(context.getString(R.string.notification_updates_available_message, updatesCount));
SQLiteDatabase db = new SqliteHelper(context).getWritableDatabase();
new EventDao(db).insert(event);
db.close();
}
private boolean canUpdate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_DOWNLOAD_INTERNAL_STORAGE)
&& context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
) {
return false;
}
return forceUpdate ||
(PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_BACKGROUND_UPDATE_DOWNLOAD)
&& (!PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_BACKGROUND_UPDATE_WIFI_ONLY)
|| !NetworkUtil.isMetered(context)
)
)
;
}
private void process(Context context, List<App> apps) {
boolean canInstallInBackground = PreferenceUtil.canInstallInBackground(context);
YalpStoreApplication application = (YalpStoreApplication) context.getApplicationContext();
application.clearPendingUpdates();
for (App app: apps) {
if (DownloadManager.isCancelled(app.getPackageName())) {
Log.i(getClass().getSimpleName(), app.getPackageName() + " cancelled before starting");
continue;
}
application.addPendingUpdate(app.getPackageName());
File apkPath = Paths.getApkPath(context, app.getPackageName(), app.getVersionCode());
if (!apkPath.exists()
|| (PreferenceUtil.getBoolean(context, PreferenceUtil.PREFERENCE_DOWNLOAD_INTERNAL_STORAGE)
&& null == DownloadManager.getApkExpectedHash(app.getPackageName())
)
) {
apkPath.delete();
download(context, app);
} else if (canInstallInBackground) {
// Not passing context because it might be an activity
// and we want it to run in background
InstallerFactory.get(context.getApplicationContext()).verifyAndInstall(app);
} else {
notifyDownloadedAlready(app);
application.removePendingUpdate(app.getPackageName());
}
}
}
private void download(Context context, App app) {
Log.i(getClass().getSimpleName(), "Starting download of update for " + app.getPackageName());
getPurchaseTask(context, app).execute();
}
private BackgroundPurchaseTask getPurchaseTask(Context context, App app) {
BackgroundPurchaseTask task = new BackgroundPurchaseTask();
task.setApp(app);
task.setContext(context);
task.setTriggeredBy(context instanceof Activity
? State.TriggeredBy.UPDATE_ALL_BUTTON
: State.TriggeredBy.SCHEDULED_UPDATE
);
return task;
}
private void notifyUpdatesFound(Context context, int updatesCount) {
Intent i = new Intent(context, UpdatableAppsActivity.class);
i.setAction(Intent.ACTION_VIEW);
new NotificationManagerWrapper(context).show(
BuildConfig.APPLICATION_ID,
i,
context.getString(R.string.notification_updates_available_title),
context.getString(R.string.notification_updates_available_message, updatesCount)
);
}
private void notifyDownloadedAlready(App app) {
new NotificationManagerWrapper(context).show(
app.getPackageName(),
InstallerAbstract.getDownloadChecksumServiceIntent(app.getPackageName()),
app.getDisplayName(),
context.getString(R.string.notification_download_complete)
);
}
}
| gpl-2.0 |
BackupTheBerlios/arara-svn | core/tags/arara-1.0/src/main/java/net/indrix/arara/servlets/photo/ShowOnePhotoServlet.java | 4954 | /*
* Created on 16/06/2005
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package net.indrix.arara.servlets.photo;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.indrix.arara.dao.DatabaseDownException;
import net.indrix.arara.model.PhotoModel;
import net.indrix.arara.servlets.ServletConstants;
import net.indrix.arara.vo.Photo;
import org.apache.log4j.Logger;
/**
* @author Jeff
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class ShowOnePhotoServlet extends HttpServlet {
static Logger logger = Logger.getLogger("net.indrix.aves");
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
RequestDispatcher dispatcher = null;
ServletContext context = this.getServletContext();
String nextPage = null;
List errors = new ArrayList();
List messages = new ArrayList();
HttpSession session = req.getSession();
String photoId = req.getParameter("photoId");
String identificationStr = req.getParameter(ServletConstants.IDENTIFICATION_KEY);
List list = null;
list = (List) session.getAttribute(ServletConstants.PHOTOS_LIST);
if ((photoId == null) || (list == null)) {
Photo photo = getPhotoFromDatabase(errors, photoId);
if (photo != null) {
session.setAttribute(ServletConstants.CURRENT_PHOTO, photo);
nextPage = ServletConstants.ONE_PHOTO_PAGE;
} else {
logger.debug("List of photos not found...");
nextPage = ServletConstants.ONE_PHOTO_PAGE_ERROR;
}
} else {
logger.debug("List of photos found...");
Iterator it = list.iterator();
int id = Integer.parseInt(photoId);
boolean found = false;
Photo photo = null;
while (it.hasNext() && (!found)) {
photo = (Photo) it.next();
if (photo.getId() == id) {
logger.debug("Photo found !!!! ");
found = true;
PhotoModel model = new PhotoModel();
try {
model.retrievePhotoImage(photo);
retrieveCommentsForPhoto(model, photo);
} catch (DatabaseDownException e) {
logger.debug("DatabaseDownException.....", e);
errors.add(ServletConstants.DATABASE_ERROR);
} catch (SQLException e) {
logger.debug("SQLException.....", e);
errors.add(ServletConstants.DATABASE_ERROR);
}
}
}
if (!found) {
photo = getPhotoFromDatabase(errors, photoId);
if (!errors.isEmpty() || photo == null) {
logger.debug("Photo does not exist in DB anymore");
nextPage = ServletConstants.ONE_PHOTO_PAGE_ERROR;
}
}
session.setAttribute(ServletConstants.CURRENT_PHOTO, photo);
nextPage = ServletConstants.ONE_PHOTO_PAGE;
}
req.setAttribute(ServletConstants.IDENTIFICATION_KEY, identificationStr);
req.setAttribute(ServletConstants.VIEW_MODE_KEY, "viewMode");
dispatcher = context.getRequestDispatcher(nextPage);
logger.debug("Dispatching to " + nextPage);
dispatcher.forward(req, res);
}
private Photo getPhotoFromDatabase(List errors, String photoId) {
// retrieve from database
PhotoModel model = new PhotoModel();
Photo photo = null;
try {
photo = model.retrieve(Integer.parseInt(photoId));
if (photo != null) {
retrieveCommentsForPhoto(model, photo);
}
logger.debug("Photo retrieved = " + photo);
} catch (NumberFormatException e) {
logger.error("Could not parse photoId " + photoId);
errors.add(ServletConstants.DATABASE_ERROR);
} catch (DatabaseDownException e) {
logger.debug("DatabaseDownException.....");
errors.add(ServletConstants.DATABASE_ERROR);
} catch (SQLException e) {
logger.debug("SQLException.....", e);
errors.add(ServletConstants.DATABASE_ERROR);
}
return photo;
}
/**
* This method retrieves the comments for a given photo
*
* @param model
* @param photo
* @throws DatabaseDownException
* @throws SQLException
*/
private void retrieveCommentsForPhoto(PhotoModel model, Photo photo)
throws DatabaseDownException, SQLException {
// now retrieve the comments
List comments = model.retrieveCommentsForPhoto(photo);
photo.setComments(comments);
if ((comments == null) || (comments.isEmpty())) {
logger.debug("There is no comment for photo " + photo);
} else {
logger.debug(comments.size() + " comments found for photo " + photo);
}
}
}
| gpl-2.0 |
Sim00n/Wolfie | Wolfie/src/net/lsrp/wolfie/graphics/Screen.java | 2587 | package net.lsrp.wolfie.graphics;
import net.lsrp.wolfie.Game;
public class Screen {
public int width, height;
public int[] pixels;
public Screen(int width, int height) {
this.width = width;
this.height = height;
pixels = new int[width*height];
for(int i = 0; i < pixels.length; i++) {
pixels[i] = 0xFFFFAAFF;
}
}
public void clear() {
for(int i = 0; i < pixels.length; i++) {
pixels[i] = 0;
}
}
public void renderSprite(int xp, int yp, Sprite sprite) {
for(int y = 0; y < sprite.SIZE; y++) {
int ya = y + yp;
for(int x = 0; x < sprite.SIZE; x++) {
int xa = x + xp;
if(xa < -sprite.SIZE || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = sprite.pixels[x + y * sprite.SIZE];
if(col != 0xFFFF00FF)
pixels[xa + ya * width] = col;
}
}
}
public void renderPlatform(int xp, int yp, int wp, Sprite sprite, Sprite sprite_l, Sprite sprite_r) {
for(int y = 0; y < sprite_l.SIZE; y++) {
int ya = y + yp;
ya+=10;
for(int x = 0; x < sprite_l.SIZE; x++) {
int xa = x + xp;
if(xa < -sprite_l.SIZE || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = sprite_l.pixels[x + y * sprite_l.SIZE];
if(col != 0xFFFF00FF)
pixels[xa + ya * width] = col;
}
}
for(int w = 1; w < wp - 1; w++) {
for(int y = 0; y < sprite.SIZE; y++) {
int ya = y + yp;
ya+=10;
for(int x = 0; x < sprite.SIZE; x++) {
int xa = x + xp + (w << 4);
if(xa < -sprite.SIZE || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = sprite.pixels[x + y * sprite.SIZE];
if(col != 0xFFFF00FF)
pixels[xa + ya * width] = col;
}
}
}
for(int y = 0; y < sprite_r.SIZE; y++) {
int ya = y + yp;
ya+=10;
for(int x = 0; x < sprite_r.SIZE; x++) {
int xa = x + xp + (wp-1 << 4);
if(xa < -sprite_r.SIZE || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = sprite_r.pixels[x + y * sprite_r.SIZE];
if(col != 0xFFFF00FF)
pixels[xa + ya * width] = col;
}
}
}
public void renderPlatformScore(int yp, Sprite sprite) {
for(int y = 0; y < sprite.SIZE; y++) {
int ya = y + yp;
for(int x = 0; x < sprite.SIZE; x++) {
int xa = x + (Game.WIDTH/2);
if(xa < -sprite.SIZE || xa >= width || ya < 0 || ya >= height) break;
if(xa < 0) xa = 0;
int col = sprite.pixels[x + y * sprite.SIZE];
if(col != 0xFFFF00FF)
pixels[xa + ya * width] = col;
}
}
}
}
| gpl-2.0 |
risingsunm/Contacts_4.0 | src/com/android/contacts/list/ContactBrowseListFragment.java | 37157 | /*
* Copyright (C) 2010 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.contacts.list;
import com.android.common.widget.CompositeCursorAdapter.Partition;
import com.android.contacts.R;
import com.android.contacts.util.ContactLoaderUtils;
import com.android.contacts.widget.AutoScrollListView;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Directory;
import android.text.TextUtils;
import android.util.Log;
/*Start of wangqiang on 2012-3-20 17:51 cantacts_longclick*/
import com.android.contacts.widget.ContextMenuAdapter;
import android.content.Context;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import com.android.contacts.util.PhoneCapabilityTester;
/*End of wangqiang on 2012-3-20 17:51 cantacts_longclick*/
import java.util.List;
/*Begin: Modified by sunrise for AddContactToBlackNumber 2012/06/07*/
import android.content.ContentValues;
import java.util.ArrayList;
/*End: Modified by sunrise for AddContactToBlackNumber 2012/06/07*/
/*Begin: Modified by sunrise for add and del hint 2012/08/10*/
import android.widget.Toast;
/*End: Modified by sunrise for add and del hint 2012/08/10*/
/**
* Fragment containing a contact list used for browsing (as compared to
* picking a contact with one of the PICK intents).
*/
public abstract class ContactBrowseListFragment extends
ContactEntryListFragment<ContactListAdapter> {
private static final String TAG = "ContactList";
private static final String KEY_SELECTED_URI = "selectedUri";
private static final String KEY_SELECTION_VERIFIED = "selectionVerified";
private static final String KEY_FILTER = "filter";
private static final String KEY_LAST_SELECTED_POSITION = "lastSelected";
private static final String PERSISTENT_SELECTION_PREFIX = "defaultContactBrowserSelection";
/**
* The id for a delayed message that triggers automatic selection of the first
* found contact in search mode.
*/
private static final int MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT = 1;
/**
* The delay that is used for automatically selecting the first found contact.
*/
private static final int DELAY_AUTOSELECT_FIRST_FOUND_CONTACT_MILLIS = 500;
/**
* The minimum number of characters in the search query that is required
* before we automatically select the first found contact.
*/
private static final int AUTOSELECT_FIRST_FOUND_CONTACT_MIN_QUERY_LENGTH = 2;
/*Start of wangqiang on 2012-3-20 17:51 cantacts_longclick*/
private static final int MENU_ITEM_VIEW_CONTACT = 1;
private static final int MENU_ITEM_CALL = 2;
private static final int MENU_ITEM_SEND_SMS = 3;
private static final int MENU_ITEM_EDIT = 4;
private static final int MENU_ITEM_DELETE = 5;
private static final int MENU_ITEM_TOGGLE_STAR = 6;
/*End of wangqiang on 2012-3-20 17:51 cantacts_longclick*/
/* Begin: Modified by sunrise for AddContactToBlackNumber 2012/06/05 */
private static final int MENU_ITEM_ADD_BLACK = 7;
private static final int MENU_ITEM_DEL_BLACK = 8;
private String rawContactsId;
/* End: Modified by sunrise for AddContactToBlackNumber 2012/06/05 */
private SharedPreferences mPrefs;
private Handler mHandler;
private boolean mStartedLoading;
private boolean mSelectionRequired;
private boolean mSelectionToScreenRequested;
private boolean mSmoothScrollRequested;
private boolean mSelectionPersistenceRequested;
private Uri mSelectedContactUri;
private long mSelectedContactDirectoryId;
private String mSelectedContactLookupKey;
private long mSelectedContactId;
private boolean mSelectionVerified;
private int mLastSelectedPosition = -1;
private boolean mRefreshingContactUri;
private ContactListFilter mFilter;
private String mPersistentSelectionPrefix = PERSISTENT_SELECTION_PREFIX;
protected OnContactBrowserActionListener mListener;
private ContactLookupTask mContactLookupTask;
private final class ContactLookupTask extends AsyncTask<Void, Void, Uri> {
private final Uri mUri;
private boolean mIsCancelled;
public ContactLookupTask(Uri uri) {
mUri = uri;
}
@Override
protected Uri doInBackground(Void... args) {
Cursor cursor = null;
try {
final ContentResolver resolver = getContext().getContentResolver();
final Uri uriCurrentFormat = ContactLoaderUtils.ensureIsContactUri(resolver, mUri);
cursor = resolver.query(uriCurrentFormat,
new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final long contactId = cursor.getLong(0);
final String lookupKey = cursor.getString(1);
if (contactId != 0 && !TextUtils.isEmpty(lookupKey)) {
return Contacts.getLookupUri(contactId, lookupKey);
}
}
Log.e(TAG, "Error: No contact ID or lookup key for contact " + mUri);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void cancel() {
super.cancel(true);
// Use a flag to keep track of whether the {@link AsyncTask} was cancelled or not in
// order to ensure onPostExecute() is not executed after the cancel request. The flag is
// necessary because {@link AsyncTask} still calls onPostExecute() if the cancel request
// came after the worker thread was finished.
mIsCancelled = true;
}
@Override
protected void onPostExecute(Uri uri) {
// Make sure the {@link Fragment} is at least still attached to the {@link Activity}
// before continuing. Null URIs should still be allowed so that the list can be
// refreshed and a default contact can be selected (i.e. the case of deleted
// contacts).
if (mIsCancelled || !isAdded()) {
return;
}
onContactUriQueryFinished(uri);
}
}
private boolean mDelaySelection;
private Handler getHandler() {
if (mHandler == null) {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT:
selectDefaultContact();
break;
}
}
};
}
return mHandler;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
restoreFilter();
restoreSelectedUri(false);
}
@Override
protected void setSearchMode(boolean flag) {
if (isSearchMode() != flag) {
if (!flag) {
restoreSelectedUri(true);
}
super.setSearchMode(flag);
}
}
public void setFilter(ContactListFilter filter) {
setFilter(filter, true);
}
public void setFilter(ContactListFilter filter, boolean restoreSelectedUri) {
if (mFilter == null && filter == null) {
return;
}
if (mFilter != null && mFilter.equals(filter)) {
return;
}
Log.v(TAG, "New filter: " + filter);
mFilter = filter;
mLastSelectedPosition = -1;
saveFilter();
if (restoreSelectedUri) {
mSelectedContactUri = null;
restoreSelectedUri(true);
}
reloadData();
}
public ContactListFilter getFilter() {
return mFilter;
}
@Override
public void restoreSavedState(Bundle savedState) {
super.restoreSavedState(savedState);
if (savedState == null) {
return;
}
mFilter = savedState.getParcelable(KEY_FILTER);
mSelectedContactUri = savedState.getParcelable(KEY_SELECTED_URI);
mSelectionVerified = savedState.getBoolean(KEY_SELECTION_VERIFIED);
mLastSelectedPosition = savedState.getInt(KEY_LAST_SELECTED_POSITION);
parseSelectedContactUri();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_FILTER, mFilter);
outState.putParcelable(KEY_SELECTED_URI, mSelectedContactUri);
outState.putBoolean(KEY_SELECTION_VERIFIED, mSelectionVerified);
outState.putInt(KEY_LAST_SELECTED_POSITION, mLastSelectedPosition);
}
protected void refreshSelectedContactUri() {
if (mContactLookupTask != null) {
mContactLookupTask.cancel();
}
if (!isSelectionVisible()) {
return;
}
mRefreshingContactUri = true;
if (mSelectedContactUri == null) {
onContactUriQueryFinished(null);
return;
}
if (mSelectedContactDirectoryId != Directory.DEFAULT
&& mSelectedContactDirectoryId != Directory.LOCAL_INVISIBLE) {
onContactUriQueryFinished(mSelectedContactUri);
} else {
mContactLookupTask = new ContactLookupTask(mSelectedContactUri);
mContactLookupTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
}
}
protected void onContactUriQueryFinished(Uri uri) {
mRefreshingContactUri = false;
mSelectedContactUri = uri;
parseSelectedContactUri();
checkSelection();
}
@Override
protected void prepareEmptyView() {
if (isSearchMode()) {
return;
} else if (isSyncActive()) {
if (hasIccCard()) {
setEmptyText(R.string.noContactsHelpTextWithSync);
} else {
setEmptyText(R.string.noContactsNoSimHelpTextWithSync);
}
} else {
if (hasIccCard()) {
setEmptyText(R.string.noContactsHelpText);
} else {
setEmptyText(R.string.noContactsNoSimHelpText);
}
}
}
public Uri getSelectedContactUri() {
return mSelectedContactUri;
}
/**
* Sets the new selection for the list.
*/
public void setSelectedContactUri(Uri uri) {
setSelectedContactUri(uri, true, true, true, false);
}
@Override
public void setQueryString(String queryString, boolean delaySelection) {
mDelaySelection = delaySelection;
super.setQueryString(queryString, delaySelection);
}
/**
* Sets whether or not a contact selection must be made.
* @param required if true, we need to check if the selection is present in
* the list and if not notify the listener so that it can load a
* different list.
* TODO: Figure out how to reconcile this with {@link #setSelectedContactUri},
* without causing unnecessary loading of the list if the selected contact URI is
* the same as before.
*/
public void setSelectionRequired(boolean required) {
mSelectionRequired = required;
}
/**
* Sets the new contact selection.
*
* @param uri the new selection
* @param required if true, we need to check if the selection is present in
* the list and if not notify the listener so that it can load a
* different list
* @param smoothScroll if true, the UI will roll smoothly to the new
* selection
* @param persistent if true, the selection will be stored in shared
* preferences.
* @param willReloadData if true, the selection will be remembered but not
* actually shown, because we are expecting that the data will be
* reloaded momentarily
*/
private void setSelectedContactUri(Uri uri, boolean required, boolean smoothScroll,
boolean persistent, boolean willReloadData) {
mSmoothScrollRequested = smoothScroll;
mSelectionToScreenRequested = true;
if ((mSelectedContactUri == null && uri != null)
|| (mSelectedContactUri != null && !mSelectedContactUri.equals(uri))) {
mSelectionVerified = false;
mSelectionRequired = required;
mSelectionPersistenceRequested = persistent;
mSelectedContactUri = uri;
parseSelectedContactUri();
if (!willReloadData) {
// Configure the adapter to show the selection based on the
// lookup key extracted from the URI
ContactListAdapter adapter = getAdapter();
if (adapter != null) {
adapter.setSelectedContact(mSelectedContactDirectoryId,
mSelectedContactLookupKey, mSelectedContactId);
getListView().invalidateViews();
}
}
// Also, launch a loader to pick up a new lookup URI in case it has changed
refreshSelectedContactUri();
}
}
private void parseSelectedContactUri() {
if (mSelectedContactUri != null) {
String directoryParam =
mSelectedContactUri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY);
mSelectedContactDirectoryId = TextUtils.isEmpty(directoryParam) ? Directory.DEFAULT
: Long.parseLong(directoryParam);
if (mSelectedContactUri.toString().startsWith(Contacts.CONTENT_LOOKUP_URI.toString())) {
List<String> pathSegments = mSelectedContactUri.getPathSegments();
mSelectedContactLookupKey = Uri.encode(pathSegments.get(2));
if (pathSegments.size() == 4) {
mSelectedContactId = ContentUris.parseId(mSelectedContactUri);
}
} else if (mSelectedContactUri.toString().startsWith(Contacts.CONTENT_URI.toString()) &&
mSelectedContactUri.getPathSegments().size() >= 2) {
mSelectedContactLookupKey = null;
mSelectedContactId = ContentUris.parseId(mSelectedContactUri);
} else {
Log.e(TAG, "Unsupported contact URI: " + mSelectedContactUri);
mSelectedContactLookupKey = null;
mSelectedContactId = 0;
}
} else {
mSelectedContactDirectoryId = Directory.DEFAULT;
mSelectedContactLookupKey = null;
mSelectedContactId = 0;
}
}
@Override
protected void configureAdapter() {
super.configureAdapter();
ContactListAdapter adapter = getAdapter();
if (adapter == null) {
return;
}
boolean searchMode = isSearchMode();
if (!searchMode && mFilter != null) {
adapter.setFilter(mFilter);
if (mSelectionRequired
|| mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
adapter.setSelectedContact(
mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId);
}
}
// Display the user's profile if not in search mode
adapter.setIncludeProfile(!searchMode);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
super.onLoadFinished(loader, data);
mSelectionVerified = false;
// Refresh the currently selected lookup in case it changed while we were sleeping
refreshSelectedContactUri();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
private void checkSelection() {
if (mSelectionVerified) {
return;
}
if (mRefreshingContactUri) {
return;
}
if (isLoadingDirectoryList()) {
return;
}
ContactListAdapter adapter = getAdapter();
if (adapter == null) {
return;
}
boolean directoryLoading = true;
int count = adapter.getPartitionCount();
for (int i = 0; i < count; i++) {
Partition partition = adapter.getPartition(i);
if (partition instanceof DirectoryPartition) {
DirectoryPartition directory = (DirectoryPartition) partition;
if (directory.getDirectoryId() == mSelectedContactDirectoryId) {
directoryLoading = directory.isLoading();
break;
}
}
}
if (directoryLoading) {
return;
}
adapter.setSelectedContact(
mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId);
final int selectedPosition = adapter.getSelectedContactPosition();
if (selectedPosition != -1) {
mLastSelectedPosition = selectedPosition;
} else {
if (isSearchMode()) {
if (mDelaySelection) {
selectFirstFoundContactAfterDelay();
if (mListener != null) {
mListener.onSelectionChange();
}
return;
}
} else if (mSelectionRequired) {
// A specific contact was requested, but it's not in the loaded list.
// Try reconfiguring and reloading the list that will hopefully contain
// the requested contact. Only take one attempt to avoid an infinite loop
// in case the contact cannot be found at all.
mSelectionRequired = false;
// If we were looking at a different specific contact, just reload
if (mFilter != null
&& mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
reloadData();
} else {
// Otherwise, call the listener, which will adjust the filter.
notifyInvalidSelection();
}
return;
} else if (mFilter != null
&& mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
// If we were trying to load a specific contact, but that contact no longer
// exists, call the listener, which will adjust the filter.
notifyInvalidSelection();
return;
}
saveSelectedUri(null);
selectDefaultContact();
}
mSelectionRequired = false;
mSelectionVerified = true;
if (mSelectionPersistenceRequested) {
saveSelectedUri(mSelectedContactUri);
mSelectionPersistenceRequested = false;
}
if (mSelectionToScreenRequested) {
requestSelectionToScreen(selectedPosition);
}
getListView().invalidateViews();
if (mListener != null) {
mListener.onSelectionChange();
}
}
/**
* Automatically selects the first found contact in search mode. The selection
* is updated after a delay to allow the user to type without to much UI churn
* and to save bandwidth on directory queries.
*/
public void selectFirstFoundContactAfterDelay() {
Handler handler = getHandler();
handler.removeMessages(MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT);
String queryString = getQueryString();
if (queryString != null
&& queryString.length() >= AUTOSELECT_FIRST_FOUND_CONTACT_MIN_QUERY_LENGTH) {
handler.sendEmptyMessageDelayed(MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT,
DELAY_AUTOSELECT_FIRST_FOUND_CONTACT_MILLIS);
} else {
setSelectedContactUri(null, false, false, false, false);
}
}
protected void selectDefaultContact() {
Uri contactUri = null;
ContactListAdapter adapter = getAdapter();
if (mLastSelectedPosition != -1) {
int count = adapter.getCount();
int pos = mLastSelectedPosition;
if (pos >= count && count > 0) {
pos = count - 1;
}
contactUri = adapter.getContactUri(pos);
}
if (contactUri == null) {
contactUri = adapter.getFirstContactUri();
}
setSelectedContactUri(contactUri, false, mSmoothScrollRequested, false, false);
}
protected void requestSelectionToScreen(int selectedPosition) {
if (selectedPosition != -1) {
AutoScrollListView listView = (AutoScrollListView)getListView();
listView.requestPositionToScreen(
selectedPosition + listView.getHeaderViewsCount(), mSmoothScrollRequested);
mSelectionToScreenRequested = false;
}
}
@Override
public boolean isLoading() {
return mRefreshingContactUri || super.isLoading();
}
@Override
protected void startLoading() {
mStartedLoading = true;
mSelectionVerified = false;
super.startLoading();
}
public void reloadDataAndSetSelectedUri(Uri uri) {
setSelectedContactUri(uri, true, true, true, true);
reloadData();
}
@Override
public void reloadData() {
if (mStartedLoading) {
mSelectionVerified = false;
mLastSelectedPosition = -1;
super.reloadData();
}
}
public void setOnContactListActionListener(OnContactBrowserActionListener listener) {
mListener = listener;
}
public void createNewContact() {
if (mListener != null) mListener.onCreateNewContactAction();
}
public void viewContact(Uri contactUri) {
setSelectedContactUri(contactUri, false, false, true, false);
if (mListener != null) mListener.onViewContactAction(contactUri);
}
public void editContact(Uri contactUri) {
if (mListener != null) mListener.onEditContactAction(contactUri);
}
public void deleteContact(Uri contactUri) {
if (mListener != null) mListener.onDeleteContactAction(contactUri);
}
public void addToFavorites(Uri contactUri) {
if (mListener != null) mListener.onAddToFavoritesAction(contactUri);
}
public void removeFromFavorites(Uri contactUri) {
if (mListener != null) mListener.onRemoveFromFavoritesAction(contactUri);
}
public void callContact(Uri contactUri) {
if (mListener != null) mListener.onCallContactAction(contactUri);
}
public void smsContact(Uri contactUri) {
if (mListener != null) mListener.onSmsContactAction(contactUri);
}
private void notifyInvalidSelection() {
if (mListener != null) mListener.onInvalidSelection();
}
@Override
protected void finish() {
super.finish();
if (mListener != null) mListener.onFinishAction();
}
private void saveSelectedUri(Uri contactUri) {
if (isSearchMode()) {
return;
}
ContactListFilter.storeToPreferences(mPrefs, mFilter);
Editor editor = mPrefs.edit();
if (contactUri == null) {
editor.remove(getPersistentSelectionKey());
} else {
editor.putString(getPersistentSelectionKey(), contactUri.toString());
}
editor.apply();
}
private void restoreSelectedUri(boolean willReloadData) {
// The meaning of mSelectionRequired is that we need to show some
// selection other than the previous selection saved in shared preferences
if (mSelectionRequired) {
return;
}
String selectedUri = mPrefs.getString(getPersistentSelectionKey(), null);
if (selectedUri == null) {
setSelectedContactUri(null, false, false, false, willReloadData);
} else {
setSelectedContactUri(Uri.parse(selectedUri), false, false, false, willReloadData);
}
}
private void saveFilter() {
ContactListFilter.storeToPreferences(mPrefs, mFilter);
}
private void restoreFilter() {
mFilter = ContactListFilter.restoreDefaultPreferences(mPrefs);
}
private String getPersistentSelectionKey() {
if (mFilter == null) {
return mPersistentSelectionPrefix;
} else {
return mPersistentSelectionPrefix + "-" + mFilter.getId();
}
}
public boolean isOptionsMenuChanged() {
// This fragment does not have an option menu of its own
return false;
}
/*Start of wangqiang on 2012-3-20 17:52 cantacts_longclick*/
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.wtf(TAG, "Bad menuInfo", e);
return;
}
ContactListAdapter adapter = this.getAdapter();
int headerViewsCount = this.getListView().getHeaderViewsCount();
int position = info.position - headerViewsCount;
// Setup the menu header
menu.setHeaderTitle(adapter.getContactDisplayName(position));
// View contact details
menu.add(0, MENU_ITEM_VIEW_CONTACT, 0, R.string.menu_viewContact);
//if (adapter.getHasPhoneNumber(position)) {
Cursor cursor = null;
try{
cursor = this.getContext().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, "_id="+adapter.getContactId(position), null, null);
}catch (Exception e) {
System.out.println(e.toString());
return;
}
cursor.moveToFirst();
if(cursor.getInt(cursor.getColumnIndex("has_phone_number"))!=0){
final Context context = this.getContext();
boolean hasPhoneApp = PhoneCapabilityTester.isPhone(context);
boolean hasSmsApp = PhoneCapabilityTester.isSmsIntentRegistered(context);
// Calling contact
if (hasPhoneApp) menu.add(0, MENU_ITEM_CALL, 0, R.string.menu_call);
// Send SMS item
if (hasSmsApp) menu.add(0, MENU_ITEM_SEND_SMS, 0, R.string.menu_sendSMS);
/* Begin: Modified by sunrise for AddContactToBlackNumber 2012/06/05 */
//System.out.println("Brows--->name_raw_contact_id:"
// + cursor.getColumnIndex("name_raw_contact_id"));
rawContactsId = String.valueOf(cursor.getInt(cursor
.getColumnIndex("name_raw_contact_id")));
Log.i(TAG, "Brows--->rawContactsId:" + rawContactsId);
Uri uriBlack = Uri
.parse("content://com.ahong.blackcall.AhongBlackCallProvider/black_number/contactid/"
+ rawContactsId);
Cursor curBlack = this.getContext().getContentResolver()
.query(uriBlack, null, null, null, null);
if (curBlack != null && curBlack.getCount() > 0)
{
menu.add(0, MENU_ITEM_DEL_BLACK, 0,
R.string.menu_delFromBlackList);
}
else
{
menu.add(0, MENU_ITEM_ADD_BLACK, 0,
R.string.menu_addToBlackList);
}
curBlack.close();
/* End: Modified by sunrise for AddContactToBlackNumber 2012/06/05 */
}
// Star toggling
//if (!adapter.isContactStarred(position)) {
if(cursor.getInt(cursor.getColumnIndex("starred"))==0){
menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_addStar);
} else {
menu.add(0, MENU_ITEM_TOGGLE_STAR, 0, R.string.menu_removeStar);
}
/*Begin: Modified by xiepengfei for cursor close bug 2012/06/07*/
if(cursor!=null){
cursor.close();
cursor = null;
}
/*End: Modified by xiepengfei for cursor close bug 2012/06/07*/
// Contact editing
menu.add(0, MENU_ITEM_EDIT, 0, R.string.menu_editContact);
menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_deleteContact);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
Log.wtf(TAG, "Bad menuInfo", e);
return false;
}
ContactListAdapter adapter = this.getAdapter();
int headerViewsCount = this.getListView().getHeaderViewsCount();
int position = info.position - headerViewsCount;
final Uri contactUri = adapter.getContactUri(position);
switch (item.getItemId()) {
case MENU_ITEM_VIEW_CONTACT: {
this.viewContact(contactUri);
return true;
}
case MENU_ITEM_TOGGLE_STAR: {
//if (adapter.isContactStarred(position)) {
Cursor cursor = this.getContext().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, "_id="+adapter.getContactId(position), null, null);
cursor.moveToFirst();
if(cursor.getInt(cursor.getColumnIndex("starred"))!=0){
this.removeFromFavorites(contactUri);
} else {
this.addToFavorites(contactUri);
}
return true;
}
/* Begin: Modified by sunrise for AddContactToBlackNumber 2012/06/05 */
case MENU_ITEM_ADD_BLACK:
{
//new Thread(new Runnable(){public void run(/* code */)})
List<String> numberArr = new ArrayList<String>();
Cursor curNumber = this
.getContext()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID
+ " =?",
new String[] { rawContactsId }, null);
if (curNumber != null && curNumber.moveToFirst())
{
do
{
String number = curNumber
.getString(curNumber
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
numberArr.add(number);
} while (curNumber.moveToNext());
curNumber.close();
Log.i(TAG, " numberArr: " + numberArr.toString());
}
else
{
return false;
}
for (String number : numberArr)
{
ContentValues value = new ContentValues();
if (number.length() > 48)
{
value.put("number", number.substring(0, 47));
}
else
{
value.put("number", number);
}
// value.put("name_raw_contact_id", Integer.parseInt(rawContactsId));
value.put("name_raw_contact_id", rawContactsId);
//at here,the better way is combine interface function AddBlackNumber(number)
Uri uriInsert = Uri
.parse("content://com.ahong.blackcall.AhongBlackCallProvider/black_number/contactid/"
+ rawContactsId);
Uri uAdd = this.getContext().getContentResolver()
.insert(uriInsert, value);
Log.i(TAG, uAdd.toString());
/*Begin: Modified by sunrise for add and del hint 2012/08/10*/
if (uAdd != null)
{
toastToBlack(R.string.add_to_black_success);
}
else
{
toastToBlack(R.string.add_to_black_fail);
return false;
}
/*End: Modified by sunrise for add and del hint 2012/08/10*/
}
return true;
}
case MENU_ITEM_DEL_BLACK:
{
if (rawContactsId != null)
{
Uri uriDelete = Uri
.parse("content://com.ahong.blackcall.AhongBlackCallProvider/black_number");
int result = this
.getContext()
.getContentResolver()
.delete(uriDelete, "name_raw_contact_id = ?",
new String[] { rawContactsId });
Log.i(TAG, "delete line: " + result);
/*Begin: Modified by sunrise for add and del hint 2012/08/10*/
if (result > 0)
{
toastToBlack(R.string.del_from_black_success);
}
else
{
toastToBlack(R.string.del_from_black_fail);
return false;
}
/*End: Modified by sunrise for add and del hint 2012/08/10*/
}
return true;
}
/* End: Modified by sunrise for AddContactToBlackNumber 2012/06/05 */
case MENU_ITEM_CALL: {
this.callContact(contactUri);
return true;
}
case MENU_ITEM_SEND_SMS: {
this.smsContact(contactUri);
return true;
}
case MENU_ITEM_EDIT: {
this.editContact(contactUri);
return true;
}
case MENU_ITEM_DELETE: {
this.deleteContact(contactUri);
return true;
}
}
return false;
}
/*End of wangqiang on 2012-3-20 17:52 cantacts_longclick*/
/*Begin: Modified by sunrise for add and del hint 2012/08/10*/
private void toastToBlack(int resId)
{
Toast.makeText(this.getContext(), resId, Toast.LENGTH_SHORT).show();
}
/*End: Modified by sunrise for add and del hint 2012/08/10*/
}
| gpl-2.0 |
bonn036/Zoo | zxing/src/main/java/com/mmnn/zxing/camera/AutoFocusManager.java | 4562 | /*
* Copyright (C) 2012 ZXing authors
*
* 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.mmnn.zxing.camera;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.RejectedExecutionException;
public class AutoFocusManager implements Camera.AutoFocusCallback {
private static final String TAG = AutoFocusManager.class.getSimpleName();
private static final long AUTO_FOCUS_INTERVAL_MS = 2000L;
private static final Collection<String> FOCUS_MODES_CALLING_AF;
static {
FOCUS_MODES_CALLING_AF = new ArrayList<String>(2);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_AUTO);
FOCUS_MODES_CALLING_AF.add(Camera.Parameters.FOCUS_MODE_MACRO);
}
private final boolean useAutoFocus;
private final Camera camera;
private boolean stopped;
private boolean focusing;
private AsyncTask<?, ?, ?> outstandingTask;
public AutoFocusManager(Context context, Camera camera) {
this.camera = camera;
String currentFocusMode = camera.getParameters().getFocusMode();
useAutoFocus = FOCUS_MODES_CALLING_AF.contains(currentFocusMode);
Log.i(TAG, "Current focus mode '" + currentFocusMode + "'; use auto focus? " + useAutoFocus);
start();
}
@Override
public synchronized void onAutoFocus(boolean success, Camera theCamera) {
focusing = false;
autoFocusAgainLater();
}
@SuppressLint("NewApi")
private synchronized void autoFocusAgainLater() {
if (!stopped && outstandingTask == null) {
AutoFocusTask newTask = new AutoFocusTask();
try {
if (Build.VERSION.SDK_INT >= 11) {
newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
newTask.execute();
}
outstandingTask = newTask;
} catch (RejectedExecutionException ree) {
Log.w(TAG, "Could not request auto focus", ree);
}
}
}
public synchronized void start() {
if (useAutoFocus) {
outstandingTask = null;
if (!stopped && !focusing) {
try {
camera.autoFocus(this);
focusing = true;
} catch (RuntimeException re) {
// Have heard RuntimeException reported in Android 4.0.x+;
// continue?
Log.w(TAG, "Unexpected exception while focusing", re);
// Try again later to keep cycle going
autoFocusAgainLater();
}
}
}
}
private synchronized void cancelOutstandingTask() {
if (outstandingTask != null) {
if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) {
outstandingTask.cancel(true);
}
outstandingTask = null;
}
}
public synchronized void stop() {
stopped = true;
if (useAutoFocus) {
cancelOutstandingTask();
// Doesn't hurt to call this even if not focusing
try {
camera.cancelAutoFocus();
} catch (RuntimeException re) {
// Have heard RuntimeException reported in Android 4.0.x+;
// continue?
Log.w(TAG, "Unexpected exception while cancelling focusing", re);
}
}
}
private final class AutoFocusTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... voids) {
try {
Thread.sleep(AUTO_FOCUS_INTERVAL_MS);
} catch (InterruptedException e) {
// continue
}
start();
return null;
}
}
}
| gpl-2.0 |
alenab/MyLabs | src/module6/task2/Rosebush.java | 76 | package module6.task2;
public class Rosebush {
private Rose[] roses;
}
| gpl-2.0 |
hzssean/soas | soas-core/soas-web/src/main/java/org/saiku/web/rest/resources/DatabaseConfigResource.java | 5162 | package org.saiku.web.rest.resources;
import org.saiku.service.ISessionService;
import org.saiku.web.bean.DatabaseInfoBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import org.saiku.web.bean.DatabaseInfoBean;
import org.saiku.web.dao.DatabaseInfoDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* User: zhisheng.hzs
* Date: 12-9-6
* Time: 上午10:32
* 保存连接配置信息
*/
@Component
@Path("/saiku/database")
@XmlAccessorType(XmlAccessType.NONE)
public class DatabaseConfigResource {
private static final Logger log = LoggerFactory.getLogger(DatabaseConfigResource.class);
DatabaseInfoDao dao=null;
/*public void setConnection(ISessionService connection) throws Exception{
try{
}
catch (Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}*/
//TODO 保存
@POST
@Path("/save")
public String saveConfig(@FormParam("con_name") String con_name,
@FormParam("con_server") String con_server,
@FormParam("con_port") String con_port,
@FormParam("con_type") String con_type,
@FormParam("user") String user,
@FormParam("password") String password){
ApplicationContext ctx=new ClassPathXmlApplicationContext("soasManager.xml");
dao=(DatabaseInfoDao)ctx.getBean("DatabaseInfoDao");
String s_UUID=UUID.randomUUID().toString();
DatabaseInfoBean config_info=new DatabaseInfoBean();
config_info.setConnection_name(con_name);
config_info.setConnection_type(con_type);
config_info.setDatabase_server(con_server);
config_info.setDatabase_port(con_port);
config_info.setUserid(user);
config_info.setPassword(password);//设置好保存的内容
dao.insertConfigInfo(config_info);
return "saved";
}
//TODO 返回已存信息
@GET
@Path("/load")
@Produces("application/json")
public List showConfigInfo() throws Exception{
List<DatabaseInfoBean> config_information=new ArrayList<DatabaseInfoBean>();
try{
ApplicationContext ctx=new ClassPathXmlApplicationContext("soasManager.xml");
dao=(DatabaseInfoDao)ctx.getBean("DatabaseInfoDao");
List[] config_info_tmp=dao.showConfigInfo();//获取到数据库的配置信息。
List<String> config_name= config_info_tmp[0];
List<String> config_type= config_info_tmp[1];
List<String> config_server= config_info_tmp[2];
List<String> config_port=config_info_tmp[3];
List<String> config_user= config_info_tmp[4];
List<String> config_password= config_info_tmp[5];//依次为name,type,server.port,user,
for(int i=0;i<config_name.size();i++){
DatabaseInfoBean databaseInfoBean=new DatabaseInfoBean();
databaseInfoBean.setConnection_name(config_name.get(i));
databaseInfoBean.setConnection_type(config_type.get(i));
databaseInfoBean.setDatabase_server(config_server.get(i));
databaseInfoBean.setDatabase_port(config_port.get(i));
databaseInfoBean.setUserid(config_user.get(i));
databaseInfoBean.setPassword(config_password.get(i));
config_information.add(databaseInfoBean);//依次添加
}
}
catch (Exception e){
System.out.println(e.getMessage());
//System.out.println(e.getErrorCode());
e.printStackTrace();
}
return config_information;
}
//TODO 删除信息
@POST
@Path("/delete")
public String deleteConfigInfo(@FormParam("con_name") String con_name) throws Exception{
try{
ApplicationContext ctx=new ClassPathXmlApplicationContext("soasManager.xml");
dao=(DatabaseInfoDao)ctx.getBean("DatabaseInfoDao");
DatabaseInfoBean config_info=new DatabaseInfoBean();
config_info.setConnection_name(con_name);//根据保存名称来删除
dao.deleteConfigInfo(config_info);
}
catch (Exception e){
System.out.println(e.getMessage());
//System.out.println(e.getErrorCode());
e.printStackTrace();
}
return "deleted!";
}
}
| gpl-2.0 |
uscbp/scs | nsl_models/HopfieldModel/HopfieldModel/v1_1_1/src/HopfieldModel.java | 2764 | package HopfieldModel.HopfieldModel.v1_1_1.src;
import HopfieldModel.HopfieldNetwork.v1_1_1.src.*;
/*********************************/
/* */
/* Importing all Nsl classes */
/* */
/*********************************/
import nslj.src.system.*;
import nslj.src.cmd.*;
import nslj.src.lang.*;
import nslj.src.math.*;
import nslj.src.display.*;
import nslj.src.display.j3d.*;
/*********************************/
public class HopfieldModel extends NslModel{
//NSL Version: 3_0_n
//Sif Version: 9
//libNickName: HopfieldModel
//moduleName: HopfieldModel
//versionName: 1_1_1
//floatSubModules: true
//variables
public HopfieldNetwork net; //
private int size=6; //
//methods
public void initSys()
{
system.setRunEndTime(300);
system.setTrainEndTime(1);
system.setTrainDelta(1);
system.setRunDelta(1);
}
public void initModule()
{
nslSetTrainDelta(1);
nslSetRunDelta(1);
NslInt2 in= new NslInt2(size, size);
in.set(-1);
net.input.setReference(in);
nslAddAreaCanvas("output", "output", net.output,-1,1);
nslAddTemporalCanvas("output", "energy", net.energy, -size*size,0, NslColor.getColor("BLACK"));
nslAddInputImageCanvas("input","input", net.input, -1, 1);
addPanel("control", "input");
addButtonToPanel("clear", "Clear Image", "control", "input");
}
public void clearPushed()
{
net.input.set(-1);
}
public void makeConn(){
}
/******************************************************/
/* */
/* Generated by nslc.src.NslCompiler. Do not edit these lines! */
/* */
/******************************************************/
/* Constructor and related methods */
/* makeinst() declared variables */
/* EMPTY CONSTRUCTOR: Called only for the top level module */
public HopfieldModel() {
super("hopfieldModel",(NslModel)null);
initSys();
makeInstHopfieldModel("hopfieldModel",null);
}
/* Formal parameters */
/* Temporary variables */
/* GENERIC CONSTRUCTOR: */
public HopfieldModel(String nslName, NslModule nslParent)
{
super(nslName, nslParent);
initSys();
makeInstHopfieldModel(nslName, nslParent);
}
public void makeInstHopfieldModel(String nslName, NslModule nslParent)
{
Object[] nslArgs=new Object[]{};
callFromConstructorTop(nslArgs);
net = new HopfieldNetwork("net", this, size);
callFromConstructorBottom();
}
/******************************************************/
/* */
/* End of automatic declaration statements. */
/* */
/******************************************************/
}//end HopfieldModel
| gpl-2.0 |
sadjava/Fortunes-Tower | src/com/peterson/programs/fortunestowergame/GameFrame.java | 12819 | package com.peterson.programs.fortunestowergame;
import com.peterson.programs.fortunestower.Board;
import com.peterson.programs.fortunestower.Board2D;
import com.peterson.programs.fortunestower.Deck;
import com.peterson.programs.fortunestower.TestDeck;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
/**
* Main GUI class for the game of Fortune's Tower.
* This will display a frame that will allow the user
* to play game of Fortunes Tower.
* @author Peterson, Ryan
* Created 7/26/2014
*/
public class GameFrame extends JFrame
{
/*
Logic Objects
*/
private GamePanel panel;
private Board board;
private Deck deck;
private GameBoard map;
/*
Display Objects
*/
private JPanel sidePanel;
private JTextField[] fields;
private JPanel buttonPanel;
private JButton drawButton;
private JButton cashOutButton;
private JButton reset;
private Container cp;
private ActionListener draw;
private int rowPtr;
private int numCards;
private long playerPoints;
private JLabel pointLabel;
/*
Constants for the background and foreground colors
*/
private static final Color BACKGROUND = new Color(12, 128, 37);
private static final Color FOREGROUND = new Color(83, 128, 38);
/*
Coefficients that determine the size of the Cards
based off of the percentage of these with
getToolkit().getScreenSize().getWidth() and getToolkit().getScreenSize().getHeight().
They allow the cards to grow and shrink based on the computer monitor this program
runs on.
*/
private static final int WIDTH_COEFF = 25;
private static final int HEIGHT_COEFF = 10;
/*
The font that the buttons and text fields will have
*/
private static final Font FONTZ = new Font("Font", Font.BOLD, 15);
/**
* Creates the window to play the game of Fortunes Tower.
* This will do the necessary steps to construct the frame and add action listeners
* for the user to draw cards, cash out, and reset the board
* @param numberCards the number of cards to play with. Use the constants from the Deck class
* for the standard sizes.
*/
public GameFrame(final int numberCards)
{
super("Fortunes Tower");
playerPoints = 0;
pointLabel = new JLabel("Points: " + playerPoints);
deck = new GameDeck(numberCards);
panel = new GamePanel();
board = new Board2D(deck);
fields = new JTextField[8];
for (int i = 0; i < fields.length; i++)
{
fields[i] = new JTextField();
fields[i].setEditable(false);
fields[i].setColumns(5);
fields[i].setFont(FONTZ);
fields[i].setHorizontalAlignment(SwingConstants.RIGHT);
}
fields[0].setText("Points");
fields[0].setBackground(Color.DARK_GRAY);
fields[0].setForeground(Color.WHITE);
fields[0].setEnabled(false);
numCards = numberCards;
rowPtr = 1;
create();
}
/*
Constructs the initial state of the GUI.
*/
private void create()
{
cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.setBackground(BACKGROUND);
panel.setBackground(BACKGROUND);
panel.setBackgroundColor(FOREGROUND);
cp.add(panel, BorderLayout.CENTER);
sidePanel = new JPanel();
sidePanel.setLayout(new GridLayout(8, 1, 100, 100));
cp.add(sidePanel, BorderLayout.WEST);
sidePanel.setBackground(BACKGROUND);
for (JTextField f : fields)
sidePanel.add(f);
buttonPanel = new JPanel();
buttonPanel.setBackground(BACKGROUND);
cp.add(buttonPanel, BorderLayout.SOUTH);
drawButton = new JButton("Deal Next Row");
drawButton.setFont(FONTZ);
draw = new DealListener();
drawButton.addActionListener(draw);
buttonPanel.add(drawButton);
cashOutButton = new JButton("Cash Out");
cashOutButton.setFont(FONTZ);
cashOutButton.addActionListener(new CashOutListener());
buttonPanel.add(cashOutButton);
reset = new JButton("Reset");
reset.setFont(FONTZ);
reset.addActionListener(new ResetListener());
buttonPanel.add(reset);
buttonPanel.add(pointLabel);
pointLabel.setFont(FONTZ);
pointLabel.setForeground(Color.BLUE);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
JMenu m = new JMenu("Info");
JMenuItem i = new JMenuItem("Rules");
i.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, RulesLoader.getRules(), "Rules",
JOptionPane.INFORMATION_MESSAGE);
}
});
m.add(i);
bar.add(m);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
/*
Set the width to fill the screen from left to right, but
set the height to be 50 less than the screen size
*/
int width = (int) getToolkit().getScreenSize().getWidth();
int height = (int) (getToolkit().getScreenSize().getHeight() - 50);
setSize(width, height);
postInit();
}
/*
Post GUI initialzation to display the first
two rows of the Board.
*/
private void postInit()
{
double pWidth = getToolkit().getScreenSize().getWidth();
double pHeight = getToolkit().getScreenSize().getHeight();
map = new GameBoard(board, (int) pWidth / WIDTH_COEFF, (int) pHeight / HEIGHT_COEFF);
panel.addRow(map.mapRow(0));
panel.addRow(map.mapRow(1));
fields[1].setText(board.lastRowValue() + "");
}
/*
Loads and displays the rules of the game.
*/
private static class RulesLoader
{
private static final String FILE = "rules.txt";
/*
Gets the rules of the game
*/
public static String getRules()
{
try
{
StringBuilder b = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(GameFrame.class.getResourceAsStream(FILE)));
String line;
while ((line = reader.readLine()) != null)
{
b.append(line).append(System.getProperty("line.separator"));
}
reader.close();
return b.toString();
}
catch (Exception e)
{
/*
This should never happen; if it does, come beat me with a
rubber chicken
*/
throw new RuntimeException(e);
}
}
}
/*
Game Logic class to run the game of Fortunes Tower.
This action listener will draw a row of cards, display them,
and if a Misfortune occurs, try to correct it if one hasn't happened yet.
*/
private class DealListener implements ActionListener
{
private boolean trySave;
public DealListener()
{
trySave = false;
}
@Override
public void actionPerformed(ActionEvent e)
{
/*
See the file "fortunes tower algorithm" for the details
of this algorithm.
*/
if (!board.isComplete())
{
board.nextRow();
rowPtr++;
panel.addRow(map.mapRow(rowPtr));
fields[rowPtr].setText("" + board.lastRowValue());
if (board.misFortune())
{
if (!trySave)
{
StringBuilder b = new StringBuilder("A Misfortune has Occurred!\n");
b.append("A save will now be attempted");
trySave = true;
JOptionPane.showMessageDialog(null, b.toString(), "Misfortune",
JOptionPane.INFORMATION_MESSAGE);
board.trySave();
panel.flipGate();
panel.removeLastRow();
panel.addRow(map.mapRow(rowPtr));
fields[rowPtr].setText("" + board.lastRowValue());
//panel.repaint();
if (board.misFortune())
{
JOptionPane.showMessageDialog(null, "Misfortune. Game Over");
//test.setEnabled(false);
drawButton.setEnabled(false);
cashOutButton.setEnabled(false);
}
}
else
{
JOptionPane.showMessageDialog(null, "Misfortune. Game Over", "Misfortune",
JOptionPane.INFORMATION_MESSAGE);
//test.setEnabled(false);
drawButton.setEnabled(false);
cashOutButton.setEnabled(false);
}
}
if (board.isComplete() && !board.misFortune())
{
if (board.hitJackpot())
{
int total = board.jackpotValue();
JOptionPane.showMessageDialog(null, "Jackpot!\n" + total);
playerPoints += total;
}
else
{
int total = board.rowValue(7);
JOptionPane.showMessageDialog(null, "Winner\n" + total);
playerPoints += total;
}
//test.setEnabled(false);
pointLabel.setText("Points: " + playerPoints);
drawButton.setEnabled(false);
cashOutButton.setEnabled(false);
}
}
}
}
/*
Allows the player to cash out.
The player wins the current row's point value,
and the game is continued, displaying the remainder of the rows,
but does not check for a misfortune
*/
private class CashOutListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if (drawButton.isEnabled())
{
int total = board.rowValue(rowPtr);
JOptionPane.showMessageDialog(null, "Cashed out and won:\n" + total);
cashOutButton.setEnabled(false);
drawButton.setEnabled(false);
playerPoints += total;
pointLabel.setText("Points: " + playerPoints);
if (!board.isComplete())
JOptionPane.showMessageDialog(null, "The game will now continue and show the results\n",
"What if?", JOptionPane.PLAIN_MESSAGE);
while (!board.isComplete())
{
board.nextRow();
rowPtr++;
panel.addRow(map.mapRow(rowPtr));
fields[rowPtr].setText("" + board.lastRowValue());
}
}
}
}
/*
* Resets the game to the initial state.
* Each game object is recreated and set to their initial states
* and the frame is reset to display the first two rows.
*/
private class ResetListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
cp.remove(panel);
deck = new TestDeck(numCards);
panel = new GamePanel();
board = new Board2D(deck);
for (int i = 1; i < fields.length; i++)
fields[i].setText("");
rowPtr = 1;
cp.add(panel, BorderLayout.CENTER);
panel.setBackgroundColor(FOREGROUND);
panel.setBackground(FOREGROUND);
drawButton.setEnabled(true);
drawButton.removeActionListener(draw);
draw = new DealListener();
drawButton.addActionListener(draw);
cashOutButton.setEnabled(true);
postInit();
}
}
}
| gpl-2.0 |
active-learning/active-learning-scala | src/main/java/clus/algo/rules/RuleNormalization.java | 3176 | /*************************************************************************
* Clus - Software for Predictive Clustering *
* Copyright (C) 2010 *
* Katholieke Universiteit Leuven, Leuven, Belgium *
* Jozef Stefan Institute, Ljubljana, Slovenia *
* *
* 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/>. *
* *
* Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. *
*************************************************************************/
/*
* Created on March 8, 2010
*/
package clus.algo.rules;
/** Information about rule normalization. Is used in rule optimization and linear term normalization.
* @author Timo Aho
*/
public class RuleNormalization {
/** Class variable. Means of descriptive attributes */
static private double[] C_descMeans = null;
/** Class variable. Standard deviation values of descriptive attributes */
static private double[] C_descStdDevs = null;
/** Class variable. Means of target attributes */
static private double[] C_targMeans = null;
/** Class variable. Standard deviation values of target attributes */
static private double[] C_targStdDevs = null;
/** Initializes the statistical information about the data. Index 0 includes means, index 1 std dev
* for both the parameters.
* @param descMeanAndStdDev Mean and std dev for descriptive attributes.
* @param targMeanAndStdDev Mean and std dev for target attributes.
*/
public static void initialize(double[][] descMeanAndStdDev, double[][] targMeanAndStdDev) {
C_descStdDevs = descMeanAndStdDev[1];
C_descMeans = descMeanAndStdDev[0];
C_targStdDevs = targMeanAndStdDev[1];
C_targMeans = targMeanAndStdDev[0];
}
public static double getDescMean(int iDescriptiveAttr) {
return C_descMeans[iDescriptiveAttr];
}
public static double getTargMean(int iTargetAttr) {
return C_targMeans[iTargetAttr];
}
public static double getDescStdDev(int iDescriptiveAttr) {
return C_descStdDevs[iDescriptiveAttr];
}
public static double getTargStdDev(int iTargetAttr) {
return C_targStdDevs[iTargetAttr];
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest20262.java | 2271 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest20262")
public class BenchmarkTest20262 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getQueryString();
String bar = doSomething(param);
try {
int randNumber = java.security.SecureRandom.getInstance("SHA1PRNG").nextInt(99);
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextInt(int) - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextInt(int) executed");
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple ? condition that assigns constant to bar on true condition
int i = 106;
bar = (7*18) + i > 200 ? "This_should_always_happen" : param;
return bar;
}
}
| gpl-2.0 |
BayCEER/goat | src/main/java/de/unibayreuth/bayeos/goat/tree/JObjektTree.java | 3637 | /*******************************************************************************
* Copyright (c) 2011 University of Bayreuth - BayCEER.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* University of Bayreuth - BayCEER - initial API and implementation
******************************************************************************/
package de.unibayreuth.bayeos.goat.tree;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.ToolTipManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.apache.log4j.Logger;
public class JObjektTree extends javax.swing.JTree
{
protected final static Logger logger = Logger.getLogger("JObjektTree.class");
private final static Insets autoscrollInsets = new Insets(20, 20, 20, 20); // insets
public JObjektTree(TreeModel treeModel)
{
super(treeModel);
setBorder(null);
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
// ensure that the tree view displays tool tips
ToolTipManager.sharedInstance().registerComponent(this);
}
public void expandPathTo(TreePath path){
logger.debug("expandPathTo:" + path.toString());
expandPath(path);
setSelectionPath(path);
scrollPathToVisible(path);
}
// drag and drop scrolling
public void autoscroll(Point cursorLocation) {
Insets insets = getAutoscrollInsets();
Rectangle outer = getVisibleRect();
Rectangle inner = new Rectangle(outer.x+insets.left, outer.y+insets.top, outer.width-(insets.left+insets.right), outer.height-(insets.top+insets.bottom));
if (!inner.contains(cursorLocation)) {
Rectangle scrollRect = new Rectangle(cursorLocation.x-insets.left, cursorLocation.y-insets.top, insets.left+insets.right, insets.top+insets.bottom);
scrollRectToVisible(scrollRect);
}
}
public Insets getAutoscrollInsets() {
return (autoscrollInsets);
}
public void refreshCurrentNode() {
TreePath path = getSelectionPath();
if (path != null) {
logger.debug(path.toString());
DefaultObjektNode node = (DefaultObjektNode)getLastSelectedPathComponent();
node.unloadChildren();
((DefaultTreeModel)getModel()).nodeStructureChanged(node);
}
}
public void refreshRoot(){
TreeModel m = this.treeModel;
DefaultObjektNode root = (DefaultObjektNode)getModel().getRoot();
root.unloadChildren();
((DefaultTreeModel)getModel()).nodeStructureChanged(root);
}
public ObjektNode getLastSelectedUserObjekt() {
DefaultObjektNode node = (DefaultObjektNode)getLastSelectedPathComponent();
if (node == null) return null;
return (ObjektNode)node.getUserObject();
}
/**
* Returns the TreeNode instance that is selected in the tree.
* If nothing is selected, null is returned.
*/
public DefaultMutableTreeNode getLastSelectedNode() {
TreePath selPath = getSelectionPath();
if(selPath != null)
return (DefaultMutableTreeNode)selPath.getLastPathComponent();
return null;
}
}
| gpl-2.0 |
gardir/INF1010-V16 | uke06/Stakk.java | 1209 | import java.util.Iterator;
public class Stakk<E> implements StakkIterable<E>{
private Node forste;
public Stakk(){
forste = new Node(null);
}
public void push(E data){
Node ny = new Node(data);
ny.neste = forste.neste;
forste.neste = ny;
}
public E top(){
if(forste.neste == null){
return null;
}
return forste.neste.data;
}
public E pop(){
if(forste.neste == null){
return null;
}
Node tmp = forste.neste;
forste.neste = forste.neste.neste;
return tmp.data;
}
public Iterator<E> iterator(){
return new StakkIterator();
}
private class StakkIterator implements Iterator<E>{
Node denne;
Node forrige;
boolean kaltNext;
StakkIterator(){
denne = forste;
forrige = forste;
kaltNext = false;
}
public boolean hasNext(){
return denne.neste != null;
}
public E next(){
kaltNext = true;
if(denne != forste){
forrige = denne;
}
denne = denne.neste;
return denne.data;
}
public void remove(){
if(kaltNext){
forrige.neste = denne.neste;
kaltNext = false;
}else{
throw new IllegalStateException();
}
}
}
private class Node{
Node neste;
E data;
Node(E e){
data = e;
}
}
}
| gpl-2.0 |
technomancers/2017SteamWorks | src/main/java/org/usfirst/frc/team1758/robot/commands/groups/HardAutoLeft.java | 521 | package org.usfirst.frc.team1758.robot.commands.groups;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc.team1758.robot.commands.MoveBack;
import org.usfirst.frc.team1758.robot.commands.TurnOnLight;
import org.usfirst.frc.team1758.robot.commands.TurnRight;
public class HardAutoLeft extends CommandGroup {
public HardAutoLeft() {
addSequential(new TurnOnLight());
addSequential(new MoveBack(8000));
addSequential(new TurnRight(30));
addSequential(new MoveBack(9931));
}
}
| gpl-2.0 |
Eli-SP/BetterThrowers | LoginApp/app/src/main/java/com/example/eli/loginapp/EntryDataBaseAdapter.java | 3699 | package com.example.eli.loginapp;
/**
* Created by Eli on 1/18/2015.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class EntryDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
static final String DATABASE_CREATE = "create table "+"ENTRY"+"( "+"ID"+" integer primary key autoincrement, "+ "GAMEID integer, HITS integer, MISSES integer, FOREIGN KEY(GAMEID) REFERENCES GAMES(ID)); ";
public SQLiteDatabase db;
private final Context context;
private DataBaseHelper dbHelper;
public EntryDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public EntryDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(int gameID, int hits, int misses)
{
db = dbHelper.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put("GAMEID", gameID);
newValues.put("HITS", hits);
newValues.put("MISSES", misses);
db.insert("ENTRY", null, newValues);
this.close();
}
public int deleteEntry(String id)
{
db = dbHelper.getWritableDatabase();
String where = "ID=?";
int x = db.delete("ENTRY", where, new String[]{id});
db.close();
return x;
}
public Cursor getEntry(int EntryNumber)
{
db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM ENTRY WHERE GAMEID=?", new String[]{String.valueOf(EntryNumber)});
if(cursor.getCount()<1)
{
cursor.close();
return null;
}
db.close();
return cursor;
}
public Cursor getEntries()
{
db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM ENTRY", null);
if(cursor.getCount()<1)
{
cursor.close();
return null;
}
db.close();
return cursor;
}
/*public int getHits()
{
Cursor cursor = db.query("ENTRY", null, " HITS=?", new String[]{gameName}, null, null, null);
if(cursor.getCount()<1)
{
cursor.close();
return -1;
}
cursor.moveToFirst();
String playername = cursor.getString(cursor.getColumnIndex("PLAYERNAME"));
cursor.close();
return playername;
}*/
/*public int getHits()
{
Cursor cursor = db.query("ENTRY", null, " GAMENAME=?", new String[]{gameName}, null, null, null);
if(cursor.getCount()<1)
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String playername = cursor.getString(cursor.getColumnIndex("PLAYERNAME"));
cursor.close();
return playername;
}*/
public void updateEntry(String gameName, int playerID)
{
db = dbHelper.getWritableDatabase();
ContentValues updatedValues = new ContentValues();
updatedValues.put("GAMENAME", gameName);
updatedValues.put("PLAYERNAME", playerID);
String where = "GAMENAME = ?";
db.update("GAMES", updatedValues, where, new String[]{gameName});
db.close();
}
} | gpl-2.0 |
course-design/test | app/src/main/java/com/kezhenxu/wechat6/Main.java | 1022 | package com.kezhenxu.wechat6;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.kezhenxu.study.activity00.R;
public class Main extends Activity {
@Override
protected void onCreate ( Bundle savedInstanceState ) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.main );
}
@Override
public boolean onCreateOptionsMenu ( Menu menu ) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater ().inflate ( R.menu.main, menu );
return true;
}
@Override
public boolean onOptionsItemSelected ( MenuItem item ) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId ();
//noinspection SimplifiableIfStatement
if ( id == R.id.action_group_chat ) {
return true;
}
return super.onOptionsItemSelected ( item );
}
}
| gpl-2.0 |
teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/WebCore/bindings/java/dom3/java/com/sun/webkit/dom/HTMLBaseFontElementImpl.java | 2404 | /*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.webkit.dom;
import org.w3c.dom.html.HTMLBaseFontElement;
public class HTMLBaseFontElementImpl extends HTMLElementImpl implements HTMLBaseFontElement {
HTMLBaseFontElementImpl(long peer) {
super(peer);
}
static HTMLBaseFontElement getImpl(long peer) {
return (HTMLBaseFontElement)create(peer);
}
// Attributes
public String getColor() {
return getColorImpl(getPeer());
}
native static String getColorImpl(long peer);
public void setColor(String value) {
setColorImpl(getPeer(), value);
}
native static void setColorImpl(long peer, String value);
public String getFace() {
return getFaceImpl(getPeer());
}
native static String getFaceImpl(long peer);
public void setFace(String value) {
setFaceImpl(getPeer(), value);
}
native static void setFaceImpl(long peer, String value);
public String getSize() {
return getSizeImpl(getPeer())+"";
}
native static String getSizeImpl(long peer);
public void setSize(String value) {
setSizeImpl(getPeer(), value);
}
native static void setSizeImpl(long peer, String value);
}
| gpl-2.0 |
TheLQ/ps3mediaserver | src/main/java/net/pms/network/HTTPServer.java | 7398 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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 2
* of the License only.
*
* 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 net.pms.network;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import org.apache.commons.lang.StringUtils;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.Executors;
public class HTTPServer implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(HTTPServer.class);
private final int port;
private String hostName;
private ServerSocketChannel serverSocketChannel;
private ServerSocket serverSocket;
private boolean stop;
private Thread runnable;
private InetAddress iafinal = null;
private ChannelFactory factory;
private Channel channel;
private NetworkInterface ni = null;
private ChannelGroup group;
public InetAddress getIafinal() {
return iafinal;
}
public NetworkInterface getNi() {
return ni;
}
public HTTPServer(int port) {
this.port = port;
}
public boolean start() throws IOException {
final PmsConfiguration configuration = PMS.getConfiguration();
hostName = configuration.getServerHostname();
InetSocketAddress address = null;
if (hostName != null && hostName.length() > 0) {
logger.info("Using forced address " + hostName);
InetAddress tempIA = InetAddress.getByName(hostName);
if (tempIA != null && ni != null && ni.equals(NetworkInterface.getByInetAddress(tempIA))) {
address = new InetSocketAddress(tempIA, port);
} else {
address = new InetSocketAddress(hostName, port);
}
} else if (isAddressFromInterfaceFound(configuration.getNetworkInterface())) {
logger.info("Using address " + iafinal + " found on network interface: " + ni.toString().trim().replace('\n', ' '));
address = new InetSocketAddress(iafinal, port);
} else {
logger.info("Using localhost address");
address = new InetSocketAddress(port);
}
logger.info("Created socket: " + address);
if (!configuration.isHTTPEngineV2()) {
serverSocketChannel = ServerSocketChannel.open();
serverSocket = serverSocketChannel.socket();
serverSocket.setReuseAddress(true);
serverSocket.bind(address);
if (hostName == null && iafinal != null) {
hostName = iafinal.getHostAddress();
} else if (hostName == null) {
hostName = InetAddress.getLocalHost().getHostAddress();
}
runnable = new Thread(this, "HTTP Server");
runnable.setDaemon(false);
runnable.start();
} else {
group = new DefaultChannelGroup("myServer");
factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()
);
ServerBootstrap bootstrap = new ServerBootstrap(factory);
HttpServerPipelineFactory pipeline = new HttpServerPipelineFactory(group);
bootstrap.setPipelineFactory(pipeline);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.setOption("reuseAddress", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.setOption("child.sendBufferSize", 65536);
bootstrap.setOption("child.receiveBufferSize", 65536);
channel = bootstrap.bind(address);
group.add(channel);
if (hostName == null && iafinal != null) {
hostName = iafinal.getHostAddress();
} else if (hostName == null) {
hostName = InetAddress.getLocalHost().getHostAddress();
}
}
return true;
}
private boolean isAddressFromInterfaceFound(String networkInterfaceName) {
NetworkConfiguration.InterfaceAssociation ia = !StringUtils.isEmpty(networkInterfaceName) ? NetworkConfiguration.getInstance()
.getAddressForNetworkInterfaceName(networkInterfaceName)
: null;
if (ia == null) {
ia = NetworkConfiguration.getInstance().getDefaultNetworkInterfaceAddress();
}
if (ia != null) {
iafinal = ia.getAddr();
ni = ia.getIface();
}
return ia != null;
}
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=10689&p=48811#p48811
//
// avoid a NPE when a) switching HTTP Engine versions and b) restarting the HTTP server
// by cleaning up based on what's in use (not null) rather than the config state, which
// might be inconsistent.
//
// NOTE: there's little in the way of cleanup to do here as PMS.reset() discards the old
// server and creates a new one
public void stop() {
logger.info("Stopping server on host " + hostName + " and port " + port + "...");
if (runnable != null) { // HTTP Engine V1
runnable.interrupt();
}
if (serverSocket != null) { // HTTP Engine V1
try {
serverSocket.close();
serverSocketChannel.close();
} catch (IOException e) {
logger.debug("Caught exception", e);
}
} else if (channel != null) { // HTTP Engine V2
if (group != null) {
group.close().awaitUninterruptibly();
}
if (factory != null) {
factory.releaseExternalResources();
}
}
NetworkConfiguration.forgetConfiguration();
}
public void run() {
logger.info("Starting DLNA Server on host " + hostName + " and port " + port + "...");
while (!stop) {
try {
Socket socket = serverSocket.accept();
InetAddress inetAddress = socket.getInetAddress();
String ip = inetAddress.getHostAddress();
// basic ipfilter: solntcev at gmail dot com
boolean ignore = false;
if (!PMS.getConfiguration().getIpFiltering().allowed(inetAddress)) {
ignore = true;
socket.close();
logger.trace("Ignoring request from: " + ip);
} else {
logger.trace("Receiving a request from: " + ip);
}
if (!ignore) {
RequestHandler request = new RequestHandler(socket);
Thread thread = new Thread(request, "Request Handler");
thread.start();
}
} catch (ClosedByInterruptException e) {
stop = true;
} catch (IOException e) {
logger.debug("Caught exception", e);
} finally {
try {
if (stop && serverSocket != null) {
serverSocket.close();
}
if (stop && serverSocketChannel != null) {
serverSocketChannel.close();
}
} catch (IOException e) {
logger.debug("Caught exception", e);
}
}
}
}
public String getURL() {
return "http://" + hostName + ":" + port;
}
public String getHost() {
return hostName;
}
public int getPort() {
return port;
}
}
| gpl-2.0 |
andybalaam/freeguide | src/freeguide/plugins/program/freeguide/wizard/BooleanWizardPanel.java | 2693 | /*
* FreeGuide J2
*
* Copyright (c) 2001-2004 by Andy Balaam and the FreeGuide contributors
*
* freeguide-tv.sourceforge.net
*
* Released under the GNU General Public License
* with ABSOLUTELY NO WARRANTY.
*
* See the file COPYING for more information.
*/
package freeguide.plugins.program.freeguide.wizard;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* A JPanel to go on a FreeGuideWizard to choose a boolean option with a
* checkbox.
*
* @author Andy Balaam
* @version 1
*/
public class BooleanWizardPanel extends WizardPanel
{
// -------------------------------------------
private JCheckBox checkbox;
/**
* Constructor for the BooleanWizardPanel object
*/
BooleanWizardPanel( )
{
super( );
}
/**
* Construct the GUI of this Wizard Panel.
*/
public void construct( )
{
java.awt.GridBagConstraints gridBagConstraints;
JPanel midPanel = new JPanel( );
JLabel topLabel = new JLabel( );
JLabel bottomLabel = new JLabel( );
checkbox = new JCheckBox( );
setLayout( new java.awt.GridLayout( 3, 0 ) );
topLabel.setFont( new java.awt.Font( "Dialog", 0, 12 ) );
topLabel.setHorizontalAlignment( javax.swing.SwingConstants.CENTER );
add( topLabel );
midPanel.setLayout( new java.awt.GridBagLayout( ) );
checkbox.setText( topMessage );
checkbox.setMnemonic( topMnemonic );
gridBagConstraints = new java.awt.GridBagConstraints( );
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 0.9;
gridBagConstraints.insets = new java.awt.Insets( 5, 5, 5, 5 );
midPanel.add( checkbox, gridBagConstraints );
add( midPanel );
bottomLabel.setFont( new java.awt.Font( "Dialog", 0, 12 ) );
bottomLabel.setHorizontalAlignment( javax.swing.SwingConstants.CENTER );
bottomLabel.setText( bottomMessage );
add( bottomLabel );
}
/**
* Gets the boxValue attribute of the BooleanWizardPanel object
*
* @return The boxValue value
*/
protected Object getBoxValue( )
{
return new Boolean( checkbox.isSelected( ) );
}
/**
* Sets the boxValue attribute of the BooleanWizardPanel object
*
* @param val The new boxValue value
*/
protected void setBoxValue( Object val )
{
checkbox.setSelected( ( (Boolean)val ).booleanValue( ) );
}
// The checkbox for the choice
}
| gpl-2.0 |
hackcraft-sk/swarm | utils/src/sk/hackcraft/als/utils/Config.java | 2786 | package sk.hackcraft.als.utils;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* Interface representing configuration, divided by sections containing key
* value pairs.
*/
public interface Config {
/**
* Check section availability.
*
* @param section name of section
* @return true if section exists, false otherwise
*/
boolean hasSection(String section);
/**
* Returns section.
*
* @param section name of section
* @return requested section
* @throws NoSuchElementException if section doesn't exists
*/
Section getSection(String section);
/**
* Returns all sections.
*
* @return all sections
*/
Set<? extends Section> getAllSections();
/**
* Interface representing configuration section.
*/
interface Section {
/**
* Gets section name.
*
* @return section name
*/
String getName();
/**
* Check if section contains pair with specified key.
*
* @param key specified key
* @return true if section contains pair with specified key, false
* otherwise
*/
boolean hasPair(String key);
/**
* Gets specified pair.
*
* @param key pair key
* @return specified pair
*/
Pair getPair(String key);
/**
* Returns all pairs.
*
* @return all pairs
*/
Set<? extends Pair> getAllPairs();
}
/**
* Interface representing configuration key value pair.
*/
interface Pair {
/**
* Gets pair key.
*
* @return pair key
*/
String getKey();
/**
* Gets pair value as string.
*
* @return value as string
*/
String getStringValue();
/**
* Gets pair value as array of strings. Delimiter for parsing value is
* ','. Whitespaces before and after each value are trimmed.
*
* @return value as array of strings
*/
String[] getStringValueAsArray();
/**
* Gets pair value as int.
*
* @return value as int
* @throws NumberFormatException if it's not possible to convert value to int
*/
int getIntValue();
/**
* Gets pair value as boolean
*
* @return value as boolean
*/
boolean getBooleanValue();
/**
* Gets pair value as double.
*
* @return value as double
* @throws NumberFormatException if it's not possible to convert value to double
*/
double getDoubleValue();
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/javax/swing/plaf/metal/MetalInternalFrameTitlePane.java | 20539 | /*
* Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.swing.plaf.metal;
import sun.swing.SwingUtilities2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.InternalFrameEvent;
import java.util.EventListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
/**
* Class that manages a JLF title bar
* @author Steve Wilson
* @author Brian Beck
* @since 1.3
*/
public class MetalInternalFrameTitlePane extends BasicInternalFrameTitlePane {
protected boolean isPalette = false;
protected Icon paletteCloseIcon;
protected int paletteTitleHeight;
private static final Border handyEmptyBorder = new EmptyBorder(0,0,0,0);
/**
* Key used to lookup Color from UIManager. If this is null,
* <code>getWindowTitleBackground</code> is used.
*/
private String selectedBackgroundKey;
/**
* Key used to lookup Color from UIManager. If this is null,
* <code>getWindowTitleForeground</code> is used.
*/
private String selectedForegroundKey;
/**
* Key used to lookup shadow color from UIManager. If this is null,
* <code>getPrimaryControlDarkShadow</code> is used.
*/
private String selectedShadowKey;
/**
* Boolean indicating the state of the <code>JInternalFrame</code>s
* closable property at <code>updateUI</code> time.
*/
private boolean wasClosable;
int buttonsWidth = 0;
MetalBumps activeBumps
= new MetalBumps( 0, 0,
MetalLookAndFeel.getPrimaryControlHighlight(),
MetalLookAndFeel.getPrimaryControlDarkShadow(),
(UIManager.get("InternalFrame.activeTitleGradient") != null) ? null :
MetalLookAndFeel.getPrimaryControl() );
MetalBumps inactiveBumps
= new MetalBumps( 0, 0,
MetalLookAndFeel.getControlHighlight(),
MetalLookAndFeel.getControlDarkShadow(),
(UIManager.get("InternalFrame.inactiveTitleGradient") != null) ? null :
MetalLookAndFeel.getControl() );
MetalBumps paletteBumps;
private Color activeBumpsHighlight = MetalLookAndFeel.
getPrimaryControlHighlight();
private Color activeBumpsShadow = MetalLookAndFeel.
getPrimaryControlDarkShadow();
public MetalInternalFrameTitlePane(JInternalFrame f) {
super( f );
}
public void addNotify() {
super.addNotify();
// This is done here instead of in installDefaults as I was worried
// that the BasicInternalFrameUI might not be fully initialized, and
// that if this resets the closable state the BasicInternalFrameUI
// Listeners that get notified might be in an odd/uninitialized state.
updateOptionPaneState();
}
protected void installDefaults() {
super.installDefaults();
setFont( UIManager.getFont("InternalFrame.titleFont") );
paletteTitleHeight
= UIManager.getInt("InternalFrame.paletteTitleHeight");
paletteCloseIcon = UIManager.getIcon("InternalFrame.paletteCloseIcon");
wasClosable = frame.isClosable();
selectedForegroundKey = selectedBackgroundKey = null;
if (MetalLookAndFeel.usingOcean()) {
setOpaque(true);
}
}
protected void uninstallDefaults() {
super.uninstallDefaults();
if (wasClosable != frame.isClosable()) {
frame.setClosable(wasClosable);
}
}
protected void createButtons() {
super.createButtons();
Boolean paintActive = frame.isSelected() ? Boolean.TRUE:Boolean.FALSE;
iconButton.putClientProperty("paintActive", paintActive);
iconButton.setBorder(handyEmptyBorder);
maxButton.putClientProperty("paintActive", paintActive);
maxButton.setBorder(handyEmptyBorder);
closeButton.putClientProperty("paintActive", paintActive);
closeButton.setBorder(handyEmptyBorder);
// The palette close icon isn't opaque while the regular close icon is.
// This makes sure palette close buttons have the right background.
closeButton.setBackground(MetalLookAndFeel.getPrimaryControlShadow());
if (MetalLookAndFeel.usingOcean()) {
iconButton.setContentAreaFilled(false);
maxButton.setContentAreaFilled(false);
closeButton.setContentAreaFilled(false);
}
}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*/
protected void assembleSystemMenu() {}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*/
protected void addSystemMenuItems(JMenu systemMenu) {}
/**
* Override the parent's method to do nothing. Metal frames do not
* have system menus.
*/
protected void showSystemMenu() {}
/**
* Override the parent's method avoid creating a menu bar. Metal frames
* do not have system menus.
*/
protected void addSubComponents() {
add(iconButton);
add(maxButton);
add(closeButton);
}
protected PropertyChangeListener createPropertyChangeListener() {
return new MetalPropertyChangeHandler();
}
protected LayoutManager createLayout() {
return new MetalTitlePaneLayout();
}
class MetalPropertyChangeHandler
extends BasicInternalFrameTitlePane.PropertyChangeHandler
{
public void propertyChange(PropertyChangeEvent evt) {
String prop = evt.getPropertyName();
if( prop.equals(JInternalFrame.IS_SELECTED_PROPERTY) ) {
Boolean b = (Boolean)evt.getNewValue();
iconButton.putClientProperty("paintActive", b);
closeButton.putClientProperty("paintActive", b);
maxButton.putClientProperty("paintActive", b);
}
else if ("JInternalFrame.messageType".equals(prop)) {
updateOptionPaneState();
frame.repaint();
}
super.propertyChange(evt);
}
}
class MetalTitlePaneLayout extends TitlePaneLayout {
public void addLayoutComponent(String name, Component c) {}
public void removeLayoutComponent(Component c) {}
public Dimension preferredLayoutSize(Container c) {
return minimumLayoutSize(c);
}
public Dimension minimumLayoutSize(Container c) {
// Compute width.
int width = 30;
if (frame.isClosable()) {
width += 21;
}
if (frame.isMaximizable()) {
width += 16 + (frame.isClosable() ? 10 : 4);
}
if (frame.isIconifiable()) {
width += 16 + (frame.isMaximizable() ? 2 :
(frame.isClosable() ? 10 : 4));
}
FontMetrics fm = frame.getFontMetrics(getFont());
String frameTitle = frame.getTitle();
int title_w = frameTitle != null ? SwingUtilities2.stringWidth(
frame, fm, frameTitle) : 0;
int title_length = frameTitle != null ? frameTitle.length() : 0;
if (title_length > 2) {
int subtitle_w = SwingUtilities2.stringWidth(frame, fm,
frame.getTitle().substring(0, 2) + "...");
width += (title_w < subtitle_w) ? title_w : subtitle_w;
}
else {
width += title_w;
}
// Compute height.
int height;
if (isPalette) {
height = paletteTitleHeight;
} else {
int fontHeight = fm.getHeight();
fontHeight += 7;
Icon icon = frame.getFrameIcon();
int iconHeight = 0;
if (icon != null) {
// SystemMenuBar forces the icon to be 16x16 or less.
iconHeight = Math.min(icon.getIconHeight(), 16);
}
iconHeight += 5;
height = Math.max(fontHeight, iconHeight);
}
return new Dimension(width, height);
}
public void layoutContainer(Container c) {
boolean leftToRight = MetalUtils.isLeftToRight(frame);
int w = getWidth();
int x = leftToRight ? w : 0;
int y = 2;
int spacing;
// assumes all buttons have the same dimensions
// these dimensions include the borders
int buttonHeight = closeButton.getIcon().getIconHeight();
int buttonWidth = closeButton.getIcon().getIconWidth();
if(frame.isClosable()) {
if (isPalette) {
spacing = 3;
x += leftToRight ? -spacing -(buttonWidth+2) : spacing;
closeButton.setBounds(x, y, buttonWidth+2, getHeight()-4);
if( !leftToRight ) x += (buttonWidth+2);
} else {
spacing = 4;
x += leftToRight ? -spacing -buttonWidth : spacing;
closeButton.setBounds(x, y, buttonWidth, buttonHeight);
if( !leftToRight ) x += buttonWidth;
}
}
if(frame.isMaximizable() && !isPalette ) {
spacing = frame.isClosable() ? 10 : 4;
x += leftToRight ? -spacing -buttonWidth : spacing;
maxButton.setBounds(x, y, buttonWidth, buttonHeight);
if( !leftToRight ) x += buttonWidth;
}
if(frame.isIconifiable() && !isPalette ) {
spacing = frame.isMaximizable() ? 2
: (frame.isClosable() ? 10 : 4);
x += leftToRight ? -spacing -buttonWidth : spacing;
iconButton.setBounds(x, y, buttonWidth, buttonHeight);
if( !leftToRight ) x += buttonWidth;
}
buttonsWidth = leftToRight ? w - x : x;
}
}
public void paintPalette(Graphics g) {
boolean leftToRight = MetalUtils.isLeftToRight(frame);
int width = getWidth();
int height = getHeight();
if (paletteBumps == null) {
paletteBumps
= new MetalBumps(0, 0,
MetalLookAndFeel.getPrimaryControlHighlight(),
MetalLookAndFeel.getPrimaryControlInfo(),
MetalLookAndFeel.getPrimaryControlShadow() );
}
Color background = MetalLookAndFeel.getPrimaryControlShadow();
Color darkShadow = MetalLookAndFeel.getPrimaryControlDarkShadow();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor( darkShadow );
g.drawLine ( 0, height - 1, width, height -1);
int xOffset = leftToRight ? 4 : buttonsWidth + 4;
int bumpLength = width - buttonsWidth -2*4;
int bumpHeight = getHeight() - 4;
paletteBumps.setBumpArea( bumpLength, bumpHeight );
paletteBumps.paintIcon( this, g, xOffset, 2);
}
public void paintComponent(Graphics g) {
if(isPalette) {
paintPalette(g);
return;
}
boolean leftToRight = MetalUtils.isLeftToRight(frame);
boolean isSelected = frame.isSelected();
int width = getWidth();
int height = getHeight();
Color background = null;
Color foreground = null;
Color shadow = null;
MetalBumps bumps;
String gradientKey;
if (isSelected) {
if (!MetalLookAndFeel.usingOcean()) {
closeButton.setContentAreaFilled(true);
maxButton.setContentAreaFilled(true);
iconButton.setContentAreaFilled(true);
}
if (selectedBackgroundKey != null) {
background = UIManager.getColor(selectedBackgroundKey);
}
if (background == null) {
background = MetalLookAndFeel.getWindowTitleBackground();
}
if (selectedForegroundKey != null) {
foreground = UIManager.getColor(selectedForegroundKey);
}
if (selectedShadowKey != null) {
shadow = UIManager.getColor(selectedShadowKey);
}
if (shadow == null) {
shadow = MetalLookAndFeel.getPrimaryControlDarkShadow();
}
if (foreground == null) {
foreground = MetalLookAndFeel.getWindowTitleForeground();
}
activeBumps.setBumpColors(activeBumpsHighlight, activeBumpsShadow,
UIManager.get("InternalFrame.activeTitleGradient") !=
null ? null : background);
bumps = activeBumps;
gradientKey = "InternalFrame.activeTitleGradient";
} else {
if (!MetalLookAndFeel.usingOcean()) {
closeButton.setContentAreaFilled(false);
maxButton.setContentAreaFilled(false);
iconButton.setContentAreaFilled(false);
}
background = MetalLookAndFeel.getWindowTitleInactiveBackground();
foreground = MetalLookAndFeel.getWindowTitleInactiveForeground();
shadow = MetalLookAndFeel.getControlDarkShadow();
bumps = inactiveBumps;
gradientKey = "InternalFrame.inactiveTitleGradient";
}
if (!MetalUtils.drawGradient(this, g, gradientKey, 0, 0, width,
height, true)) {
g.setColor(background);
g.fillRect(0, 0, width, height);
}
g.setColor( shadow );
g.drawLine ( 0, height - 1, width, height -1);
g.drawLine ( 0, 0, 0 ,0);
g.drawLine ( width - 1, 0 , width -1, 0);
int titleLength;
int xOffset = leftToRight ? 5 : width - 5;
String frameTitle = frame.getTitle();
Icon icon = frame.getFrameIcon();
if ( icon != null ) {
if( !leftToRight )
xOffset -= icon.getIconWidth();
int iconY = ((height / 2) - (icon.getIconHeight() /2));
icon.paintIcon(frame, g, xOffset, iconY);
xOffset += leftToRight ? icon.getIconWidth() + 5 : -5;
}
if(frameTitle != null) {
Font f = getFont();
g.setFont(f);
FontMetrics fm = SwingUtilities2.getFontMetrics(frame, g, f);
int fHeight = fm.getHeight();
g.setColor(foreground);
int yOffset = ( (height - fm.getHeight() ) / 2 ) + fm.getAscent();
Rectangle rect = new Rectangle(0, 0, 0, 0);
if (frame.isIconifiable()) { rect = iconButton.getBounds(); }
else if (frame.isMaximizable()) { rect = maxButton.getBounds(); }
else if (frame.isClosable()) { rect = closeButton.getBounds(); }
int titleW;
if( leftToRight ) {
if (rect.x == 0) {
rect.x = frame.getWidth()-frame.getInsets().right-2;
}
titleW = rect.x - xOffset - 4;
frameTitle = getTitle(frameTitle, fm, titleW);
} else {
titleW = xOffset - rect.x - rect.width - 4;
frameTitle = getTitle(frameTitle, fm, titleW);
xOffset -= SwingUtilities2.stringWidth(frame, fm, frameTitle);
}
titleLength = SwingUtilities2.stringWidth(frame, fm, frameTitle);
SwingUtilities2.drawString(frame, g, frameTitle, xOffset, yOffset);
xOffset += leftToRight ? titleLength + 5 : -5;
}
int bumpXOffset;
int bumpLength;
if( leftToRight ) {
bumpLength = width - buttonsWidth - xOffset - 5;
bumpXOffset = xOffset;
} else {
bumpLength = xOffset - buttonsWidth - 5;
bumpXOffset = buttonsWidth + 5;
}
int bumpYOffset = 3;
int bumpHeight = getHeight() - (2 * bumpYOffset);
bumps.setBumpArea( bumpLength, bumpHeight );
bumps.paintIcon(this, g, bumpXOffset, bumpYOffset);
}
public void setPalette(boolean b) {
isPalette = b;
if (isPalette) {
closeButton.setIcon(paletteCloseIcon);
if( frame.isMaximizable() )
remove(maxButton);
if( frame.isIconifiable() )
remove(iconButton);
} else {
closeButton.setIcon(closeIcon);
if( frame.isMaximizable() )
add(maxButton);
if( frame.isIconifiable() )
add(iconButton);
}
revalidate();
repaint();
}
/**
* Updates any state dependant upon the JInternalFrame being shown in
* a <code>JOptionPane</code>.
*/
private void updateOptionPaneState() {
int type = -2;
boolean closable = wasClosable;
Object obj = frame.getClientProperty("JInternalFrame.messageType");
if (obj == null) {
// Don't change the closable state unless in an JOptionPane.
return;
}
if (obj instanceof Integer) {
type = ((Integer) obj).intValue();
}
switch (type) {
case JOptionPane.ERROR_MESSAGE:
selectedBackgroundKey =
"OptionPane.errorDialog.titlePane.background";
selectedForegroundKey =
"OptionPane.errorDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.errorDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.QUESTION_MESSAGE:
selectedBackgroundKey =
"OptionPane.questionDialog.titlePane.background";
selectedForegroundKey =
"OptionPane.questionDialog.titlePane.foreground";
selectedShadowKey =
"OptionPane.questionDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.WARNING_MESSAGE:
selectedBackgroundKey =
"OptionPane.warningDialog.titlePane.background";
selectedForegroundKey =
"OptionPane.warningDialog.titlePane.foreground";
selectedShadowKey = "OptionPane.warningDialog.titlePane.shadow";
closable = false;
break;
case JOptionPane.INFORMATION_MESSAGE:
case JOptionPane.PLAIN_MESSAGE:
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey =
null;
closable = false;
break;
default:
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey =
null;
break;
}
if (closable != frame.isClosable()) {
frame.setClosable(closable);
}
}
}
| gpl-2.0 |
piaolinzhi/fight | dubbo/pay/pay-common/src/main/java/wusc/edu/pay/common/utils/export/ExportDataSource.java | 208 | package wusc.edu.pay.common.utils.export;
import java.util.List;
/**
* 描述: 数据导出,数据源
* @author Hill
*
*/
public interface ExportDataSource<T>{
<T> List<T> getData();
}
| gpl-2.0 |
ubjelly/DCU | src/org/dcu/net/CallbackListener.java | 174 | package org.dcu.net;
/**
* Interface for http callback.
* @author Brendan Dodd
*/
public interface CallbackListener {
public void onComplete(String jsonResponse);
}
| gpl-2.0 |
prajdheeraj/CS557Project | Code/ivy/src/IvyBindListener.java | 883 | /**
* this interface specifies the methods of a BindListener; it is only useful if you want
* to develop a bus monitor (Ivy Probe, spy, ivymon)
*
* @author Yannick Jestin
* @author <a href="http://www.tls.cena.fr/products/ivy/">http://www.tls.cena.fr/products/ivy/</a>
*
* Changelog:
* 1.2.8
* - removed the public abstract modifiers, which are redundant
*/
package fr.dgac.ivy;
public interface IvyBindListener extends java.util.EventListener {
/**
* invoked when a Ivy Client performs a bind
* @param client the peer
* @param id the regexp ID
* @param regexp the regexp
*/
void bindPerformed(IvyClient client,int id, String regexp);
/**
* invoked when a Ivy Client performs a unbind
* @param client the peer
* @param id the regexp ID
* @param regexp the regexp
*/
void unbindPerformed(IvyClient client,int id,String regexp);
}
| gpl-2.0 |
SeekingFor/jfniki | alien/src/gnu/inet/nntp/Newsrc.java | 2823 | /*
* Newsrc.java
* Copyright (C) 2002 The Free Software Foundation
*
* This file is part of GNU inetlib, a library.
*
* GNU inetlib 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.
*
* GNU inetlib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obliged to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package gnu.inet.nntp;
import java.util.Iterator;
/**
* Interface for a .newsrc configuration.
*
* @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
*/
public interface Newsrc
{
/**
* Returns an iterator over the names of the subscribed newsgroups.
* Each item returned is a String.
*/
public Iterator list();
/**
* Indicates whether a newsgroup is subscribed in this newsrc.
*/
public boolean isSubscribed(String newsgroup);
/**
* Sets whether a newsgroup is subscribed in this newsrc.
*/
public void setSubscribed(String newsgroup, boolean subs);
/**
* Indicates whether an article is marked as seen in the specified newsgroup.
*/
public boolean isSeen(String newsgroup, int article);
/**
* Sets whether an article is marked as seen in the specified newsgroup.
*/
public void setSeen(String newsgroup, int article, boolean seen);
/**
* Closes the configuration, potentially saving any changes.
*/
public void close();
}
| gpl-2.0 |
w7cook/batch-javac | src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/LayoutParser.java | 4026 | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.internal.toolkit.builders;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;
import java.io.*;
import java.util.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.*;
/**
* Parse the XML that specified the order of operation for the builders. This
* Parser uses SAX parsing.
*
* @author Jamie Ho
* @since 1.5
* @see SAXParser
*/
public class LayoutParser extends DefaultHandler {
/**
* The map of XML elements that have been parsed.
*/
private Map<String, XMLNode> xmlElementsMap;
private XMLNode currentNode;
private Configuration configuration;
private static LayoutParser instance;
private String currentRoot;
private boolean isParsing;
/**
* This class is a singleton.
*/
private LayoutParser(Configuration configuration) {
xmlElementsMap = new HashMap<String, XMLNode>();
this.configuration = configuration;
}
/**
* Return an instance of the BuilderXML.
*
* @param configuration
* the current configuration of the doclet.
* @return an instance of the BuilderXML.
*/
public static LayoutParser getInstance(Configuration configuration) {
if (instance == null) {
instance = new LayoutParser(configuration);
}
return instance;
}
/**
* Parse the XML specifying the layout of the documentation.
*
* @return the list of XML elements parsed.
*/
public XMLNode parseXML(String root) {
if (xmlElementsMap.containsKey(root)) {
return xmlElementsMap.get(root);
}
try {
currentRoot = root;
isParsing = false;
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
InputStream in = configuration.getBuilderXML();
saxParser.parse(in, this);
return xmlElementsMap.get(root);
} catch (Throwable t) {
t.printStackTrace();
throw new DocletAbortException();
}
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(String namespaceURI, String sName, String qName,
Attributes attrs) throws SAXException {
if (isParsing || qName.equals(currentRoot)) {
isParsing = true;
currentNode = new XMLNode(currentNode, qName);
for (int i = 0; i < attrs.getLength(); i++)
currentNode.attrs.put(attrs.getLocalName(i), attrs.getValue(i));
if (qName.equals(currentRoot))
xmlElementsMap.put(qName, currentNode);
}
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(String namespaceURI, String sName, String qName)
throws SAXException {
if (!isParsing) {
return;
}
currentNode = currentNode.parent;
isParsing = !qName.equals(currentRoot);
}
}
| gpl-2.0 |
ow2-proactive/catalog | src/main/java/org/ow2/proactive/catalog/service/exception/LostOfAdminGrantRightException.java | 1459 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.catalog.service.exception;
import org.ow2.proactive.microservices.common.exception.ClientException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.FORBIDDEN)
public class LostOfAdminGrantRightException extends ClientException {
public LostOfAdminGrantRightException(String message) {
super(message);
}
}
| agpl-3.0 |
CecileBONIN/Silverpeas-Core | ejb-core/node/src/main/java/com/silverpeas/subscribe/util/SubscriptionUtil.java | 4152 | /*
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.subscribe.util;
import com.silverpeas.subscribe.SubscriptionSubscriber;
import com.silverpeas.subscribe.constant.SubscriberType;
import com.silverpeas.util.MapUtil;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
/**
* User: Yohann Chastagnier
* Date: 28/02/13
*/
public class SubscriptionUtil {
/**
* Adding containerToAdd into finalContainer.
* @param finalContainer
* @param containerToAdd
*/
public static void mergeIndexedSubscriberIdsByType(
Map<SubscriberType, Collection<String>> finalContainer,
Map<SubscriberType, Collection<String>> containerToAdd) {
if (finalContainer != null && containerToAdd != null) {
for (Map.Entry<SubscriberType, Collection<String>> entry : containerToAdd.entrySet()) {
if (entry.getValue() != null) {
Collection<String> subscriberIds = finalContainer.get(entry.getKey());
if (subscriberIds != null) {
subscriberIds.addAll(entry.getValue());
} else {
finalContainer.put(entry.getKey(), new LinkedHashSet<String>(entry.getValue()));
}
}
}
}
}
/**
* Indexes given subscribers by their type.
* @param subscribers
* @return a map which has type of subscriber as a key and the corresponding subscriber ids of
* type of subscriber as a value
*/
public static Map<SubscriberType, Collection<String>> indexSubscriberIdsByType(
Collection<SubscriptionSubscriber> subscribers) {
return indexSubscriberIdsByType(null, subscribers);
}
/**
* Indexes given subscribers by their type.
* @param existingSubscribers
* @param subscribers
* @return a map which has type of subscriber as a key and the corresponding subscriber ids of
* type of subscriber as a value
*/
public static Map<SubscriberType, Collection<String>> indexSubscriberIdsByType(
Map<SubscriberType, Collection<String>> existingSubscribers,
Collection<SubscriptionSubscriber> subscribers) {
// Initializing the result
Map<SubscriberType, Collection<String>> indexedSubscribers =
(existingSubscribers == null) ? new HashMap<SubscriberType, Collection<String>>() :
existingSubscribers;
// From given subscribers
if (subscribers != null) {
for (SubscriptionSubscriber subscriber : subscribers) {
MapUtil.putAdd(LinkedHashSet.class, indexedSubscribers, subscriber.getType(),
subscriber.getId());
}
}
// Initialize empty collections on subscriber type indexes that don't exist.
// It avoid to callers to take in account null collections.
for (SubscriberType subscriberType : SubscriberType.getValidValues()) {
if (!indexedSubscribers.containsKey(subscriberType)) {
indexedSubscribers.put(subscriberType, new LinkedHashSet<String>(0));
}
}
// Returning indexed subscribers
return indexedSubscribers;
}
}
| agpl-3.0 |
gnosygnu/xowa_android | _400_xowa/src/main/java/gplx/xowa/xtns/lst/Lst_section_nde_mgr.java | 399 | package gplx.xowa.xtns.lst; import gplx.*; import gplx.xowa.*; import gplx.xowa.xtns.*;
public class Lst_section_nde_mgr {
private final List_adp list = List_adp_.New();
public int Len() {return list.Count();}
public Lst_section_nde Get_at(int i) {return (Lst_section_nde)list.Get_at(i);}
public void Add(Lst_section_nde xnde) {list.Add(xnde);}
public void Clear() {list.Clear();}
}
| agpl-3.0 |
automenta/java_dann | src/syncleus/dann/math/counting/Counters.java | 20586 | /******************************************************************************
* *
* Copyright: (c) Syncleus, Inc. *
* *
* You may redistribute and modify this source code under the terms and *
* conditions of the Open Source Community License - Type C version 1.0 *
* or any later version as published by Syncleus, Inc. at www.syncleus.com. *
* There should be a copy of the license included with this file. If a copy *
* of the license is not included you are granted no right to distribute or *
* otherwise use this file except through a legal and valid license. You *
* should also contact Syncleus, Inc. at the information below if you cannot *
* find a license: *
* *
* Syncleus, Inc. *
* 2604 South 12th Street *
* Philadelphia, PA 19148 *
* *
******************************************************************************/
package syncleus.dann.math.counting;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public final class Counters {
/**
* This is an utility class, so it can not be instantiated. We ensure this
* by making the default constructor private.
*
* @throws InstantiationException
*/
private Counters() {
throw new IllegalStateException(
"This is an utility class, it can not be instantiated");
}
public static <O> BigInteger everyCombinationCount(
final Collection<O> superCollection) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for (int currentSequenceLength = 1; currentSequenceLength <= superCollection
.size(); currentSequenceLength++)
combinations = combinations.add(fixedLengthCombinationCount(
superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthCombinationCount(
final Collection<O> superCollection, final int length) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superCollection.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
final Counter generator = new CombinationCounter(
superCollection.size(), length);
return generator.getTotal();
}
public static <O> Set<List<O>> everyCombination(final List<O> superList) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
final Set<List<O>> combinations = new HashSet<>();
for (int currentSequenceLength = 1; currentSequenceLength <= superList
.size(); currentSequenceLength++)
combinations.addAll(fixedLengthCombinations(superList,
currentSequenceLength));
return Collections.unmodifiableSet(combinations);
}
public static <O> Set<Set<O>> everyCombination(final Set<O> superSet) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
final Set<Set<O>> combinations = new HashSet<>();
for (int currentSequenceLength = 1; currentSequenceLength <= superSet
.size(); currentSequenceLength++)
combinations.addAll(fixedLengthCombinations(superSet,
currentSequenceLength));
return Collections.unmodifiableSet(combinations);
}
public static <O> Set<List<O>> fixedLengthCombinations(
final List<O> superList, final int length) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superList.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
final Set<List<O>> combinations = new HashSet<>();
final Counter generator = new CombinationCounter(superList.size(),
length);
while (generator.hasMore()) {
final List<O> combination = new ArrayList<>();
final int[] combinationIndexes = generator.getNext();
for (final int combinationIndex : combinationIndexes)
combination.add(superList.get(combinationIndex));
combinations.add(Collections.unmodifiableList(combination));
}
return Collections.unmodifiableSet(combinations);
}
public static <O> Set<Set<O>> fixedLengthCombinations(
final Set<O> superSet, final int length) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superSet.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
final List<O> superSetList = new ArrayList<>(superSet);
final Set<Set<O>> combinations = new HashSet<>();
final Counter generator = new CombinationCounter(superSet.size(),
length);
while (generator.hasMore()) {
final Set<O> combination = new HashSet<>();
final int[] combinationIndexes = generator.getNext();
for (final int combinationIndex : combinationIndexes)
combination.add(superSetList.get(combinationIndex));
combinations.add(Collections.unmodifiableSet(combination));
}
return Collections.unmodifiableSet(combinations);
}
private static <O> Set<List<O>> sameLengthPermutations(
final List<O> superList) {
final Set<List<O>> permutations = new HashSet<>();
final Counter generator = new PermutationCounter(superList.size());
while (generator.hasMore()) {
final List<O> permutation = new ArrayList<>();
final int[] permutationIndexes = generator.getNext();
for (final int permutationIndex : permutationIndexes)
permutation.add(superList.get(permutationIndex));
permutations.add(Collections.unmodifiableList(permutation));
}
return Collections.unmodifiableSet(permutations);
}
public static <O> BigInteger everyPermutationCount(
final Collection<O> superCollection) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for (int currentSequenceLength = 1; currentSequenceLength <= superCollection
.size(); currentSequenceLength++)
combinations = combinations.add(fixedLengthPermutationCount(
superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthPermutationCount(
final Collection<O> superCollection, final int length) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superCollection.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
final Counter permutator = new PermutationCounter(length);
final Counter combinator = new CombinationCounter(
superCollection.size(), length);
final BigInteger combinationCount = combinator.getTotal();
final BigInteger permutationsPerCount = permutator.getTotal();
return combinationCount.multiply(permutationsPerCount);
}
public static <O> Set<List<O>> everyPermutation(final List<O> superList) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
// get every combination then permutate it
final Set<List<O>> permutations = new HashSet<>();
final Set<List<O>> combinations = everyCombination(superList);
combinations.stream().forEach((combination) -> permutations.addAll(sameLengthPermutations(combination)));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> everyPermutation(final Set<O> superSet) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
return everyPermutation(new ArrayList<>(superSet));
}
public static <O> Set<List<O>> fixedLengthPermutations(
final List<O> superList, final int length) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superList.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
// get every combination then permutate it
final Set<List<O>> permutations = new HashSet<>();
final Set<List<O>> combinations = fixedLengthCombinations(superList,
length);
combinations.stream().forEach((combination) -> permutations.addAll(sameLengthPermutations(combination)));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> fixedLengthPermutations(
final Set<O> superSet, final int length) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superSet.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
return fixedLengthPermutations(new ArrayList<>(superSet), length);
}
private static <O> Set<List<O>> sameLengthLexicographicPermutations(
final List<O> superList) {
final Set<List<O>> permutations = new HashSet<>();
final Counter generator = new LexicographicPermutationCounter(
superList.size());
while (generator.hasMore()) {
final List<O> permutation = new ArrayList<>();
final int[] permutationIndexes = generator.getNext();
for (final int permutationIndex : permutationIndexes)
permutation.add(superList.get(permutationIndex));
permutations.add(Collections.unmodifiableList(permutation));
}
return Collections.unmodifiableSet(permutations);
}
public static <O> BigInteger everyLexicographicPermutationCount(
final Collection<O> superCollection) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for (int currentSequenceLength = 1; currentSequenceLength <= superCollection
.size(); currentSequenceLength++)
combinations = combinations
.add(fixedLengthLexicographicPermutationCount(
superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthLexicographicPermutationCount(
final Collection<O> superCollection, final int length) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superCollection.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
final Counter permutator = new LexicographicPermutationCounter(length);
final Counter combinator = new CombinationCounter(
superCollection.size(), length);
final BigInteger combinationCount = combinator.getTotal();
final BigInteger permutationsPerCount = permutator.getTotal();
return combinationCount.multiply(permutationsPerCount);
}
public static <O> Set<List<O>> everyLexicographicPermutation(
final List<O> superList) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
// get every combination then permutate it
final Set<List<O>> permutations = new HashSet<>();
final Set<List<O>> combinations = everyCombination(superList);
combinations.stream().forEach((combination) -> permutations
.addAll(sameLengthLexicographicPermutations(combination)));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> everyLexicographicPermutation(
final Set<O> superSet) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
return everyLexicographicPermutation(new ArrayList<>(superSet));
}
public static <O> Set<List<O>> fixedLengthLexicographicPermutations(
final List<O> superList, final int length) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superList.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
// get every combination then permutate it
final Set<List<O>> permutations = new HashSet<>();
final Set<List<O>> combinations = fixedLengthCombinations(superList,
length);
combinations.stream().forEach((combination) -> permutations
.addAll(sameLengthLexicographicPermutations(combination)));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> fixedLengthLexicographicPermutations(
final Set<O> superSet, final int length) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superSet.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
return fixedLengthLexicographicPermutations(new ArrayList<>(superSet),
length);
}
private static <O> Set<List<O>> sameLengthJohnsonTrotterPermutations(
final List<O> superList) {
final Set<List<O>> permutations = new HashSet<>();
final Counter generator = new JohnsonTrotterPermutationCounter(
superList.size());
while (generator.hasMore()) {
final List<O> permutation = new ArrayList<>();
final int[] permutationIndexes = generator.getNext();
for (final int permutationIndex : permutationIndexes)
permutation.add(superList.get(permutationIndex));
permutations.add(Collections.unmodifiableList(permutation));
}
return Collections.unmodifiableSet(permutations);
}
public static <O> BigInteger everyJohnsonTrotterPermutationCount(
final Collection<O> superCollection) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for (int currentSequenceLength = 1; currentSequenceLength <= superCollection
.size(); currentSequenceLength++)
combinations = combinations
.add(fixedLengthJohnsonTrotterPermutationCount(
superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthJohnsonTrotterPermutationCount(
final Collection<O> superCollection, final int length) {
if (superCollection == null)
throw new IllegalArgumentException(
"superCollection can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superCollection.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
final Counter permutator = new JohnsonTrotterPermutationCounter(length);
final Counter combinator = new CombinationCounter(
superCollection.size(), length);
final BigInteger combinationCount = combinator.getTotal();
final BigInteger permutationsPerCount = permutator.getTotal();
return combinationCount.multiply(permutationsPerCount);
}
public static <O> Set<List<O>> everyJohnsonTrotterPermutation(
final List<O> superList) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
// get every combination then permutate it
final Set<List<O>> permutations = new HashSet<>();
final Set<List<O>> combinations = everyCombination(superList);
combinations.stream().forEach((combination) -> permutations
.addAll(sameLengthJohnsonTrotterPermutations(combination)));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> everyJohnsonTrotterPermutation(
final Set<O> superSet) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
return everyJohnsonTrotterPermutation(new ArrayList<>(superSet));
}
public static <O> Set<List<O>> fixedLengthJohnsonTrotterPermutations(
final List<O> superList, final int length) {
if (superList == null)
throw new IllegalArgumentException("superList can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superList.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
// get every combination then permutate it
final Set<List<O>> permutations = new HashSet<>();
final Set<List<O>> combinations = fixedLengthCombinations(superList,
length);
combinations.stream().forEach((combination) -> permutations
.addAll(sameLengthJohnsonTrotterPermutations(combination)));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> fixedLengthJohnsonTrotterPermutations(
final Set<O> superSet, final int length) {
if (superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if (length < 0)
throw new IllegalArgumentException("length must be >= 0");
if (length > superSet.size())
throw new IllegalArgumentException(
"length can not be larger than the collection size");
return fixedLengthJohnsonTrotterPermutations(
new ArrayList<>(superSet), length);
}
}
| agpl-3.0 |
StratusNetwork/ProjectAres | Util/core/src/main/java/tc/oc/commons/core/chat/NullAudience.java | 273 | package tc.oc.commons.core.chat;
import java.util.Optional;
public interface NullAudience extends ForwardingAudience {
@Override
default Optional<Audience> audience() {
return Optional.empty();
}
NullAudience INSTANCE = new NullAudience(){};
}
| agpl-3.0 |
SynthesisProject/server | synthesis-service/src/main/java/coza/opencollab/synthesis/service/util/impl/StringEntry.java | 880 | package coza.opencollab.synthesis.service.util.impl;
import coza.opencollab.synthesis.service.api.Defaults;
import coza.opencollab.synthesis.service.api.util.StorageEntry;
/**
* A entry that work with strings
*
* @author OpenCollab
* @since 1.0.0
* @version 1.0.1
*/
public class StringEntry extends StorageEntry {
/**
* The data in String.
*/
private String data;
/**
* Set all constructor
*
* @param name a {@link java.lang.String} object.
* @param relativePath a {@link java.lang.String} object.
* @param data a {@link java.lang.String} object.
*/
public StringEntry(String name, String relativePath, String data) {
super(name, relativePath);
this.data = data;
}
/** {@inheritDoc} */
@Override
public byte[] getContents() {
return data.getBytes(Defaults.UTF8);
}
}
| agpl-3.0 |
ProtocolSupport/ProtocolSupport | src/protocolsupport/protocol/packet/middle/impl/clientbound/play/v_8/ChunkData.java | 3225 | package protocolsupport.protocol.packet.middle.impl.clientbound.play.v_8;
import java.util.Map;
import org.bukkit.NamespacedKey;
import protocolsupport.protocol.codec.ArrayCodec;
import protocolsupport.protocol.codec.MiscDataCodec;
import protocolsupport.protocol.codec.PositionCodec;
import protocolsupport.protocol.packet.ClientBoundPacketData;
import protocolsupport.protocol.packet.ClientBoundPacketType;
import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV8;
import protocolsupport.protocol.packet.middle.impl.clientbound.play.v_4_5_6_7_8_9r1_9r2_10_11_12r1_12r2_13.AbstractChunkCacheChunkData;
import protocolsupport.protocol.packet.middle.impl.clientbound.play.v_8_9r1_9r2_10_11_12r1_12r2_13.BlockTileUpdate;
import protocolsupport.protocol.typeremapper.basic.BiomeTransformer;
import protocolsupport.protocol.typeremapper.block.BlockDataLegacyDataRegistry;
import protocolsupport.protocol.typeremapper.chunk.ChunkBiomeLegacyWriter;
import protocolsupport.protocol.typeremapper.chunk.ChunkBlockdataLegacyWriterShort;
import protocolsupport.protocol.typeremapper.chunk.ChunkLegacyWriteUtils;
import protocolsupport.protocol.typeremapper.utils.MappingTable.GenericMappingTable;
import protocolsupport.protocol.typeremapper.utils.MappingTable.IntMappingTable;
import protocolsupport.protocol.types.Position;
import protocolsupport.protocol.types.TileEntity;
import protocolsupport.utils.CollectionsUtils;
public class ChunkData extends AbstractChunkCacheChunkData implements IClientboundMiddlePacketV8 {
public ChunkData(IMiddlePacketInit init) {
super(init);
}
protected final GenericMappingTable<NamespacedKey> biomeLegacyDataTable = BiomeTransformer.REGISTRY.getTable(version);
protected final IntMappingTable blockLegacyDataTable = BlockDataLegacyDataRegistry.INSTANCE.getTable(version);
@Override
protected void write() {
ClientBoundPacketData chunkdataPacket = ClientBoundPacketData.create(ClientBoundPacketType.PLAY_CHUNK_DATA);
PositionCodec.writeIntChunkCoord(chunkdataPacket, coord);
chunkdataPacket.writeBoolean(full);
if (mask.isEmpty() && full) {
chunkdataPacket.writeShort(1);
ArrayCodec.writeVarIntByteArray(chunkdataPacket, ChunkLegacyWriteUtils.getEmptySectionShort(clientCache.hasDimensionSkyLight()));
} else {
chunkdataPacket.writeShort(CollectionsUtils.getBitSetFirstLong(mask));
MiscDataCodec.writeVarIntLengthPrefixedType(chunkdataPacket, this, (to, chunkdataInstance) -> {
to.writeBytes(ChunkBlockdataLegacyWriterShort.serializeSections(
chunkdataInstance.blockLegacyDataTable,
chunkdataInstance.cachedChunk, chunkdataInstance.mask, chunkdataInstance.clientCache.hasDimensionSkyLight()
));
if (chunkdataInstance.full) {
for (int biomeId : ChunkBiomeLegacyWriter.toPerBlockBiomeData(chunkdataInstance.clientCache, chunkdataInstance.biomeLegacyDataTable, chunkdataInstance.sections[0].getBiomes())) {
to.writeByte(biomeId);
}
}
});
}
io.writeClientbound(chunkdataPacket);
for (Map<Position, TileEntity> sectionTiles : cachedChunk.getTiles()) {
for (TileEntity tile : sectionTiles.values()) {
io.writeClientbound(BlockTileUpdate.create(version, tile));
}
}
}
}
| agpl-3.0 |
irina-mitrea-luxoft/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/netty/bootstrap/channel/AbstractServerChannel.java | 2613 | /*
* Copyright 2014, Kaazing Corporation. All rights reserved.
*
* 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 org.kaazing.k3po.driver.internal.netty.bootstrap.channel;
import static org.jboss.netty.channel.Channels.fireChannelOpen;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelConfig;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelSink;
import org.kaazing.k3po.driver.internal.netty.channel.ChannelAddress;
public class AbstractServerChannel<T extends ChannelConfig> extends org.jboss.netty.channel.AbstractServerChannel {
private final T config;
private final AtomicBoolean bound;
private final AtomicInteger bindCount;
private volatile ChannelAddress localAddress;
private volatile Channel transport;
public AbstractServerChannel(ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, T config) {
super(factory, pipeline, sink);
this.config = config;
this.bound = new AtomicBoolean();
this.bindCount = new AtomicInteger();
// required by ServerBootstrap
fireChannelOpen(this);
}
@Override
public T getConfig() {
return config;
}
@Override
public ChannelAddress getLocalAddress() {
return bound.get() ? localAddress : null;
}
@Override
public ChannelAddress getRemoteAddress() {
return null;
}
@Override
public boolean isBound() {
return isOpen() && bound.get();
}
public AtomicInteger getBindCount() {
return bindCount;
}
protected void setLocalAddress(ChannelAddress localAddress) {
this.localAddress = localAddress;
}
protected void setBound() {
bound.set(true);
}
protected void setTransport(Channel transport) {
this.transport = transport;
}
protected Channel getTransport() {
return transport;
}
}
| agpl-3.0 |
podd/podd-redesign | webapp/lib/src/main/java/com/github/podd/impl/PoddSesameManagerImpl.java | 114196 | /**
* PODD is an OWL ontology database used for scientific project management
*
* Copyright (C) 2009-2013 The University Of Queensland
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.podd.impl;
import info.aduna.iteration.Iterations;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.openrdf.OpenRDFException;
import org.openrdf.model.Model;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.model.impl.LiteralImpl;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.OWL;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.RDFS;
import org.openrdf.query.BindingSet;
import org.openrdf.query.BooleanQuery;
import org.openrdf.query.GraphQuery;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.QueryResults;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.impl.DatasetImpl;
import org.openrdf.query.resultio.helpers.QueryResultCollector;
import org.openrdf.queryrender.RenderUtils;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.helpers.StatementCollector;
import org.openrdf.sail.memory.MemoryStore;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntologyID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.podd.api.MetadataPolicy;
import com.github.podd.api.PoddSesameManager;
import com.github.podd.exception.SchemaManifestException;
import com.github.podd.exception.UnmanagedArtifactIRIException;
import com.github.podd.exception.UnmanagedSchemaIRIException;
import com.github.podd.ontologies.PODDSCIENCE;
import com.github.podd.utils.DebugUtils;
import com.github.podd.utils.InferredOWLOntologyID;
import com.github.podd.utils.OntologyUtils;
import com.github.podd.utils.PODD;
import com.github.podd.utils.PoddObjectLabel;
import com.github.podd.utils.PoddObjectLabelImpl;
import com.github.podd.utils.RdfUtility;
/**
* @author kutila
* @author Peter Ansell p_ansell@yahoo.com
*
*/
public class PoddSesameManagerImpl implements PoddSesameManager
{
private final Logger log = LoggerFactory.getLogger(this.getClass());
public PoddSesameManagerImpl()
{
}
@Override
public void deleteOntologies(final Collection<InferredOWLOntologyID> givenOntologies,
final RepositoryConnection permanentConnection, final RepositoryConnection managementConnection,
final URI managementGraph) throws OpenRDFException
{
for(final InferredOWLOntologyID nextOntologyID : givenOntologies)
{
final List<InferredOWLOntologyID> versionInternal =
this.getCurrentVersionsInternal(nextOntologyID.getOntologyIRI(), managementConnection,
managementGraph);
boolean updateCurrentVersion = false;
InferredOWLOntologyID newCurrentVersion = null;
// If there were managed versions, and the head of the list, which
// is the current
// version by convention, is the same as out version, then we need
// to update it,
// otherwise we don't need to update it.
if(!versionInternal.isEmpty()
&& versionInternal.get(0).getVersionIRI().equals(nextOntologyID.getVersionIRI()))
{
updateCurrentVersion = true;
if(versionInternal.size() > 1)
{
// FIXME: Improve this version detection...
newCurrentVersion = versionInternal.get(1);
}
}
// clear out the direct and inferred ontology graphs
permanentConnection.remove((URI)null, null, null, nextOntologyID.getInferredOntologyIRI().toOpenRDFURI());
permanentConnection.remove((URI)null, null, null, nextOntologyID.getVersionIRI().toOpenRDFURI());
// clear out references attached to the version and inferred IRIs in
// the management graph
managementConnection.remove(nextOntologyID.getVersionIRI().toOpenRDFURI(), null, null, managementGraph);
managementConnection.remove(nextOntologyID.getInferredOntologyIRI().toOpenRDFURI(), null, null,
managementGraph);
// clear out references linked to the version and inferred IRIs in
// the management graph
managementConnection
.remove((URI)null, null, nextOntologyID.getVersionIRI().toOpenRDFURI(), managementGraph);
managementConnection.remove((URI)null, null, nextOntologyID.getInferredOntologyIRI().toOpenRDFURI(),
managementGraph);
if(updateCurrentVersion)
{
final List<Statement> asList =
Iterations.asList(managementConnection.getStatements(nextOntologyID.getOntologyIRI()
.toOpenRDFURI(), PODD.OMV_CURRENT_VERSION, null, false, managementGraph));
if(asList.size() != 1)
{
this.log.error(
"Did not find a unique managed current version for ontology with ID: {} List was: {}",
nextOntologyID, asList);
}
// remove the current versions from the management graph
managementConnection.remove(asList, managementGraph);
// If there is no replacement available, then wipe the slate
// clean in the management
// graph
if(newCurrentVersion == null)
{
managementConnection.remove(nextOntologyID.getOntologyIRI().toOpenRDFURI(), null, null,
managementGraph);
}
else
{
// Push the next current version into the management graph
managementConnection.add(nextOntologyID.getOntologyIRI().toOpenRDFURI(), PODD.OMV_CURRENT_VERSION,
newCurrentVersion.getVersionIRI().toOpenRDFURI(), managementGraph);
}
}
}
}
@Override
public Model fillMissingLabels(final Model inputModel, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
final Set<URI> missingLabelUris = new LinkedHashSet<>();
for(final Resource subject : inputModel.subjects())
{
if(subject instanceof URI)
{
final Set<Value> objects = inputModel.filter(subject, RDFS.LABEL, null, contexts).objects();
if(objects.isEmpty() || objects.size() == 1 && objects.iterator().next().stringValue().equals("?blank"))
{
missingLabelUris.add((URI)subject);
}
}
}
if(missingLabelUris.isEmpty())
{
return new LinkedHashModel();
}
final StringBuilder graphQuery = new StringBuilder(1024);
graphQuery.append("CONSTRUCT { ");
graphQuery.append(" ?subject ");
graphQuery.append(RenderUtils.getSPARQLQueryString(RDFS.LABEL));
graphQuery.append(" ?label . ");
graphQuery.append("} WHERE {");
graphQuery.append(" ?subject ");
graphQuery.append(RenderUtils.getSPARQLQueryString(RDFS.LABEL));
graphQuery.append(" ?label . ");
graphQuery.append("}");
graphQuery.append(" VALUES (?subject) { ");
for(final URI nextMissingLabelUri : missingLabelUris)
{
graphQuery.append(" ( ");
graphQuery.append(RenderUtils.getSPARQLQueryString(nextMissingLabelUri));
graphQuery.append(" ) ");
}
graphQuery.append(" } ");
final GraphQuery rdfsGraphQuery =
repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, graphQuery.toString());
this.log.trace("Created SPARQL {}.", graphQuery);
return RdfUtility.executeGraphQuery(rdfsGraphQuery, contexts);
}
@Override
public Set<InferredOWLOntologyID> getAllCurrentSchemaOntologyVersions(
final RepositoryConnection repositoryConnection, final URI schemaManagementGraph) throws OpenRDFException
{
final Set<InferredOWLOntologyID> returnList = new HashSet<InferredOWLOntologyID>();
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT ?ontologyIri ?currentVersionIri ?inferredVersionIri WHERE { ");
sb.append(" ?ontologyIri <" + RDF.TYPE.stringValue() + "> <" + OWL.ONTOLOGY.stringValue() + "> . ");
sb.append(" ?ontologyIri <" + PODD.OMV_CURRENT_VERSION.stringValue() + "> ?currentVersionIri . ");
sb.append(" OPTIONAL { ?currentVersionIri <" + PODD.PODD_BASE_INFERRED_VERSION.stringValue()
+ "> ?inferredVersionIri . } ");
sb.append(" }");
this.log.debug("Generated SPARQL {} ", sb);
final TupleQuery query = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(query, schemaManagementGraph);
for(final BindingSet nextResult : queryResults.getBindingSets())
{
final String nextOntologyIRI = nextResult.getValue("ontologyIri").stringValue();
final String nextVersionIRI = nextResult.getValue("currentVersionIri").stringValue();
IRI nextInferredIRI = null;
if(nextResult.hasBinding("inferredVersionIri"))
{
nextInferredIRI = IRI.create(nextResult.getValue("inferredVersionIri").stringValue());
}
returnList.add(new InferredOWLOntologyID(IRI.create(nextOntologyIRI), IRI.create(nextVersionIRI),
nextInferredIRI));
}
return returnList;
}
@Override
public List<InferredOWLOntologyID> getAllOntologyVersions(final IRI ontologyIRI,
final RepositoryConnection repositoryConnection, final URI ontologyManagementGraph) throws OpenRDFException
{
// FIXME: This implementation doesn't seem correct. Verify with tests.
return this.getCurrentVersionsInternal(ontologyIRI, repositoryConnection, ontologyManagementGraph);
}
@Override
public Set<InferredOWLOntologyID> getAllSchemaOntologyVersions(final RepositoryConnection repositoryConnection,
final URI schemaManagementGraph) throws OpenRDFException
{
final Set<InferredOWLOntologyID> returnList = new LinkedHashSet<InferredOWLOntologyID>();
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?ontologyIri ?versionIri ?inferredVersionIri WHERE { ");
sb.append(" ?ontologyIri a <" + OWL.ONTOLOGY.stringValue() + "> . ");
sb.append(" ?ontologyIri <" + OWL.VERSIONIRI.stringValue() + "> ?versionIri . ");
sb.append(" OPTIONAL { ?versionIri <" + PODD.PODD_BASE_INFERRED_VERSION.stringValue()
+ "> ?inferredVersionIri . } ");
sb.append(" }");
this.log.debug("Generated SPARQL {} ", sb);
final TupleQuery query = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(query, schemaManagementGraph);
for(final BindingSet nextResult : queryResults.getBindingSets())
{
final String nextOntologyIRI = nextResult.getValue("ontologyIri").stringValue();
final String nextVersionIRI = nextResult.getValue("versionIri").stringValue();
IRI nextInferredIRI = null;
if(nextResult.hasBinding("inferredVersionIri"))
{
nextInferredIRI = IRI.create(nextResult.getValue("inferredVersionIri").stringValue());
}
returnList.add(new InferredOWLOntologyID(IRI.create(nextOntologyIRI), IRI.create(nextVersionIRI),
nextInferredIRI));
}
return returnList;
}
@Override
public Map<URI, URI> getCardinalityValues(final InferredOWLOntologyID artifactID, final URI objectUri,
final Collection<URI> propertyUris, final RepositoryConnection managementConnection,
final RepositoryConnection permanentConnection, final URI schemaManagementGraph,
final URI artifactManagementGraph) throws OpenRDFException, SchemaManifestException,
UnmanagedSchemaIRIException
{
return this.getCardinalityValues(objectUri, propertyUris, false, permanentConnection, this
.versionAndInferredAndSchemaContexts(artifactID, managementConnection, schemaManagementGraph,
artifactManagementGraph));
}
@Override
public Map<URI, URI> getCardinalityValues(final URI objectUri, final Collection<URI> propertyUris,
final boolean findFromType, final RepositoryConnection repositoryConnection, final URI... contexts)
throws OpenRDFException
{
/*
* Example of how a qualified cardinality statement appears in RDF triples
*
* {poddBase:PoddTopObject} <rdfs:subClassOf> {_:node17l3l94qux1}
*
* {_:node17l3l94qux1} <rdf:type> {owl:Restriction}
*
* {_:node17l3l94qux1} <owl#onProperty> {poddBase:hasLeadInstitution}
*
* {_:node17l3l94qux1} <owl:qualifiedCardinality> {"1"^^<xsd:nonNegativeInteger>}
*
* {_:node17l3l94qux1} <owl:onDataRange> {xsd:string}
*/
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?propertyUri ?qualifiedCardinality ?minQualifiedCardinality ?maxQualifiedCardinality ");
sb.append(" WHERE { ");
if(!findFromType)
{
sb.append(" ?poddObject a ?somePoddConcept . ");
}
sb.append(" ?somePoddConcept <" + RDFS.SUBCLASSOF.stringValue() + ">+ ?x . ");
sb.append(" ?x a <" + OWL.RESTRICTION.stringValue() + "> . ");
sb.append(" ?x <" + OWL.ONPROPERTY.stringValue() + "> ?propertyUri . ");
sb.append(" OPTIONAL { ?x <http://www.w3.org/2002/07/owl#maxQualifiedCardinality> ?maxQualifiedCardinality } . ");
sb.append(" OPTIONAL { ?x <http://www.w3.org/2002/07/owl#minQualifiedCardinality> ?minQualifiedCardinality } . ");
sb.append(" OPTIONAL { ?x <http://www.w3.org/2002/07/owl#qualifiedCardinality> ?qualifiedCardinality } . ");
sb.append(" } ");
if(!propertyUris.isEmpty())
{
sb.append(" VALUES (?propertyUri) { ");
for(final URI nextProperty : propertyUris)
{
sb.append(" ( ");
sb.append(RenderUtils.getSPARQLQueryString(nextProperty));
sb.append(" ) ");
}
sb.append(" } ");
}
// this.log.trace("Created SPARQL {} with propertyUri {} and poddObject {}",
// sb,
// propertyUri, objectUri);
final TupleQuery query = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
// query.setBinding("propertyUri", propertyUri);
if(findFromType)
{
query.setBinding("somePoddConcept", objectUri);
}
else
{
query.setBinding("poddObject", objectUri);
}
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(query, contexts);
final ConcurrentMap<URI, URI> resultMap = new ConcurrentHashMap<URI, URI>();
for(final BindingSet next : queryResults.getBindingSets())
{
final Value nextProperty = next.getValue("propertyUri");
if(nextProperty instanceof URI)
{
final URI nextPropertyURI = (URI)nextProperty;
URI nextCardinality = PODD.PODD_BASE_CARDINALITY_ZERO_OR_MANY;
final Value qualifiedCardinalityValue = next.getValue("qualifiedCardinality");
if(qualifiedCardinalityValue != null)
{
nextCardinality = PODD.PODD_BASE_CARDINALITY_EXACTLY_ONE;
}
int minCardinality = -1;
int maxCardinality = -1;
final Value minCardinalityValue = next.getValue("minQualifiedCardinality");
if(minCardinalityValue != null && minCardinalityValue instanceof LiteralImpl)
{
minCardinality = ((LiteralImpl)minCardinalityValue).intValue();
}
final Value maxCardinalityValue = next.getValue("maxQualifiedCardinality");
if(maxCardinalityValue != null && maxCardinalityValue instanceof LiteralImpl)
{
maxCardinality = ((LiteralImpl)maxCardinalityValue).intValue();
}
if(maxCardinality == 1 && minCardinality < 1)
{
nextCardinality = PODD.PODD_BASE_CARDINALITY_ZERO_OR_ONE;
}
else if(minCardinality == 1 && maxCardinality != 1)
{
nextCardinality = PODD.PODD_BASE_CARDINALITY_ONE_OR_MANY;
}
final URI putIfAbsent = resultMap.putIfAbsent(nextPropertyURI, nextCardinality);
if(putIfAbsent != null && !nextCardinality.equals(putIfAbsent))
{
this.log.warn(
"Found duplicate cardinality constraints for {} : original constraint : {} ignored constraint {}",
nextPropertyURI, putIfAbsent, nextCardinality);
}
}
else
{
this.log.warn("Property was not bound to a URI: {}", nextProperty);
}
}
return resultMap;
}
@Override
public Set<URI> getEventsTopConcepts(final RepositoryConnection repositoryConnection, final URI... contexts)
throws OpenRDFException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?event ");
sb.append(" WHERE { ");
sb.append(" ?event rdfs:subClassOf <" + PODD.INRA_EVENT_EVENT + "> ");
sb.append(" } ");
this.log.debug("Create SPARQL {} to find Event Type", sb);
final TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(tupleQuery, contexts);
final Set<URI> resultSet = new HashSet<URI>();
for(final BindingSet next : queryResults.getBindingSets())
{
final Value event = next.getValue("event");
if(event instanceof URI)
{
resultSet.add((URI)event);
}
}
this.log.info("Result spql query getEventsTopConcepts {}", resultSet);
return resultSet;
}
@Override
public Set<URI> getDirectSubClassOf(final URI concept, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?subclass ");
sb.append(" WHERE { ");
sb.append(" ?subclass rdfs:subClassOf <" + concept + "> ");
sb.append(" } ");
this.log.debug("Create SPARQL {} to find direct subclass of one concept", sb);
final TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(tupleQuery, contexts);
final Set<URI> resultSet = new HashSet<URI>();
for(final BindingSet next : queryResults.getBindingSets())
{
final Value event = next.getValue("subclass");
if(event instanceof URI)
{
resultSet.add((URI)event);
}
}
this.log.info("Result spql query getDirectSubClassOf ({}) {}", concept, resultSet);
return resultSet;
}
@Override
public Set<URI> getChildObjects(final URI objectUri, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?childUri ");
sb.append(" WHERE { ");
sb.append(" ?poddObject ?propertyUri ?childUri . ");
sb.append(" FILTER(isIRI(?childUri)) . ");
sb.append(" ?propertyUri <" + RDFS.SUBPROPERTYOF.stringValue() + "> <" + PODD.PODD_BASE_CONTAINS + "> . ");
sb.append(" } ");
this.log.trace("Created SPARQL {} with poddObject bound to {}", sb, objectUri);
final TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
tupleQuery.setBinding("poddObject", objectUri);
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(tupleQuery, contexts);
final Set<URI> resultSet = new HashSet<URI>();
for(final BindingSet next : queryResults.getBindingSets())
{
final Value child = next.getValue("childUri");
if(child instanceof URI)
{
resultSet.add((URI)child);
}
}
return resultSet;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getCurrentArtifactVersion(org.
* semanticweb.owlapi.model .IRI, org.openrdf.repository.RepositoryConnection,
* org.openrdf.model.URI)
*/
@Override
public InferredOWLOntologyID getCurrentArtifactVersion(final IRI ontologyIRI,
final RepositoryConnection repositoryConnection, final URI managementGraph) throws OpenRDFException,
UnmanagedArtifactIRIException
{
if(ontologyIRI.toString().startsWith("_:"))
{
throw new UnmanagedArtifactIRIException(ontologyIRI,
"This IRI does not refer to a managed ontology (blank node)");
}
final InferredOWLOntologyID inferredOntologyID =
this.getCurrentVersionInternal(ontologyIRI, repositoryConnection, managementGraph);
if(inferredOntologyID != null)
{
return inferredOntologyID;
}
else
{
throw new UnmanagedArtifactIRIException(ontologyIRI, "This IRI does not refer to a managed ontology");
}
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getCurrentSchemaVersion(org.semanticweb
* .owlapi.model .IRI, org.openrdf.repository.RepositoryConnection, org.openrdf.model.URI)
*/
@Override
public InferredOWLOntologyID getCurrentSchemaVersion(final IRI ontologyIRI,
final RepositoryConnection repositoryConnection, final URI managementGraph) throws OpenRDFException,
UnmanagedSchemaIRIException
{
final InferredOWLOntologyID inferredOntologyID =
this.getCurrentVersionInternal(ontologyIRI, repositoryConnection, managementGraph);
if(inferredOntologyID != null)
{
return inferredOntologyID;
}
else
{
throw new UnmanagedSchemaIRIException(ontologyIRI, "This IRI does not refer to a managed ontology: "
+ ontologyIRI);
}
}
/**
* Inner helper method for getCurrentArtifactVersion() and getCurrentSchemaVersion().
*
* @param ontologyIRI
* @param repositoryConnection
* @param managementGraph
* @return
* @throws OpenRDFException
*/
private InferredOWLOntologyID getCurrentVersionInternal(final IRI ontologyIRI,
final RepositoryConnection repositoryConnection, final URI managementGraph) throws OpenRDFException
{
final List<InferredOWLOntologyID> list =
this.getCurrentVersionsInternal(ontologyIRI, repositoryConnection, managementGraph);
if(list.isEmpty())
{
return null;
}
else
{
return list.get(0);
}
}
/**
* Inner helper method for getCurrentArtifactVersion() and getCurrentSchemaVersion().
*
* If the input ontologyIRI is either an Ontology IRI or Version IRI for a managed ontology, the
* ID of the current version of this ontology is returned.
*
* @param ontologyIRI
* Either an Ontology IRI or Version IRI for which the current version is requested.
* @param repositoryConnection
* @param managementGraph
* @return A List of InferredOWLOntologyIDs. If the ontology is managed, the list will contain
* one entry for its current version. Otherwise the list will be empty.
* @throws OpenRDFException
*/
private List<InferredOWLOntologyID> getCurrentVersionsInternal(final IRI ontologyIRI,
final RepositoryConnection repositoryConnection, final URI managementGraph) throws OpenRDFException
{
final List<InferredOWLOntologyID> returnList = new ArrayList<InferredOWLOntologyID>();
final DatasetImpl dataset = new DatasetImpl();
dataset.addDefaultGraph(managementGraph);
dataset.addNamedGraph(managementGraph);
if(this.log.isDebugEnabled())
{
DebugUtils.printContents(repositoryConnection, managementGraph);
}
// 1: see if the given IRI exists as an ontology IRI
final StringBuilder sb1 = new StringBuilder(1024);
sb1.append("SELECT DISTINCT ?cv ?civ WHERE { ");
sb1.append(" ?ontologyIri <" + RDF.TYPE.stringValue() + "> <" + OWL.ONTOLOGY.stringValue() + "> . ");
sb1.append(" ?ontologyIri <" + PODD.OMV_CURRENT_VERSION.stringValue() + "> ?cv . ");
sb1.append(" OPTIONAL { ?cv <" + PODD.PODD_BASE_INFERRED_VERSION.stringValue() + "> ?civ . } ");
sb1.append(" }");
this.log.debug("Generated SPARQL {} with ontologyIri bound to {}", sb1, ontologyIRI);
final TupleQuery query1 = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb1.toString());
query1.setBinding("ontologyIri", ontologyIRI.toOpenRDFURI());
query1.setDataset(dataset);
final TupleQueryResult query1Results = query1.evaluate();
final QueryResultCollector nextResults1 = new QueryResultCollector();
QueryResults.report(query1Results, nextResults1);
for(final BindingSet nextResult : nextResults1.getBindingSets())
{
final URI nextVersionIRI = (URI)nextResult.getValue("cv");
IRI nextInferredIRI;
if(nextResult.hasBinding("civ"))
{
nextInferredIRI = IRI.create(nextResult.getValue("civ").stringValue());
}
else
{
nextInferredIRI = null;
}
returnList.add(new InferredOWLOntologyID(ontologyIRI, IRI.create(nextVersionIRI), nextInferredIRI));
}
// 2: see if the given IRI exists as a version IRI
final StringBuilder sb2 = new StringBuilder(1024);
sb2.append("SELECT DISTINCT ?x ?cv ?civ WHERE { ");
sb2.append(" ?x <" + RDF.TYPE.stringValue() + "> <" + OWL.ONTOLOGY.stringValue() + "> . ");
sb2.append(" ?x <" + OWL.VERSIONIRI.stringValue() + "> ?nextVersion . ");
sb2.append(" ?x <" + OWL.VERSIONIRI.stringValue() + "> ?cv . ");
sb2.append(" ?x <" + PODD.OMV_CURRENT_VERSION.stringValue() + "> ?cv . ");
sb2.append(" OPTIONAL { ?cv <" + PODD.PODD_BASE_INFERRED_VERSION.stringValue() + "> ?civ . } ");
sb2.append(" }");
this.log.debug("Generated SPARQL {} with versionIri bound to {}", sb2, ontologyIRI);
final TupleQuery query2 = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb2.toString());
query2.setBinding("nextVersion", ontologyIRI.toOpenRDFURI());
query2.setDataset(dataset);
final TupleQueryResult queryResults2 = query2.evaluate();
final QueryResultCollector nextResults2 = new QueryResultCollector();
QueryResults.report(queryResults2, nextResults2);
for(final BindingSet nextResult : nextResults2.getBindingSets())
{
final String nextOntologyIRI = nextResult.getValue("x").stringValue();
final String nextVersionIRI = nextResult.getValue("cv").stringValue();
IRI nextInferredIRI;
if(nextResult.hasBinding("civ"))
{
nextInferredIRI = IRI.create(nextResult.getValue("civ").stringValue());
}
else
{
nextInferredIRI = null;
}
returnList.add(new InferredOWLOntologyID(IRI.create(nextOntologyIRI), IRI.create(nextVersionIRI),
nextInferredIRI));
}
return returnList;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getDirectImports(org.openrdf.repository .
* RepositoryConnection, org.openrdf.model.URI)
*/
@Override
public Set<URI> getDirectImports(final InferredOWLOntologyID ontologyID,
final RepositoryConnection permanentConnection) throws OpenRDFException
{
return this.getDirectImports(ontologyID.getOntologyIRI(), permanentConnection,
this.versionAndInferredContexts(ontologyID));
}
@Override
public Set<URI> getDirectImports(final RepositoryConnection permanentConnection, final URI... contexts)
throws OpenRDFException
{
return this.getDirectImports(null, permanentConnection, contexts);
}
@Override
public Set<URI> getDirectImports(final IRI ontologyIRI, final RepositoryConnection permanentConnection,
final URI... contexts) throws OpenRDFException
{
final Set<URI> results = new HashSet<>();
RepositoryResult<Statement> statements;
if(ontologyIRI != null)
{
statements =
permanentConnection.getStatements(ontologyIRI.toOpenRDFURI(), OWL.IMPORTS, null, true, contexts);
}
else
{
statements = permanentConnection.getStatements(null, OWL.IMPORTS, null, true, contexts);
}
// DebugUtils.printContents(permanentConnection, contexts);
for(final Statement nextImport : Iterations.asList(statements))
{
if(nextImport.getObject() instanceof URI)
{
results.add((URI)nextImport.getObject());
}
}
return results;
}
private Model getInstancesOf(final Collection<URI> nextRangeTypes, final RepositoryConnection repositoryConnection,
final URI[] contexts) throws OpenRDFException
{
if(nextRangeTypes.isEmpty())
{
return new LinkedHashModel();
}
/*
* This query gets the instances and their RDFS:labels for that are of the given type.
*/
final StringBuilder instanceQuery = new StringBuilder(1024);
instanceQuery.append("CONSTRUCT { ");
instanceQuery.append(" ?instanceUri <" + RDF.TYPE.stringValue() + "> ?rangeClass . ");
instanceQuery.append(" ?instanceUri <" + RDFS.LABEL.stringValue() + "> ?label . ");
instanceQuery.append("} WHERE {");
instanceQuery.append(" ?instanceUri <" + RDF.TYPE.stringValue() + "> ?rangeClass . ");
instanceQuery.append(" OPTIONAL { ?instanceUri <" + RDFS.LABEL.stringValue() + "> ?label . } ");
instanceQuery.append("}");
instanceQuery.append(" VALUES (?rangeClass) { ");
for(final URI nextRangeType : nextRangeTypes)
{
instanceQuery.append(" ( ");
instanceQuery.append(RenderUtils.getSPARQLQueryString(nextRangeType));
instanceQuery.append(" ) ");
}
instanceQuery.append(" } ");
final GraphQuery rdfsGraphQuery =
repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, instanceQuery.toString());
// rdfsGraphQuery.setBinding("rangeClass", nextRangeType);
// this.log.trace("Created SPARQL {} \n with nextRangeType bound to {}",
// instanceQuery,
// nextRangeType);
return RdfUtility.executeGraphQuery(rdfsGraphQuery, contexts);
}
@Override
public Model getObjectData(final InferredOWLOntologyID artifactID, final URI objectUri,
final RepositoryConnection repositoryConnection, final URI... contexts) throws OpenRDFException
{
if(objectUri == null)
{
return new LinkedHashModel();
}
final StringBuilder sb = new StringBuilder(1024);
sb.append("CONSTRUCT { ");
sb.append(" ?poddObject ?propertyUri ?value . ");
sb.append(" ?parent ?somePropertyUri ?poddObject . ");
sb.append("} WHERE {");
sb.append(" ?poddObject ?propertyUri ?value . ");
// TODO: somePropertyUri should be a sub property of podd:contains
sb.append(" OPTIONAL { ?parent ?somePropertyUri ?poddObject . }");
sb.append("}");
final GraphQuery graphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sb.toString());
graphQuery.setBinding("poddObject", objectUri);
final Model queryResults = RdfUtility.executeGraphQuery(graphQuery, contexts);
return queryResults;
}
/**
* The result of this method is a Model containing all data required for displaying the details
* of the object in HTML+RDFa.
*
* The returned graph has the following structure.
*
* poddObject :propertyUri :value
*
* propertyUri RDFS:Label "property label"
*
* value RDFS:Label "value label"
*
* @param objectUri
* @param permanentConnection
* @param artifactManagementGraph
* @param contexts
*
* @return
* @throws OpenRDFException
* @throws SchemaManifestException
* @throws UnmanagedSchemaIRIException
*/
@Override
public Model getObjectDetailsForDisplay(final InferredOWLOntologyID artifactID, final URI objectUri,
final RepositoryConnection managementConnection, final RepositoryConnection permanentConnection,
final URI schemaManagementGraph, final URI artifactManagementGraph) throws OpenRDFException,
SchemaManifestException, UnmanagedSchemaIRIException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("CONSTRUCT { ");
sb.append(" ?poddObject ?propertyUri ?value . ");
sb.append(" ?propertyUri <" + RDFS.LABEL.stringValue() + "> ?propertyLabel . ");
sb.append(" ?value <" + RDFS.LABEL.stringValue() + "> ?valueLabel . ");
sb.append("} WHERE {");
sb.append(" ?poddObject ?propertyUri ?value . ");
sb.append(" ?propertyUri <" + RDFS.LABEL.stringValue() + "> ?propertyLabel . ");
// value may not have a Label
sb.append(" OPTIONAL {?value <" + RDFS.LABEL.stringValue() + "> ?valueLabel } . ");
sb.append(" FILTER NOT EXISTS { ?propertyUri <" + PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue() + "> true } ");
sb.append(" FILTER (?value != <" + OWL.THING.stringValue() + ">) ");
sb.append(" FILTER (?value != <" + OWL.INDIVIDUAL.stringValue() + ">) ");
sb.append(" FILTER (?value != <http://www.w3.org/2002/07/owl#NamedIndividual>) ");
sb.append(" FILTER (?value != <" + OWL.CLASS.stringValue() + ">) ");
sb.append("}");
final String queryString = sb.toString();
this.log.debug("query={}", queryString);
final GraphQuery graphQuery = permanentConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
graphQuery.setBinding("poddObject", objectUri);
final Model queryResults =
RdfUtility.executeGraphQuery(graphQuery, this.versionAndInferredAndSchemaContexts(artifactID,
managementConnection, schemaManagementGraph, artifactManagementGraph));
return queryResults;
}
/**
* Given an object URI, this method attempts to retrieve its label (rdfs:label) and description
* (rdfs:comment) encapsulated in a <code>PoddObjectLabel</code> instance.
*
* If a label is not found, the local name from the Object URI is used as the label.
*
* @param ontologyID
* Is used to decide on the graphs in which to search for a label. This includes the
* given ontology as well as its imports.
* @param objectUri
* The object whose label and description are sought.
* @param permanentConnection
* @param artifactManagementGraph
* @return
* @throws OpenRDFException
* @throws SchemaManifestException
* @throws UnmanagedSchemaIRIException
*/
/*
* TODO
*
* MANAGE DIFFERENT LANGUAGE : ONLY @en MANAGED (non-Javadoc)
*
* @see
* com.github.podd.api.PoddSesameManager#getObjectLabel(com.github.podd.utils.InferredOWLOntologyID
* , org.openrdf.model.URI, org.openrdf.repository.RepositoryConnection,
* org.openrdf.repository.RepositoryConnection, org.openrdf.model.URI, org.openrdf.model.URI)
*/
@Override
public PoddObjectLabel getObjectLabel(final InferredOWLOntologyID ontologyID, final URI objectUri,
final RepositoryConnection managementConnection, final RepositoryConnection permanentConnection,
final URI schemaManagementGraph, final URI artifactManagementGraph) throws OpenRDFException,
SchemaManifestException, UnmanagedSchemaIRIException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT ?label ?description ?barcode ");
sb.append(" WHERE { ");
sb.append(" OPTIONAL { ?objectUri <" + RDFS.LABEL + "> ?label . } ");
sb.append(" OPTIONAL { ?objectUri <" + RDFS.COMMENT + "> ?description . } ");
sb.append(" OPTIONAL { ?objectUri <" + PODDSCIENCE.HAS_BARCODE + "> ?barcode . } ");
sb.append(" FILTER (lang(?label) = 'en'|| lang(?label)='')");
sb.append(" }");
// To get lang
// Locale.getDefault();
this.log.trace("Created SPARQL {} with objectUri bound to {}", sb, objectUri);
final TupleQuery tupleQuery = permanentConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
tupleQuery.setBinding("objectUri", objectUri);
URI[] contexts;
if(ontologyID != null)
{
contexts =
this.versionAndSchemaContexts(ontologyID, managementConnection, schemaManagementGraph,
artifactManagementGraph);
}
else
{
contexts =
this.schemaContexts(ontologyID, managementConnection, schemaManagementGraph,
artifactManagementGraph);
}
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(tupleQuery, contexts);
String label = null;
String description = null;
String barcode = null;
for(final BindingSet next : queryResults.getBindingSets())
{
if(next.getValue("label") != null)
{
label = next.getValue("label").stringValue();
}
else
{
// Disabled this method as it produces worse than useless
// results for the typical
// URIs that end in /UUID/object, and "object" is literally the
// word "object" and is
// displayed as such.
// FIXME: This method may be worse than showing them a URI
// label = objectUri.getLocalName();
label = objectUri.stringValue();
}
if(next.getValue("description") != null)
{
description = next.getValue("description").stringValue();
}
if(next.getValue("barcode") != null)
{
barcode = next.getValue("barcode").stringValue();
}
}
return new PoddObjectLabelImpl(ontologyID, objectUri, label, description, barcode);
}
@Override
public Model getObjectTypeContainsMetadata(final URI objectType, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
final Model results = new LinkedHashModel();
if(objectType == null)
{
return results;
}
/*
* NOTE: This SPARQL query only finds properties defined as OWL restrictions in the given
* Object Type and its ancestors.
*/
final StringBuilder owlRestrictionQuery = new StringBuilder(1024);
owlRestrictionQuery.append("CONSTRUCT { ");
owlRestrictionQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + "> ?x . ");
owlRestrictionQuery.append(" ?x <" + RDF.TYPE.stringValue() + "> <" + OWL.RESTRICTION.stringValue() + "> . ");
owlRestrictionQuery.append(" ?x <" + OWL.ONPROPERTY.stringValue() + "> ?propertyUri . ");
owlRestrictionQuery.append(" ?x <" + OWL.ALLVALUESFROM.stringValue() + "> ?rangeClass . ");
owlRestrictionQuery.append(" ?x <http://www.w3.org/2002/07/owl#onClass> ?owlClass . ");
owlRestrictionQuery.append(" ?x <http://www.w3.org/2002/07/owl#onDataRange> ?valueRange . ");
owlRestrictionQuery.append(" ?propertyUri <" + RDFS.LABEL.stringValue() + "> ?propertyUriLabel . ");
owlRestrictionQuery.append(" ?rangeClass <" + RDFS.LABEL.stringValue() + "> ?rangeClassLabel . ");
owlRestrictionQuery.append("} WHERE {");
// TODO: The following seems to pick up restrictions that are put onto
// other types
owlRestrictionQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + ">+ ?x . ");
// owlRestrictionQuery.append(" ?objectType <" +
// RDFS.SUBCLASSOF.stringValue() + "> ?x . ");
owlRestrictionQuery.append(" ?x <" + RDF.TYPE.stringValue() + "> <" + OWL.RESTRICTION.stringValue() + "> . ");
owlRestrictionQuery.append(" ?x <" + OWL.ONPROPERTY.stringValue() + "> ?propertyUri . ");
owlRestrictionQuery.append(" OPTIONAL { ?x <" + OWL.ALLVALUESFROM.stringValue() + "> ?rangeClass } . ");
owlRestrictionQuery.append(" OPTIONAL { ?x <http://www.w3.org/2002/07/owl#onClass> ?owlClass } . ");
owlRestrictionQuery.append(" OPTIONAL { ?x <http://www.w3.org/2002/07/owl#onDataRange> ?valueRange } . ");
owlRestrictionQuery
.append(" OPTIONAL { ?propertyUri <" + RDFS.LABEL.stringValue() + "> ?propertyUriLabel } . ");
owlRestrictionQuery.append(" OPTIONAL { ?rangeClass <" + RDFS.LABEL.stringValue() + "> ?rangeClassLabel } . ");
// exclude doNotDisplay properties
owlRestrictionQuery.append(" FILTER NOT EXISTS { ?propertyUri <" + PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue()
+ "> true . } ");
// include only contains sub-properties
owlRestrictionQuery.append("FILTER EXISTS { ?propertyUri <" + RDFS.SUBPROPERTYOF.stringValue() + "> <"
+ PODD.PODD_BASE_CONTAINS.stringValue() + "> } ");
owlRestrictionQuery.append("}");
final String owlRestrictionQueryString = owlRestrictionQuery.toString();
final GraphQuery rdfsGraphQuery =
repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, owlRestrictionQueryString);
rdfsGraphQuery.setBinding("objectType", objectType);
this.log.debug("[getObjectTypeContainsMetadata] Created SPARQL {} \n with objectType bound to {}",
owlRestrictionQueryString, objectType);
final Model rdfsQueryResults = RdfUtility.executeGraphQuery(rdfsGraphQuery, contexts);
results.addAll(rdfsQueryResults);
this.log.debug("rdfsQueryResults ", rdfsQueryResults);
// this.log.info("{} Restrictions found", restrictions.size());
/*
* Find any sub-classes of the above ranges and include them also
*/
if(rdfsQueryResults.contains(null, RDF.TYPE, OWL.RESTRICTION))
{
final StringBuilder subRangeQuery = new StringBuilder(1024);
subRangeQuery.append("CONSTRUCT { ");
subRangeQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + "> _:x . ");
subRangeQuery.append(" _:x <" + RDF.TYPE.stringValue() + "> <" + OWL.RESTRICTION.stringValue() + "> . ");
subRangeQuery.append(" _:x <" + OWL.ONPROPERTY.stringValue() + "> ?propertyUri . ");
subRangeQuery.append(" _:x <" + OWL.ALLVALUESFROM.stringValue() + "> ?subRange . ");
subRangeQuery.append(" ?subRange <" + RDFS.LABEL.stringValue() + "> ?subRangeLabel . ");
subRangeQuery.append("} WHERE {");
subRangeQuery.append(" ?subRange <" + RDFS.SUBCLASSOF.stringValue() + ">+ ?rangeClass . ");
subRangeQuery.append(" OPTIONAL { ?subRange <" + RDFS.LABEL.stringValue() + "> ?subRangeLabel } . ");
subRangeQuery.append("}");
subRangeQuery.append(" VALUES (?rangeClass ?propertyUri ?objectType) { ");
for(final Value restriction : rdfsQueryResults.filter(null, RDF.TYPE, OWL.RESTRICTION).subjects())
{
if(restriction instanceof Resource)
{
final Resource onProperty =
rdfsQueryResults.filter((Resource)restriction, OWL.ONPROPERTY, null).objectResource();
final Resource onRange =
rdfsQueryResults.filter((Resource)restriction, OWL.ALLVALUESFROM, null).objectResource();
if(onProperty instanceof URI && onRange instanceof URI)
{
subRangeQuery.append(" ( ");
subRangeQuery.append(RenderUtils.getSPARQLQueryString(onRange));
subRangeQuery.append(" ");
subRangeQuery.append(RenderUtils.getSPARQLQueryString(onProperty));
subRangeQuery.append(" ");
subRangeQuery.append(RenderUtils.getSPARQLQueryString(objectType));
subRangeQuery.append(" ) ");
}
else
{
// Add warning... If we need to support blank nodes here
// we will need to
// switch to a different type of query, as SPARQL-1.1
// VALUES doesn't support
// blank nodes
this.log.warn("FIXME: restriction pointed to a non-URI property or allvaluesfrom : {} {} {}",
onProperty, onRange, objectType);
}
}
}
subRangeQuery.append(" } ");
final String subRangeQueryString = subRangeQuery.toString();
this.log.debug("[getObjectTypeContainsMetadata] Created SPARQL subRangeQueryString {}", subRangeQueryString);
final GraphQuery subRangeGraphQuery =
repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, subRangeQueryString);
// this.log.trace("Created SPARQL {} \n with rangeClass bound to {}",
// subRangeQueryString, restriction);
results.addAll(RdfUtility.executeGraphQuery(subRangeGraphQuery, contexts));
}
return results;
}
@Override
public Model getObjectTypeMetadata(final URI objectType, final boolean includeDoNotDisplayProperties,
final MetadataPolicy containsPropertyPolicy, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
final Model results = new LinkedHashModel();
if(objectType == null)
{
return results;
}
// - check if the objectType is known at all (i.e. exists somewhere in
// the graphs)
final boolean objectTypeExists =
repositoryConnection.getStatements(objectType, null, null, false, contexts).hasNext()
|| repositoryConnection.getStatements(null, null, objectType, false, contexts).hasNext();
if(!objectTypeExists)
{
this.log.info("Object type <{}> does not exist", objectType);
return results;
}
// - identify it as an owl:Class
results.add(objectType, RDF.TYPE, OWL.CLASS);
// - find all Properties and their ranges
final Set<Value> properties = new HashSet<Value>();
/*
* NOTE: This SPARQL query only finds properties defined as OWL restrictions in the given
* Object Type and its ancestors.
*/
final StringBuilder owlRestrictionQuery = new StringBuilder(1024);
owlRestrictionQuery.append("CONSTRUCT { ");
owlRestrictionQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + "> ?x . ");
owlRestrictionQuery.append(" ?x <" + RDF.TYPE.stringValue() + "> <" + OWL.RESTRICTION.stringValue() + "> . ");
owlRestrictionQuery.append(" ?x <" + OWL.ONPROPERTY.stringValue() + "> ?propertyUri . ");
owlRestrictionQuery.append(" ?x <" + OWL.ALLVALUESFROM.stringValue() + "> ?rangeClass . ");
owlRestrictionQuery.append(" ?x <http://www.w3.org/2002/07/owl#onClass> ?owlClass . ");
owlRestrictionQuery.append(" ?x <http://www.w3.org/2002/07/owl#onDataRange> ?valueRange . ");
owlRestrictionQuery.append("} WHERE {");
// TODO: The following seems to pick up restrictions that are put onto
// other types
owlRestrictionQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + ">+ ?x . ");
// owlRestrictionQuery.append(" ?objectType <" +
// RDFS.SUBCLASSOF.stringValue() + "> ?x . ");
owlRestrictionQuery.append(" ?x <" + RDF.TYPE.stringValue() + "> <" + OWL.RESTRICTION.stringValue() + "> . ");
owlRestrictionQuery.append(" ?x <" + OWL.ONPROPERTY.stringValue() + "> ?propertyUri . ");
owlRestrictionQuery.append(" OPTIONAL { ?x <" + OWL.ALLVALUESFROM.stringValue() + "> ?rangeClass } . ");
owlRestrictionQuery.append(" OPTIONAL { ?x <http://www.w3.org/2002/07/owl#onClass> ?owlClass } . ");
owlRestrictionQuery.append(" OPTIONAL { ?x <http://www.w3.org/2002/07/owl#onDataRange> ?valueRange } . ");
if(!includeDoNotDisplayProperties)
{
owlRestrictionQuery.append(" FILTER NOT EXISTS { ?propertyUri <"
+ PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue() + "> true . } ");
}
switch(containsPropertyPolicy)
{
case EXCLUDE_CONTAINS:
owlRestrictionQuery.append("FILTER NOT EXISTS { ?propertyUri <" + RDFS.SUBPROPERTYOF.stringValue()
+ "> <" + PODD.PODD_BASE_CONTAINS.stringValue() + "> } ");
break;
case ONLY_CONTAINS:
owlRestrictionQuery.append("FILTER EXISTS { ?propertyUri <" + RDFS.SUBPROPERTYOF.stringValue() + "> <"
+ PODD.PODD_BASE_CONTAINS.stringValue() + "> } ");
break;
default:
// ALL: do nothing. everything will be included
}
owlRestrictionQuery.append("}");
final String owlRestrictionQueryString = owlRestrictionQuery.toString();
final GraphQuery graphQuery =
repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, owlRestrictionQueryString);
graphQuery.setBinding("objectType", objectType);
this.log.trace("Created SPARQL {} \n with objectType bound to {}", owlRestrictionQueryString, objectType);
final Model restrictionQueryResults = RdfUtility.executeGraphQuery(graphQuery, contexts);
results.addAll(restrictionQueryResults);
this.log.debug("restrictionQueryResults {}", restrictionQueryResults);
properties.addAll(restrictionQueryResults.filter(null, OWL.ONPROPERTY, null).objects());
/*
* This query maps RDFS:Domain and RDFS:Range to OWL:Restriction/SubClassOf so that we get a
* homogeneous set of results.
*/
final StringBuilder rdfsQuery = new StringBuilder(1024);
rdfsQuery.append("CONSTRUCT { ");
rdfsQuery.append(" ?objectType <" + RDF.TYPE.stringValue() + "> <" + OWL.CLASS.stringValue() + "> . ");
rdfsQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + "> _:x . ");
rdfsQuery.append(" _:x <" + RDF.TYPE.stringValue() + "> <" + OWL.RESTRICTION.stringValue() + "> . ");
rdfsQuery.append(" _:x <" + OWL.ONPROPERTY.stringValue() + "> ?propertyUri . ");
rdfsQuery.append(" _:x <" + OWL.ALLVALUESFROM.stringValue() + "> ?rangeClass . ");
rdfsQuery.append("} WHERE {");
rdfsQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + ">* ?actualObjectType . ");
rdfsQuery.append(" ?propertyUri <" + RDFS.DOMAIN.stringValue() + "> ?actualObjectType . ");
rdfsQuery.append(" ?propertyUri <" + RDFS.RANGE.stringValue() + "> ?rangeClass . ");
if(!includeDoNotDisplayProperties)
{
rdfsQuery.append(" FILTER NOT EXISTS { ?propertyUri <" + PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue()
+ "> true . } ");
}
switch(containsPropertyPolicy)
{
case EXCLUDE_CONTAINS:
rdfsQuery.append("FILTER NOT EXISTS { ?propertyUri <" + RDFS.SUBPROPERTYOF.stringValue() + "> <"
+ PODD.PODD_BASE_CONTAINS.stringValue() + "> } ");
break;
case ONLY_CONTAINS:
rdfsQuery.append("FILTER EXISTS { ?propertyUri <" + RDFS.SUBPROPERTYOF.stringValue() + "> <"
+ PODD.PODD_BASE_CONTAINS.stringValue() + "> } ");
break;
default:
// do nothing. everything will be included
}
rdfsQuery.append("}");
final String rdfsQueryString = rdfsQuery.toString();
final GraphQuery rdfsGraphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, rdfsQueryString);
rdfsGraphQuery.setBinding("objectType", objectType);
this.log.trace("Created SPARQL {} \n with objectType bound to {}", rdfsQueryString, objectType);
final Model rdfsQueryResults = RdfUtility.executeGraphQuery(rdfsGraphQuery, contexts);
results.addAll(rdfsQueryResults);
this.log.debug("rdfsQueryResults {}", rdfsQueryResults);
properties.addAll(rdfsQueryResults.filter(null, OWL.ONPROPERTY, null).objects());
/*
* add statements for annotation properties RDFS:Label and RDFS:Comment
*/
if(containsPropertyPolicy != MetadataPolicy.ONLY_CONTAINS)
{
final URI[] commonAnnotationProperties = { RDFS.LABEL, RDFS.COMMENT };
final StringBuilder annotationQuery = new StringBuilder(1024);
annotationQuery.append("CONSTRUCT { ");
annotationQuery.append(" ?objectType <" + RDFS.SUBCLASSOF.stringValue() + "> _:x . ");
annotationQuery.append(" _:x <" + RDF.TYPE.stringValue() + "> <" + OWL.RESTRICTION.stringValue() + "> . ");
annotationQuery.append(" _:x <" + OWL.ONPROPERTY.stringValue() + "> ?annotationProperty . ");
annotationQuery.append(" _:x <" + OWL.ALLVALUESFROM.stringValue() + "> ?rangeClass . ");
annotationQuery.append("} WHERE {");
annotationQuery.append(" ?annotationProperty <" + RDFS.RANGE.stringValue() + "> ?rangeClass . ");
annotationQuery.append("}");
if(commonAnnotationProperties.length > 0)
{
annotationQuery.append(" VALUES (?annotationProperty) { ");
for(final URI nextAnnotationPropertyURI : commonAnnotationProperties)
{
annotationQuery.append(" ( ");
annotationQuery.append(RenderUtils.getSPARQLQueryString(nextAnnotationPropertyURI));
annotationQuery.append(" ) ");
}
annotationQuery.append(" } ");
}
final String annotationQueryString = annotationQuery.toString();
this.log.trace("Created SPARQL annotationQuery {} ", annotationQuery);
final GraphQuery annotationGraphQuery =
repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, annotationQueryString);
annotationGraphQuery.setBinding("objectType", objectType);
final Model annotationQueryResults = RdfUtility.executeGraphQuery(annotationGraphQuery, contexts);
this.log.debug("annotationQueryResults {}", annotationQueryResults);
results.addAll(annotationQueryResults);
properties.addAll(annotationQueryResults.filter(null, OWL.ONPROPERTY, null).objects());
}
final Set<URI> propertyUris = new LinkedHashSet<>();
for(final Value property : properties)
{
if(property instanceof URI)
{
propertyUris.add((URI)property);
}
}
// -- for each property, get meta-data about it
if(!propertyUris.isEmpty())
{
final StringBuilder sb2 = new StringBuilder(1024);
sb2.append("CONSTRUCT { ");
sb2.append(" ?propertyUri <" + RDF.TYPE.stringValue() + "> ?propertyType . ");
sb2.append(" ?propertyUri <" + RDFS.LABEL.stringValue() + "> ?propertyLabel . ");
sb2.append(" ?propertyUri <" + PODD.PODD_BASE_DISPLAY_TYPE.stringValue() + "> ?propertyDisplayType . ");
sb2.append(" ?propertyUri <" + PODD.PODD_BASE_WEIGHT.stringValue() + "> ?propertyWeight . ");
sb2.append(" ?propertyUri <" + PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue() + "> ?propertyDoNotDisplay . ");
sb2.append("} WHERE {");
sb2.append(" ?propertyUri <" + RDF.TYPE.stringValue() + "> ?propertyType . ");
sb2.append(" OPTIONAL {?propertyUri <" + PODD.PODD_BASE_DISPLAY_TYPE.stringValue()
+ "> ?propertyDisplayType . } ");
sb2.append(" OPTIONAL {?propertyUri <" + RDFS.LABEL.stringValue() + "> ?propertyLabel . } ");
sb2.append(" OPTIONAL {?propertyUri <" + PODD.PODD_BASE_WEIGHT.stringValue() + "> ?propertyWeight . } ");
if(includeDoNotDisplayProperties)
{
sb2.append(" OPTIONAL { ?propertyUri <" + PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue()
+ "> ?propertyDoNotDisplay . } ");
}
sb2.append("}");
sb2.append(" VALUES (?propertyUri) { ");
for(final URI nextProperty : propertyUris)
{
sb2.append(" ( ");
sb2.append(RenderUtils.getSPARQLQueryString(nextProperty));
sb2.append(" ) ");
}
sb2.append(" } ");
final String sb2String = sb2.toString();
this.log.trace("Created SPARQL get metaData for properties {} ", sb2);
final GraphQuery graphQuery2 = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sb2String);
final Model queryResults2 = RdfUtility.executeGraphQuery(graphQuery2, contexts);
this.log.debug("SPARQL get metaData for properties result {}", queryResults2);
results.addAll(queryResults2);
}
// - add cardinality value
final Map<URI, URI> cardinalityValues =
this.getCardinalityValues(objectType, propertyUris, true, repositoryConnection, contexts);
for(final URI nextProperty : propertyUris)
{
URI cardinalityValue = null;
if(cardinalityValues.containsKey(nextProperty))
{
cardinalityValue = cardinalityValues.get(nextProperty);
}
if(cardinalityValue != null)
{
results.add(nextProperty, PODD.PODD_BASE_HAS_CARDINALITY, cardinalityValue);
}
else if(nextProperty.equals(RDFS.LABEL))
{
results.add(nextProperty, PODD.PODD_BASE_HAS_CARDINALITY, PODD.PODD_BASE_CARDINALITY_EXACTLY_ONE);
}
}
final Collection<URI> nextRangeTypeURIs = new LinkedHashSet<>();
for(final URI property : propertyUris)
{
// - find property: type (e.g. object/datatype/annotation), label,
// display-type,
// weight
// graphQuery2.setBinding("propertyUri", property);
// this.log.trace("Created SPARQL {} \n with propertyUri bound to {}",
// sb2String,
// property);
// --- for 'drop-down' type properties, add all possible options
// into Model
if(results.contains(property, PODD.PODD_BASE_DISPLAY_TYPE, PODD.PODD_BASE_DISPLAY_TYPE_DROPDOWN))
{
for(final Resource nextRestriction : results.filter(null, OWL.ONPROPERTY, property).subjects())
{
Set<Value> nextRangeTypes = results.filter(nextRestriction, OWL.ALLVALUESFROM, null).objects();
if(nextRangeTypes.isEmpty())
{
// see if restriction exists with owl:onClass
// TODO: Add OWL.ONCLASS to Sesame vocabulary
nextRangeTypes =
results.filter(nextRestriction,
PODD.VF.createURI("http://www.w3.org/2002/07/owl#onClass"), null).objects();
}
for(final Value nextRangeType : nextRangeTypes)
{
if(nextRangeType instanceof URI)
{
nextRangeTypeURIs.add((URI)nextRangeType);
}
else
{
this.log.warn("Restriction was on a class that did not have a URI: property={}", property);
}
}
}
}
}
results.addAll(this.getInstancesOf(nextRangeTypeURIs, repositoryConnection, contexts));
this.log.debug("Results Metadata {} ", results);
return results;
}
/**
* Retrieves the most specific types of the given object as a List of URIs.
*
* The contexts searched in are, the given ongology's asserted and inferred graphs as well as
* their imported schema ontology graphs.
*
* This method depends on the poddBase:doNotDisplay annotation to filter out unwanted
* super-types.
*
* @param ontologyID
* The artifact to which the object belongs
* @param objectUri
* The object whose type is to be determined
* @param permanentConnection
* @param artifactManagementGraph
* @return A list of URIs for the identified object Types
* @throws OpenRDFException
* @throws SchemaManifestException
* @throws UnmanagedSchemaIRIException
*/
@Override
public List<URI> getObjectTypes(final InferredOWLOntologyID ontologyID, final URI objectUri,
final RepositoryConnection managementConnection, final RepositoryConnection permanentConnection,
final URI schemaManagementGraph, final URI artifactManagementGraph) throws OpenRDFException,
SchemaManifestException, UnmanagedSchemaIRIException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?poddTypeUri ");
sb.append(" WHERE { ");
sb.append(" ?objectUri <" + RDF.TYPE + "> ?poddTypeUri . ");
sb.append(" FILTER NOT EXISTS { ?poddTypeUri <" + PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue() + "> true } ");
sb.append(" FILTER isIRI(?poddTypeUri) ");
// filter out TYPE statements for OWL:Thing, OWL:Individual,
// OWL:NamedIndividual & OWL:Class
sb.append("FILTER (?poddTypeUri != <" + OWL.THING.stringValue() + ">) ");
sb.append("FILTER (?poddTypeUri != <" + OWL.INDIVIDUAL.stringValue() + ">) ");
sb.append("FILTER (?poddTypeUri != <http://www.w3.org/2002/07/owl#NamedIndividual>) ");
sb.append("FILTER (?poddTypeUri != <" + OWL.CLASS.stringValue() + ">) ");
sb.append(" }");
this.log.trace("Created SPARQL {} with objectUri bound to {}", sb, objectUri);
final TupleQuery tupleQuery = permanentConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
tupleQuery.setBinding("objectUri", objectUri);
final QueryResultCollector queryResults =
RdfUtility.executeTupleQuery(tupleQuery, this.versionAndSchemaContexts(ontologyID,
managementConnection, schemaManagementGraph, artifactManagementGraph));
final List<URI> results = new ArrayList<URI>(queryResults.getBindingSets().size());
for(final BindingSet next : queryResults.getBindingSets())
{
results.add((URI)next.getValue("poddTypeUri"));
}
return results;
}
@Override
public Collection<InferredOWLOntologyID> getOntologies(final boolean onlyCurrentVersions,
final RepositoryConnection repositoryConnection, final URI ontologyManagementGraph) throws OpenRDFException
{
final List<InferredOWLOntologyID> returnList = new ArrayList<InferredOWLOntologyID>();
final DatasetImpl dataset = new DatasetImpl();
dataset.addDefaultGraph(ontologyManagementGraph);
dataset.addNamedGraph(ontologyManagementGraph);
// 1: see if the given IRI exists as an ontology IRI
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT ?ontology ?version ?inferredVersion WHERE { ?ontology ");
sb.append(RenderUtils.getSPARQLQueryString(RDF.TYPE));
sb.append(" ");
sb.append(RenderUtils.getSPARQLQueryString(OWL.ONTOLOGY));
sb.append(" . ");
if(onlyCurrentVersions)
{
sb.append(" ?ontology ");
sb.append(RenderUtils.getSPARQLQueryString(PODD.OMV_CURRENT_VERSION));
sb.append(" ?version . ");
}
else
{
sb.append(" ?ontology ");
sb.append(RenderUtils.getSPARQLQueryString(OWL.VERSIONIRI));
sb.append(" ?version . ");
}
sb.append("OPTIONAL{ ?version ");
sb.append(RenderUtils.getSPARQLQueryString(PODD.PODD_BASE_INFERRED_VERSION));
sb.append(" ?inferredVersion . ");
sb.append(" }");
sb.append("}");
this.log.debug("Generated SPARQL {}", sb);
final TupleQuery query1 = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
query1.setDataset(dataset);
final TupleQueryResult query1Results = query1.evaluate();
final QueryResultCollector nextResults1 = new QueryResultCollector();
QueryResults.report(query1Results, nextResults1);
for(final BindingSet nextResult : nextResults1.getBindingSets())
{
final String nextOntologyIRI = nextResult.getValue("ontology").stringValue();
final String nextVersionIRI = nextResult.getValue("version").stringValue();
String nextInferredIRI = null;
if(nextResult.hasBinding("inferredVersion"))
{
nextInferredIRI = nextResult.getValue("inferredVersion").stringValue();
returnList.add(new InferredOWLOntologyID(IRI.create(nextOntologyIRI), IRI.create(nextVersionIRI), IRI
.create(nextInferredIRI)));
}
else
{
returnList
.add(new InferredOWLOntologyID(IRI.create(nextOntologyIRI), IRI.create(nextVersionIRI), null));
}
}
return returnList;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getOntologyIRI(org.openrdf.repository
* .RepositoryConnection , org.openrdf.model.URI)
*/
@Override
public IRI getOntologyIRI(final RepositoryConnection repositoryConnection, final URI context)
throws OpenRDFException
{
// get ontology IRI from the RepositoryConnection using a SPARQL SELECT
// query
final String sparqlQuery =
"SELECT ?nextOntology WHERE { ?nextOntology <" + RDF.TYPE + "> <" + OWL.ONTOLOGY.stringValue()
+ "> . " + " ?nextOntology <" + PODD.PODD_BASE_HAS_TOP_OBJECT + "> ?y " + " }";
this.log.debug("Generated SPARQL {}", sparqlQuery);
final TupleQuery query = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sparqlQuery);
final DatasetImpl dataset = new DatasetImpl();
dataset.addDefaultGraph(context);
dataset.addNamedGraph(context);
query.setDataset(dataset);
IRI ontologyIRI = null;
final TupleQueryResult queryResults = query.evaluate();
if(queryResults.hasNext())
{
final BindingSet nextResult = queryResults.next();
final Value nextOntology = nextResult.getValue("nextOntology");
if(nextOntology instanceof URI)
{
ontologyIRI = IRI.create(nextOntology.stringValue());
}
else
{
ontologyIRI = IRI.create("_:" + nextOntology.stringValue());
}
}
return ontologyIRI;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getOntologyVersion(org.semanticweb
* .owlapi.model.IRI, org.openrdf.repository.RepositoryConnection, org.openrdf.model.URI)
*/
@Override
public InferredOWLOntologyID getOntologyVersion(final IRI versionIRI,
final RepositoryConnection repositoryConnection, final URI managementGraph) throws OpenRDFException
{
final DatasetImpl dataset = new DatasetImpl();
dataset.addDefaultGraph(managementGraph);
// see if the given IRI exists as a version IRI
final StringBuilder sb2 = new StringBuilder(1024);
sb2.append("SELECT ?ontologyIri ?inferredIri WHERE { ");
sb2.append(" ?ontologyIri <" + RDF.TYPE.stringValue() + "> <" + OWL.ONTOLOGY.stringValue() + "> . ");
sb2.append(" ?ontologyIri <" + OWL.VERSIONIRI.stringValue() + "> ?versionIri . ");
sb2.append(" OPTIONAL { ?versionIri <" + PODD.PODD_BASE_INFERRED_VERSION.stringValue() + "> ?inferredIri . } ");
sb2.append(" }");
this.log.trace("Generated SPARQL {} with versionIri bound to <{}>", sb2, versionIRI);
final TupleQuery query = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb2.toString());
query.setBinding("versionIri", versionIRI.toOpenRDFURI());
query.setDataset(dataset);
final TupleQueryResult queryResults = query.evaluate();
final QueryResultCollector resultsCollector = new QueryResultCollector();
QueryResults.report(queryResults, resultsCollector);
for(final BindingSet nextResult : resultsCollector.getBindingSets())
{
final URI nextOntologyIRI = (URI)nextResult.getValue("ontologyIri");
IRI nextInferredIRI = null;
if(nextResult.hasBinding("inferredIri"))
{
nextInferredIRI = IRI.create((URI)nextResult.getValue("inferredIri"));
}
// return the first solution since there should only be only one
// result
return new InferredOWLOntologyID(IRI.create(nextOntologyIRI), versionIRI, nextInferredIRI);
}
// could not find given IRI as a version IRI
return null;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getParentDetails(org.openrdf.model .URI,
* org.openrdf.repository.RepositoryConnection, org.openrdf.model.URI...)
*/
@Override
public Model getParentDetails(final URI objectUri, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
if(objectUri == null)
{
return new LinkedHashModel();
}
final StringBuilder sb = new StringBuilder(1024);
sb.append("CONSTRUCT { ");
sb.append(" ?parent ?parentChildProperty ?poddObject ");
sb.append("} WHERE {");
sb.append(" ?parent ?parentChildProperty ?poddObject . ");
sb.append(" ?parentChildProperty <" + RDFS.SUBPROPERTYOF.stringValue() + "> <"
+ PODD.PODD_BASE_CONTAINS.stringValue() + "> . ");
sb.append("}");
final GraphQuery graphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sb.toString());
graphQuery.setBinding("poddObject", objectUri);
this.log.trace("Created SPARQL {} \n with poddObject bound to {}", sb, objectUri);
return RdfUtility.executeGraphQuery(graphQuery, contexts);
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getReferringObjectDetails(org.openrdf .model.URI,
* org.openrdf.repository.RepositoryConnection, org.openrdf.model.URI...)
*/
@Override
public Model getReferringObjectDetails(final URI objectUri, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
if(objectUri == null)
{
return new LinkedHashModel();
}
final StringBuilder sb = new StringBuilder(1024);
sb.append("CONSTRUCT { ");
sb.append(" ?referrer ?refersToProperty ?poddObject ");
sb.append("} WHERE {");
sb.append(" ?referrer ?refersToProperty ?poddObject . ");
sb.append(" ?refersToProperty <" + RDFS.SUBPROPERTYOF.stringValue() + "> <"
+ PODD.PODD_BASE_REFERS_TO.stringValue() + "> . ");
sb.append("}");
final GraphQuery graphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sb.toString());
graphQuery.setBinding("poddObject", objectUri);
this.log.trace("Created SPARQL {} \n with poddObject bound to {}", sb, objectUri);
return RdfUtility.executeGraphQuery(graphQuery, contexts);
}
@Override
public InferredOWLOntologyID getSchemaVersion(final IRI schemaVersionIRI,
final RepositoryConnection repositoryConnection, final URI schemaManagementGraph) throws OpenRDFException,
UnmanagedSchemaIRIException
{
final InferredOWLOntologyID ontologyID =
this.getOntologyVersion(schemaVersionIRI, repositoryConnection, schemaManagementGraph);
if(ontologyID != null)
{
return ontologyID;
}
else
{
// not a version IRI, return the current schema version
return this.getCurrentSchemaVersion(schemaVersionIRI, repositoryConnection, schemaManagementGraph);
}
}
/**
* Internal helper method to retrieve the Top-Object IRI for a given ontology.
*
*/
@Override
public URI getTopObjectIRI(final InferredOWLOntologyID ontologyIRI, final RepositoryConnection repositoryConnection)
throws OpenRDFException
{
final List<URI> results = this.getTopObjects(ontologyIRI, repositoryConnection);
if(results.isEmpty())
{
return null;
}
else if(results.size() == 1)
{
return results.get(0);
}
else
{
this.log.warn("More than one top object found: {}", ontologyIRI.getOntologyIRI());
return results.get(0);
}
}
/**
* Retrieve a list of Top Objects that are contained in the given ontology.
*
* @param repositoryConnection
* @param contexts
* @return
* @throws OpenRDFException
*/
@Override
public List<URI> getTopObjects(final InferredOWLOntologyID ontologyID,
final RepositoryConnection repositoryConnection) throws OpenRDFException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?topObjectUri ");
sb.append(" WHERE { ");
sb.append(" ?artifactUri <" + PODD.PODD_BASE_HAS_TOP_OBJECT.stringValue() + "> ?topObjectUri . \n");
sb.append(" }");
final TupleQuery query = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
query.setBinding("artifactUri", ontologyID.getOntologyIRI().toOpenRDFURI());
final QueryResultCollector queryResults =
RdfUtility.executeTupleQuery(query, this.versionAndInferredContexts(ontologyID));
final List<URI> topObjectList = new ArrayList<URI>();
for(final BindingSet next : queryResults.getBindingSets())
{
final URI pred = (URI)next.getValue("topObjectUri");
topObjectList.add(pred);
}
return topObjectList;
}
/*
* (non-Javadoc)
*
* @see com.github.podd.api.PoddSesameManager#getWeightedProperties(com.github .podd.utils.
* InferredOWLOntologyID, org.openrdf.model.URI, boolean,
* org.openrdf.repository.RepositoryConnection)
*/
@Override
public List<URI> getWeightedProperties(final URI objectUri, final boolean excludeContainsProperties,
final RepositoryConnection repositoryConnection, final URI... contexts) throws OpenRDFException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("SELECT DISTINCT ?propertyUri ");
sb.append(" WHERE { ");
sb.append(" ?poddObject ?propertyUri ?value . ");
// for ORDER BY
sb.append(" OPTIONAL { ?propertyUri <" + RDFS.LABEL.stringValue() + "> ?propertyLabel } . ");
// for ORDER BY
sb.append("OPTIONAL { ?propertyUri <" + PODD.PODD_BASE_WEIGHT.stringValue() + "> ?weight } . ");
sb.append("FILTER (?value != <" + OWL.THING.stringValue() + ">) ");
sb.append("FILTER (?value != <" + OWL.INDIVIDUAL.stringValue() + ">) ");
sb.append("FILTER (?value != <http://www.w3.org/2002/07/owl#NamedIndividual>) ");
sb.append("FILTER (?value != <" + OWL.CLASS.stringValue() + ">) ");
// Exclude as TYPE, Label (title) and Comment (description) are
// displayed separately
sb.append("FILTER (?propertyUri != <" + RDF.TYPE.stringValue() + ">) ");
sb.append("FILTER (?propertyUri != <" + RDFS.LABEL.stringValue() + ">) ");
sb.append("FILTER (?propertyUri != <" + RDFS.COMMENT.stringValue() + ">) ");
if(excludeContainsProperties)
{
sb.append("FILTER NOT EXISTS { ?propertyUri <" + RDFS.SUBPROPERTYOF.stringValue() + "> <"
+ PODD.PODD_BASE_CONTAINS.stringValue() + "> } ");
}
sb.append(" FILTER NOT EXISTS { ?propertyUri <" + PODD.PODD_BASE_DO_NOT_DISPLAY.stringValue() + "> true } ");
sb.append(" } ");
sb.append(" ORDER BY ASC(xsd:integer(?weight)) ASC(?propertyLabel) ");
this.log.trace("Created SPARQL {} with poddObject bound to {}", sb, objectUri);
final TupleQuery tupleQuery = repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sb.toString());
tupleQuery.setBinding("poddObject", objectUri);
final QueryResultCollector queryResults = RdfUtility.executeTupleQuery(tupleQuery, contexts);
// this.versionAndSchemaContexts(artifactID, repositoryConnection, c));
final List<URI> resultList = new ArrayList<URI>();
for(final BindingSet next : queryResults.getBindingSets())
{
final Value property = next.getValue("propertyUri");
if(property instanceof URI)
{
resultList.add((URI)property);
}
}
return resultList;
}
/**
* Given an artifact, this method evaluates whether all Objects within the artifact are
* connected to the Top Object.
*
* @param inputStream
* Input stream containing the artifact statements
* @param format
* The RDF format in which the statements are provided
* @return True if the artifact is structurally valid, false otherwise
*/
public boolean isConnectedStructure(final InputStream inputStream, RDFFormat format)
{
if(inputStream == null)
{
throw new NullPointerException("Input stream must not be null");
}
if(format == null)
{
format = RDFFormat.RDFXML;
}
final URI context = ValueFactoryImpl.getInstance().createURI("urn:concrete:random");
Repository tempRepository = null;
RepositoryConnection connection = null;
try
{
// create a temporary in-memory repository
tempRepository = new SailRepository(new MemoryStore());
tempRepository.initialize();
connection = tempRepository.getConnection();
connection.begin();
// load artifact statements into repository
connection.add(inputStream, "", format, context);
// DebugUtils.printContents(connection, context);
return this.isConnectedStructure(connection, context);
}
catch(final Exception e)
{
// better to throw an exception containing error details
this.log.error("An exception in checking connectedness of artifact", e);
return false;
}
finally
{
try
{
if(connection != null && connection.isOpen())
{
connection.rollback();
connection.close();
}
if(tempRepository != null)
{
tempRepository.shutDown();
}
}
catch(final Exception e)
{
this.log.error("Exception while releasing resources", e);
}
}
}
/**
* Given an artifact, this method evaluates whether all Objects within the artifact are
* connected to the Top Object.
*
* @param connection
* The RepositoryConnection
* @param context
* The Context within the RepositoryConnection.
* @return True if all internal objects are connected to the top object, false otherwise.
* @throws RepositoryException
*/
public boolean isConnectedStructure(final RepositoryConnection connection, final URI... context)
throws RepositoryException
{
// - find artifact and top object URIs
final List<Statement> topObjects =
Iterations.asList(connection.getStatements(null, PODD.PODD_BASE_HAS_TOP_OBJECT, null, false, context));
if(topObjects.size() != 1)
{
this.log.info("Artifact should have exactly 1 Top Object");
return false;
}
final URI artifactUri = (URI)topObjects.get(0).getSubject();
final Set<URI> disconnectedNodes = RdfUtility.findDisconnectedNodes(artifactUri, connection, context);
if(disconnectedNodes == null || disconnectedNodes.isEmpty())
{
return true;
}
else
{
return false;
}
}
@Override
public boolean isPublished(final InferredOWLOntologyID ontologyID, final RepositoryConnection repositoryConnection,
final URI managementGraph) throws OpenRDFException
{
if(ontologyID == null || ontologyID.getOntologyIRI() == null || ontologyID.getVersionIRI() == null)
{
throw new NullPointerException("OWLOntology is incomplete");
}
final URI artifactGraphUri = ontologyID.getVersionIRI().toOpenRDFURI();
/*
* ASK {
*
* ?artifact owl:versionIRI ontology-version .
*
* ?artifact poddBase:hasTopObject ?top .
*
* ?top poddBase:hasPublicationStatus poddBase:Published .
*
* }
*/
// final String sparqlQueryString =
// "?artifact <" + PoddRdfConstants.OWL_VERSION_IRI.stringValue() + "> "
// + ontologyID.getVersionIRI().toQuotedString() + " . " + "?artifact <"
// + PoddRdfConstants.PODD_BASE_HAS_TOP_OBJECT.stringValue() +
// "> ?top ." + " ?top <"
// + PoddRdfConstants.PODD_BASE_HAS_PUBLICATION_STATUS.stringValue() +
// "> <"
// + PoddRdfConstants.PODD_BASE_PUBLISHED.stringValue() + ">" + " }";
final StringBuilder sparqlQuery = new StringBuilder(1024);
sparqlQuery.append("ASK { ");
sparqlQuery.append(" ?artifact ").append(RenderUtils.getSPARQLQueryString(OWL.VERSIONIRI)).append(" ");
sparqlQuery.append(RenderUtils.getSPARQLQueryString(ontologyID.getVersionIRI().toOpenRDFURI()));
sparqlQuery.append(" . ");
sparqlQuery.append(" ?artifact ").append(
RenderUtils.getSPARQLQueryString(PODD.PODD_BASE_HAS_PUBLICATION_STATUS));
sparqlQuery.append(" ");
sparqlQuery.append(RenderUtils.getSPARQLQueryString(PODD.PODD_BASE_PUBLISHED));
sparqlQuery.append(" . ");
sparqlQuery.append(" } ");
this.log.debug("Generated SPARQL {}", sparqlQuery);
final BooleanQuery booleanQuery =
repositoryConnection.prepareBooleanQuery(QueryLanguage.SPARQL, sparqlQuery.toString());
// Create a dataset to specify the contexts
final DatasetImpl dataset = new DatasetImpl();
dataset.addDefaultGraph(managementGraph);
dataset.addNamedGraph(managementGraph);
booleanQuery.setDataset(dataset);
return booleanQuery.evaluate();
}
@Override
public Model searchOntologyLabels(final String searchTerm, final URI[] searchTypes, final int limit,
final int offset, final RepositoryConnection repositoryConnection, final URI... contexts)
throws OpenRDFException
{
final StringBuilder sb = new StringBuilder(1024);
sb.append("CONSTRUCT { ");
sb.append(" ?uri <" + RDFS.LABEL.stringValue() + "> ?label ");
sb.append(" } WHERE { ");
// limit the "types" of objects to search for
if(searchTypes != null)
{
for(final URI type : searchTypes)
{
sb.append(" ?uri a <" + type.stringValue() + "> . ");
// sb.append(" ?uri a ?type . ");
// sb.append(" ?type rdfs:subClassOf+ <" + type.stringValue() +
// "> . ");
}
}
sb.append(" ?uri <" + RDFS.LABEL.stringValue() + "> ?label . ");
// filter for "searchTerm" in label
sb.append(" FILTER(CONTAINS( LCASE(STR(?label)) , LCASE(?searchTerm) )) ");
sb.append(" } LIMIT ");
sb.append(limit);
sb.append(" OFFSET ");
sb.append(offset);
final GraphQuery graphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sb.toString());
graphQuery.setBinding("searchTerm", PODD.VF.createLiteral(searchTerm));
this.log.trace("Created SPARQL {} with searchTerm bound to '{}' ", sb, searchTerm);
final Model queryResults = RdfUtility.executeGraphQuery(graphQuery, contexts);
return queryResults;
}
@Override
public InferredOWLOntologyID setPublished(final boolean wantToPublish, final InferredOWLOntologyID ontologyID,
final RepositoryConnection repositoryConnection, final URI artifactManagementGraph) throws OpenRDFException
{
boolean changeRequired = false;
if(wantToPublish)
{
if(!repositoryConnection.hasStatement(ontologyID.getOntologyIRI().toOpenRDFURI(),
PODD.PODD_BASE_HAS_PUBLICATION_STATUS, PODD.PODD_BASE_PUBLISHED, false, artifactManagementGraph))
{
changeRequired = true;
}
}
else
{
if(!repositoryConnection
.hasStatement(ontologyID.getOntologyIRI().toOpenRDFURI(), PODD.PODD_BASE_HAS_PUBLICATION_STATUS,
PODD.PODD_BASE_NOT_PUBLISHED, false, artifactManagementGraph))
{
changeRequired = true;
}
}
if(!changeRequired)
{
return ontologyID;
}
else if(wantToPublish)
{
// remove previous value for publication status
repositoryConnection.remove(ontologyID.getOntologyIRI().toOpenRDFURI(),
PODD.PODD_BASE_HAS_PUBLICATION_STATUS, null, artifactManagementGraph);
// then insert the publication status as #Published
repositoryConnection.add(ontologyID.getOntologyIRI().toOpenRDFURI(), PODD.PODD_BASE_HAS_PUBLICATION_STATUS,
PODD.PODD_BASE_PUBLISHED, artifactManagementGraph);
this.log.info("{} was set as Published", ontologyID.getOntologyIRI().toOpenRDFURI());
}
else
{
// remove previous value for publication status
repositoryConnection.remove(ontologyID.getOntologyIRI().toOpenRDFURI(),
PODD.PODD_BASE_HAS_PUBLICATION_STATUS, null, artifactManagementGraph);
this.updateManagedPoddArtifactVersion(ontologyID, true, repositoryConnection, artifactManagementGraph);
// then insert the publication status as #NotPublished
repositoryConnection.add(ontologyID.getOntologyIRI().toOpenRDFURI(), PODD.PODD_BASE_HAS_PUBLICATION_STATUS,
PODD.PODD_BASE_NOT_PUBLISHED, artifactManagementGraph);
this.log.info("{} was set as Unpublished", ontologyID.getOntologyIRI().toOpenRDFURI());
}
return ontologyID;
}
@Override
public void updateManagedSchemaOntologyVersion(final OWLOntologyID nextOntologyID, final boolean updateCurrent,
final RepositoryConnection repositoryConnection, final URI context) throws OpenRDFException
{
final URI nextOntologyUri = nextOntologyID.getOntologyIRI().toOpenRDFURI();
final URI nextVersionUri = nextOntologyID.getVersionIRI().toOpenRDFURI();
// NOTE: The version is not used for the inferred ontology ID. A new ontology URI must be
// generated for each new inferred ontology generation. For reference though, the version is
// equal to the ontology IRI in the prototype code. See generateInferredOntologyID method
// for the corresponding code.
// type the ontology
repositoryConnection.add(nextOntologyUri, RDF.TYPE, OWL.ONTOLOGY, context);
// type the version
repositoryConnection.add(nextVersionUri, RDF.TYPE, OWL.ONTOLOGY, context);
// setup a version number link for this version
repositoryConnection.add(nextOntologyUri, OWL.VERSIONIRI, nextVersionUri, context);
final List<Statement> currentVersions =
Iterations.asList(repositoryConnection.getStatements(nextOntologyUri, PODD.OMV_CURRENT_VERSION, null,
false, context));
// If there are no current versions, or we must update the current version, then do it here
if(currentVersions.isEmpty() || updateCurrent)
{
// remove whatever was previously there for the current version marker
repositoryConnection.remove(nextOntologyUri, PODD.OMV_CURRENT_VERSION, null, context);
// then insert the new current version marker
repositoryConnection.add(nextOntologyUri, PODD.OMV_CURRENT_VERSION, nextVersionUri, context);
}
if(nextOntologyID instanceof InferredOWLOntologyID
&& ((InferredOWLOntologyID)nextOntologyID).getInferredOntologyIRI() != null)
{
final URI nextInferredOntologyUri =
((InferredOWLOntologyID)nextOntologyID).getInferredOntologyIRI().toOpenRDFURI();
// then do a similar process with the inferred axioms ontology
repositoryConnection.add(nextInferredOntologyUri, RDF.TYPE, OWL.ONTOLOGY, context);
// link from the ontology version IRI to the matching inferred axioms
// ontology version
repositoryConnection.add(nextVersionUri, PODD.PODD_BASE_INFERRED_VERSION, nextInferredOntologyUri, context);
}
// remove deprecated current inferred version marker
// Deprecated in favour of just tracking the podd base inferred version, see below
// TODO: Add this to migration scripts when they are active
repositoryConnection.remove(nextOntologyUri, PODD.VF.createURI(PODD.PODD_BASE, "currentInferredVersion"), null,
context);
}
@Override
public void updateManagedPoddArtifactVersion(final InferredOWLOntologyID nextOntologyID,
final boolean updateCurrentAndDeletePrevious, final RepositoryConnection repositoryConnection,
final URI managementGraph) throws OpenRDFException
{
final URI nextOntologyUri = nextOntologyID.getOntologyIRI().toOpenRDFURI();
final URI nextVersionUri = nextOntologyID.getVersionIRI().toOpenRDFURI();
// NOTE: The version is not used for the inferred ontology ID. A new ontology URI must be
// generated for each new inferred ontology generation. For reference though, the version is
// equal to the ontology IRI in the prototype code. See generateInferredOntologyID method
// for the corresponding code.
final URI nextInferredOntologyUri = nextOntologyID.getInferredOntologyIRI().toOpenRDFURI();
final List<InferredOWLOntologyID> allOntologyVersions =
this.getAllOntologyVersions(nextOntologyID.getOntologyIRI(), repositoryConnection, managementGraph);
// type the ontology
repositoryConnection.add(nextOntologyUri, RDF.TYPE, OWL.ONTOLOGY, managementGraph);
// type the version of the ontology
repositoryConnection.add(nextVersionUri, RDF.TYPE, OWL.ONTOLOGY, managementGraph);
// type the inferred ontology
repositoryConnection.add(nextInferredOntologyUri, RDF.TYPE, OWL.ONTOLOGY, managementGraph);
// type the ontology
repositoryConnection.add(nextOntologyUri, RDF.TYPE, OWL.ONTOLOGY, managementGraph);
// type the version of the ontology
repositoryConnection.add(nextVersionUri, RDF.TYPE, OWL.ONTOLOGY, managementGraph);
// type the inferred ontology
repositoryConnection.add(nextInferredOntologyUri, RDF.TYPE, OWL.ONTOLOGY, managementGraph);
// If there are no current versions then the steps are relatively simple
if(allOntologyVersions.isEmpty())
{
// then insert the new current version marker
repositoryConnection.add(nextOntologyUri, PODD.OMV_CURRENT_VERSION, nextVersionUri, managementGraph);
// link from the ontology IRI to the current inferred axioms
// ontology version
// repositoryConnection.add(nextOntologyUri, PODD.PODD_BASE_CURRENT_INFERRED_VERSION,
// nextInferredOntologyUri,
// managementGraph);
// setup a version number link for this version
repositoryConnection.add(nextOntologyUri, OWL.VERSIONIRI, nextVersionUri, managementGraph);
// link from the ontology version IRI to the matching inferred
// axioms ontology version
repositoryConnection.add(nextVersionUri, PODD.PODD_BASE_INFERRED_VERSION, nextInferredOntologyUri,
managementGraph);
}
else
{
// else, do find and replace to add the version into the system
// Update the current version and cleanup previous versions
if(updateCurrentAndDeletePrevious)
{
// remove the content of any contexts that are the object of
// versionIRI statements
final List<Statement> previousVersions =
Iterations.asList(repositoryConnection.getStatements(nextOntologyUri, OWL.VERSIONIRI, null,
true, managementGraph));
for(final Statement nextPreviousVersion : previousVersions)
{
if(nextPreviousVersion.getObject() instanceof URI)
{
final List<Statement> previousInferredVersions =
Iterations.asList(repositoryConnection.getStatements(
(URI)nextPreviousVersion.getObject(), PODD.PODD_BASE_INFERRED_VERSION, null,
false, managementGraph));
for(final Statement nextInferredVersion : previousInferredVersions)
{
if(nextInferredVersion.getObject() instanceof URI)
{
// clear inferred statements for previous inferred version
repositoryConnection.clear((URI)nextInferredVersion.getObject());
// remove all references from artifact management graph
repositoryConnection.remove((URI)nextInferredVersion.getObject(), null, null,
managementGraph);
}
else
{
this.log.error("Found inferred version IRI that was not a URI: {}", nextInferredVersion);
}
}
repositoryConnection.clear((URI)nextPreviousVersion.getObject());
repositoryConnection.remove((URI)nextPreviousVersion.getObject(), null, null, managementGraph);
}
else
{
this.log.error("Found version IRI that was not a URI: {}", nextPreviousVersion);
}
}
// remove whatever was previously there for the current version
// marker
repositoryConnection.remove(nextOntologyUri, PODD.OMV_CURRENT_VERSION, null, managementGraph);
// then insert the new current version marker
repositoryConnection.add(nextOntologyUri, PODD.OMV_CURRENT_VERSION, nextVersionUri, managementGraph);
// remove deprecated current inferred version marker, see podd base infered version
// below
repositoryConnection.remove(nextOntologyUri,
PODD.VF.createURI(PODD.PODD_BASE, "currentInferredVersion"), null, managementGraph);
// link from the ontology IRI to the current inferred axioms
// ontology version
// repositoryConnection.add(nextOntologyUri,
// PODD.PODD_BASE_CURRENT_INFERRED_VERSION,
// nextInferredOntologyUri, managementGraph);
// remove previous versionIRI statements if they are no longer
// needed, before adding the new version below
repositoryConnection.remove(nextOntologyUri, OWL.VERSIONIRI, null, managementGraph);
}
// always setup a version number link for this version
repositoryConnection.add(nextOntologyUri, OWL.VERSIONIRI, nextVersionUri, managementGraph);
// always setup an inferred axioms ontology version for this version
repositoryConnection.add(nextVersionUri, PODD.PODD_BASE_INFERRED_VERSION, nextInferredOntologyUri,
managementGraph);
}
}
/**
* Return an array of URIs representing contexts that can be used to access the version and
* inferred contexts for the given {@link InferredOWLOntologyID}, along with all of its imported
* schema ontologies, which are derived using
* {@link #getDirectImports(InferredOWLOntologyID, RepositoryConnection)}.
*
* @param ontologyID
* @param managementConnection
* @return
* @throws OpenRDFException
* @throws SchemaManifestException
* @throws UnmanagedSchemaIRIException
*/
@Override
public URI[] versionAndInferredAndSchemaContexts(final InferredOWLOntologyID ontologyID,
final RepositoryConnection managementConnection, final URI schemaManagementGraph,
final URI artifactManagementGraph) throws OpenRDFException, SchemaManifestException,
UnmanagedSchemaIRIException
{
final Set<URI> contexts = new LinkedHashSet<URI>();
if(ontologyID != null)
{
contexts.add(ontologyID.getVersionIRI().toOpenRDFURI());
if(ontologyID.getInferredOntologyIRI() != null)
{
contexts.add(ontologyID.getInferredOntologyIRI().toOpenRDFURI());
}
}
contexts.addAll(Arrays.asList(this.schemaContexts(ontologyID, managementConnection, schemaManagementGraph,
artifactManagementGraph)));
return contexts.toArray(new URI[0]);
}
/**
* Return an array of URIs representing contexts that can be used to access the version and
* inferred contexts for the given {@link InferredOWLOntologyID}.
*
* @param ontologyID
* @return
*/
@Override
public URI[] versionAndInferredContexts(final InferredOWLOntologyID ontologyID)
{
if(ontologyID.getInferredOntologyIRI() != null)
{
return new URI[] { ontologyID.getVersionIRI().toOpenRDFURI(),
ontologyID.getInferredOntologyIRI().toOpenRDFURI() };
}
else
{
return new URI[] { ontologyID.getVersionIRI().toOpenRDFURI() };
}
}
/**
* Return an array of URIs representing contexts that can be used to access the version and
* inferred contexts for the given {@link InferredOWLOntologyID}, along with all of its imported
* schema ontologies, which are derived using
* {@link #getDirectImports(InferredOWLOntologyID, RepositoryConnection)}.
* <p>
* NOTE: This method intentionally does not include the inferred ontology IRI here so that we
* can search for concrete triples specifically.
*
* @param ontologyID
* An InferredOWLOntologyID which can be used to identify which schemas are relevant.
* If it is null all of the current schema contexts will be returned.
* @param managementConnection
* The repository connection which is to be used to source the contexts from.
* @param schemaManagementGraph
* If ontologyID is null, this parameter is used instead to source all of the current
* schema ontology versions.
* @return An array of {@link URI}s that can be passed into the {@link RepositoryConnection}
* varargs methods to define which contexts are relevant to queries, or used to define
* the default graphs for SPARQL queries.
* @throws OpenRDFException
* @throws SchemaManifestException
* @throws UnmanagedSchemaIRIException
*/
@Override
public URI[] versionAndSchemaContexts(final InferredOWLOntologyID ontologyID,
final RepositoryConnection managementConnection, final URI schemaManagementGraph,
final URI artifactManagementGraph) throws OpenRDFException, SchemaManifestException,
UnmanagedSchemaIRIException
{
final Set<URI> contexts = new LinkedHashSet<URI>();
if(ontologyID != null)
{
contexts.add(ontologyID.getVersionIRI().toOpenRDFURI());
}
contexts.addAll(Arrays.asList(this.schemaContexts(ontologyID, managementConnection, schemaManagementGraph,
artifactManagementGraph)));
return contexts.toArray(new URI[0]);
}
@Override
public URI[] inferredAndSchemaContexts(final InferredOWLOntologyID ontologyID,
final RepositoryConnection managementConnection, final URI schemaManagementGraph,
final URI artifactManagementGraph) throws OpenRDFException, SchemaManifestException,
UnmanagedSchemaIRIException
{
final Set<URI> contexts = new LinkedHashSet<URI>();
if(ontologyID != null && ontologyID.getInferredOntologyIRI() != null)
{
contexts.add(ontologyID.getInferredOntologyIRI().toOpenRDFURI());
}
contexts.addAll(Arrays.asList(this.schemaContexts(ontologyID, managementConnection, schemaManagementGraph,
artifactManagementGraph)));
return contexts.toArray(new URI[0]);
}
@Override
public URI[] inferredContexts(final InferredOWLOntologyID ontologyID) throws OpenRDFException
{
if(ontologyID.getInferredOntologyIRI() != null)
{
return new URI[] { ontologyID.getInferredOntologyIRI().toOpenRDFURI() };
}
else
{
return new URI[] {};
}
}
@Override
public URI[] schemaContexts(final InferredOWLOntologyID artifactID,
final RepositoryConnection managementConnection, final URI schemaManagementGraph,
final URI artifactManagementGraph) throws OpenRDFException, SchemaManifestException,
UnmanagedSchemaIRIException
{
final Set<URI> contexts = new LinkedHashSet<URI>();
final Set<OWLOntologyID> dependentSchemaOntologies = new LinkedHashSet<>();
if(artifactID != null)
{
final Set<URI> directImports =
this.getDirectImports(artifactID.getOntologyIRI(), managementConnection, artifactManagementGraph);
for(final URI directImport : directImports)
{
final InferredOWLOntologyID schemaVersion =
this.getSchemaVersion(IRI.create(directImport), managementConnection, schemaManagementGraph);
dependentSchemaOntologies.add(schemaVersion);
}
}
else
{
dependentSchemaOntologies.addAll(this.getAllCurrentSchemaOntologyVersions(managementConnection,
schemaManagementGraph));
}
final Model model = new LinkedHashModel();
managementConnection.export(new StatementCollector(model), schemaManagementGraph);
final ConcurrentMap<URI, Set<URI>> importsMap = new ConcurrentHashMap<>();
final List<OWLOntologyID> schemaManifestImports =
OntologyUtils.schemaImports(model, dependentSchemaOntologies, importsMap);
for(final OWLOntologyID schemaOntology : schemaManifestImports)
{
contexts.add(schemaOntology.getVersionIRI().toOpenRDFURI());
}
return contexts.toArray(new URI[0]);
}
@Override
public URI[] versionContexts(final InferredOWLOntologyID ontologyID)
{
return new URI[] { ontologyID.getVersionIRI().toOpenRDFURI() };
}
@Override
public Model ChildOfList(final Set<URI> objectsType, final RepositoryConnection repositoryConnection,
final URI... contexts) throws OpenRDFException
{
final Model results = new LinkedHashModel();
if(objectsType == null)
{
return results;
}
final StringBuilder subChildQuery = new StringBuilder(1024);
subChildQuery.append("CONSTRUCT {");
subChildQuery.append(" ?subConcept <" + RDFS.SUBCLASSOF.stringValue() + "> ?concept ");
subChildQuery.append(" } WHERE {");
subChildQuery.append(" ?subConcept <" + RDFS.SUBCLASSOF.stringValue() + "> ?concept . ");
subChildQuery.append("}");
subChildQuery.append(" VALUES ?concept { ");
for(final Value subClass : objectsType)
{
if(subClass instanceof URI)
{
subChildQuery.append(" <" + subClass + "> ");
}
}
subChildQuery.append(" } ");
final String subChildQueryString = subChildQuery.toString();
this.log.debug("[ChildOfList] Created SPARQL {}", subChildQueryString);
final GraphQuery subChildGraphQuery =
repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, subChildQueryString);
this.log.trace("Created SPARQL {} \n with objects types bound to {}", subChildQueryString, objectsType);
return RdfUtility.executeGraphQuery(subChildGraphQuery, contexts);
}
}
| agpl-3.0 |
WenbinHou/PKUAutoGateway.Android | Reference/IPGWAndroid/com/google/android/gms/ads/internal/reward/mediation/client/b.java | 3990 | package com.google.android.gms.ads.internal.reward.mediation.client;
import android.os.Binder;
import android.os.Parcel;
import com.google.android.gms.a.a;
public abstract class b extends Binder implements a {
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) {
switch (i) {
case 1:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
a(com.google.android.gms.a.b.a(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 2:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
a(com.google.android.gms.a.b.a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
return true;
case 3:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
b(com.google.android.gms.a.b.a(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 4:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
c(com.google.android.gms.a.b.a(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 5:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
d(com.google.android.gms.a.b.a(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 6:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
e(com.google.android.gms.a.b.a(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 7:
RewardItemParcel a;
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
a a2 = com.google.android.gms.a.b.a(parcel.readStrongBinder());
if (parcel.readInt() != 0) {
d dVar = RewardItemParcel.CREATOR;
a = d.a(parcel);
} else {
a = null;
}
a(a2, a);
parcel2.writeNoException();
return true;
case 8:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
f(com.google.android.gms.a.b.a(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 9:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
b(com.google.android.gms.a.b.a(parcel.readStrongBinder()), parcel.readInt());
parcel2.writeNoException();
return true;
case 10:
parcel.enforceInterface("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
g(com.google.android.gms.a.b.a(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 1598968902:
parcel2.writeString("com.google.android.gms.ads.internal.reward.mediation.client.IMediationRewardedVideoAdListener");
return true;
default:
return super.onTransact(i, parcel, parcel2, i2);
}
}
}
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/IfcStructuralSurfaceActivityTypeEnum.java | 10397 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.ifc4;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Ifc Structural Surface Activity Type Enum</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.bimserver.models.ifc4.Ifc4Package#getIfcStructuralSurfaceActivityTypeEnum()
* @model
* @generated
*/
public enum IfcStructuralSurfaceActivityTypeEnum implements Enumerator {
/**
* The '<em><b>NULL</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NULL_VALUE
* @generated
* @ordered
*/
NULL(0, "NULL", "NULL"),
/**
* The '<em><b>BILINEAR</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #BILINEAR_VALUE
* @generated
* @ordered
*/
BILINEAR(1, "BILINEAR", "BILINEAR"),
/**
* The '<em><b>NOTDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NOTDEFINED_VALUE
* @generated
* @ordered
*/
NOTDEFINED(2, "NOTDEFINED", "NOTDEFINED"),
/**
* The '<em><b>ISOCONTOUR</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #ISOCONTOUR_VALUE
* @generated
* @ordered
*/
ISOCONTOUR(3, "ISOCONTOUR", "ISOCONTOUR"),
/**
* The '<em><b>CONST</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CONST_VALUE
* @generated
* @ordered
*/
CONST(4, "CONST", "CONST"),
/**
* The '<em><b>DISCRETE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #DISCRETE_VALUE
* @generated
* @ordered
*/
DISCRETE(5, "DISCRETE", "DISCRETE"),
/**
* The '<em><b>USERDEFINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #USERDEFINED_VALUE
* @generated
* @ordered
*/
USERDEFINED(6, "USERDEFINED", "USERDEFINED");
/**
* The '<em><b>NULL</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NULL</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NULL
* @model
* @generated
* @ordered
*/
public static final int NULL_VALUE = 0;
/**
* The '<em><b>BILINEAR</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>BILINEAR</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #BILINEAR
* @model
* @generated
* @ordered
*/
public static final int BILINEAR_VALUE = 1;
/**
* The '<em><b>NOTDEFINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NOTDEFINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NOTDEFINED
* @model
* @generated
* @ordered
*/
public static final int NOTDEFINED_VALUE = 2;
/**
* The '<em><b>ISOCONTOUR</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>ISOCONTOUR</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #ISOCONTOUR
* @model
* @generated
* @ordered
*/
public static final int ISOCONTOUR_VALUE = 3;
/**
* The '<em><b>CONST</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>CONST</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #CONST
* @model
* @generated
* @ordered
*/
public static final int CONST_VALUE = 4;
/**
* The '<em><b>DISCRETE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>DISCRETE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #DISCRETE
* @model
* @generated
* @ordered
*/
public static final int DISCRETE_VALUE = 5;
/**
* The '<em><b>USERDEFINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>USERDEFINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #USERDEFINED
* @model
* @generated
* @ordered
*/
public static final int USERDEFINED_VALUE = 6;
/**
* An array of all the '<em><b>Ifc Structural Surface Activity Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final IfcStructuralSurfaceActivityTypeEnum[] VALUES_ARRAY = new IfcStructuralSurfaceActivityTypeEnum[] { NULL, BILINEAR, NOTDEFINED, ISOCONTOUR, CONST, DISCRETE, USERDEFINED, };
/**
* A public read-only list of all the '<em><b>Ifc Structural Surface Activity Type Enum</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<IfcStructuralSurfaceActivityTypeEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Ifc Structural Surface Activity Type Enum</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcStructuralSurfaceActivityTypeEnum get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcStructuralSurfaceActivityTypeEnum result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Structural Surface Activity Type Enum</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcStructuralSurfaceActivityTypeEnum getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
IfcStructuralSurfaceActivityTypeEnum result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Ifc Structural Surface Activity Type Enum</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static IfcStructuralSurfaceActivityTypeEnum get(int value) {
switch (value) {
case NULL_VALUE:
return NULL;
case BILINEAR_VALUE:
return BILINEAR;
case NOTDEFINED_VALUE:
return NOTDEFINED;
case ISOCONTOUR_VALUE:
return ISOCONTOUR;
case CONST_VALUE:
return CONST;
case DISCRETE_VALUE:
return DISCRETE;
case USERDEFINED_VALUE:
return USERDEFINED;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private IfcStructuralSurfaceActivityTypeEnum(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //IfcStructuralSurfaceActivityTypeEnum
| agpl-3.0 |
dzhw/metadatamanagement | src/test/java/eu/dzhw/fdz/metadatamanagement/datapackagemanagement/rest/DataPackageAccessWaysResourceControllerTest.java | 4084 | package eu.dzhw.fdz.metadatamanagement.datapackagemanagement.rest;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import eu.dzhw.fdz.metadatamanagement.AbstractTest;
import eu.dzhw.fdz.metadatamanagement.common.service.JaversService;
import eu.dzhw.fdz.metadatamanagement.common.unittesthelper.util.UnitTestCreateDomainObjectUtils;
import eu.dzhw.fdz.metadatamanagement.datapackagemanagement.domain.DataPackage;
import eu.dzhw.fdz.metadatamanagement.datapackagemanagement.repository.DataPackageRepository;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.domain.DataSet;
import eu.dzhw.fdz.metadatamanagement.datasetmanagement.repository.DataSetRepository;
import eu.dzhw.fdz.metadatamanagement.projectmanagement.domain.DataAcquisitionProject;
import eu.dzhw.fdz.metadatamanagement.projectmanagement.repository.DataAcquisitionProjectRepository;
import eu.dzhw.fdz.metadatamanagement.searchmanagement.repository.ElasticsearchUpdateQueueItemRepository;
import eu.dzhw.fdz.metadatamanagement.searchmanagement.service.ElasticsearchAdminService;
import eu.dzhw.fdz.metadatamanagement.surveymanagement.domain.Survey;
import eu.dzhw.fdz.metadatamanagement.surveymanagement.repository.SurveyRepository;
import eu.dzhw.fdz.metadatamanagement.usermanagement.security.AuthoritiesConstants;
public class DataPackageAccessWaysResourceControllerTest extends AbstractTest {
@Autowired
private WebApplicationContext wac;
@Autowired
private DataAcquisitionProjectRepository dataAcquisitionProjectRepository;
@Autowired
private DataPackageRepository dataPackageRepository;
@Autowired
private DataSetRepository dataSetRepository;
@Autowired
private SurveyRepository surveyRepository;
@Autowired
private ElasticsearchUpdateQueueItemRepository elasticsearchUpdateQueueItemRepository;
@Autowired
private ElasticsearchAdminService elasticsearchAdminService;
@Autowired
private JaversService javersService;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@AfterEach
public void cleanUp() {
dataAcquisitionProjectRepository.deleteAll();
dataSetRepository.deleteAll();
surveyRepository.deleteAll();
dataPackageRepository.deleteAll();
elasticsearchUpdateQueueItemRepository.deleteAll();
elasticsearchAdminService.recreateAllIndices();
javersService.deleteAll();
}
@Test
@WithMockUser(authorities = AuthoritiesConstants.PUBLISHER)
public void testGetAccessWaysOfDataPackage() throws IOException, Exception {
DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject();
dataAcquisitionProjectRepository.save(project);
DataPackage dataPackage = UnitTestCreateDomainObjectUtils.buildDataPackage(project.getId());
dataPackageRepository.save(dataPackage);
Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId());
surveyRepository.save(survey);
DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project.getId(), survey.getId(),
survey.getNumber());
dataSetRepository.save(dataSet);
// get the available access ways
mockMvc
.perform(get("/api/data-packages/" + dataPackage.getId() + "/access-ways"))
.andExpect(status().isOk()).andExpect(jsonPath("$.length()", is(4)));
}
}
| agpl-3.0 |
yinan-liu/scheduling | scheduler/scheduler-server/src/main/java/org/ow2/proactive/scheduler/core/EnabledListenJobLogsSupport.java | 6702 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.scheduler.core;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;
import org.ow2.proactive.scheduler.common.exception.InternalException;
import org.ow2.proactive.scheduler.common.exception.UnknownJobException;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobResult;
import org.ow2.proactive.scheduler.common.task.Log4JTaskLogs;
import org.ow2.proactive.scheduler.common.task.TaskLogs;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.util.logforwarder.AppenderProvider;
import org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingException;
import org.ow2.proactive.scheduler.common.util.logforwarder.LogForwardingService;
import org.ow2.proactive.scheduler.core.db.SchedulerDBManager;
import org.ow2.proactive.scheduler.task.TaskLauncher;
import org.ow2.proactive.scheduler.util.JobLogger;
import org.ow2.proactive.scheduler.util.TaskLogger;
class EnabledListenJobLogsSupport extends ListenJobLogsSupport {
private static final JobLogger jlogger = JobLogger.getInstance();
private static final TaskLogger tlogger = TaskLogger.getInstance();
private final Set<JobId> jobsToBeLogged = new HashSet<>();
private final SchedulerDBManager dbManager;
private final LogForwardingService lfs;
private final LiveJobs liveJobs;
EnabledListenJobLogsSupport(SchedulerDBManager dbManager, LiveJobs liveJobs, String providerClassname)
throws LogForwardingException {
this.dbManager = dbManager;
this.liveJobs = liveJobs;
this.lfs = new LogForwardingService(providerClassname);
this.lfs.initialize();
logger.info("Initialized log forwarding service at " + this.lfs.getServerURI());
}
@Override
void shutdown() {
try {
lfs.terminate();
} catch (LogForwardingException e) {
logger.error("Cannot terminate logging service : " + e.getMessage());
logger.error("", e);
}
}
@Override
synchronized void cleanLoggers(JobId jobId) {
jobsToBeLogged.remove(jobId);
jlogger.debug(jobId, "cleaning loggers");
String loggerName = Log4JTaskLogs.getLoggerName(jobId);
lfs.removeAllAppenders(loggerName);
lfs.removeLogger(loggerName);
}
@Override
synchronized void activeLogsIfNeeded(JobId jobId, TaskLauncher launcher) throws LogForwardingException {
if (jobsToBeLogged.contains(jobId)) {
launcher.activateLogs(lfs.getAppenderProvider());
}
}
@Override
synchronized void listenJobLogs(JobId jobId, AppenderProvider appenderProvider) throws UnknownJobException {
jlogger.info(jobId, "listening logs");
// create the appender to the remote listener
Appender clientAppender = null;
try {
clientAppender = appenderProvider.getAppender();
} catch (LogForwardingException e) {
jlogger.error(jobId, "cannot create an appender", e);
throw new InternalException("Cannot create an appender for job " + jobId, e);
}
boolean logIsAlreadyInitialized = jobsToBeLogged.contains(jobId);
initJobLogging(jobId, clientAppender);
JobResult result = dbManager.loadJobResult(jobId);
if (result == null) {
throw new UnknownJobException(jobId);
}
// for finished tasks, add logs events "manually"
Collection<TaskResult> allRes = result.getAllResults().values();
for (TaskResult tr : allRes) {
this.flushTaskLogs(tr, clientAppender, jobId);
}
for (RunningTaskData taskData : liveJobs.getRunningTasks(jobId)) {
try {
TaskLauncher taskLauncher = taskData.getLauncher();
if (logIsAlreadyInitialized) {
taskLauncher.getStoredLogs(appenderProvider);
} else {
taskLauncher.activateLogs(lfs.getAppenderProvider());
}
} catch (Exception e) {
tlogger.error(taskData.getTask().getId(), "cannot create an appender provider", e);
}
}
if (!result.getJobInfo().getStatus().isJobAlive()) {
jlogger.info(jobId, "cleaning loggers for already finished job");
cleanLoggers(jobId);
}
}
private void initJobLogging(JobId jobId, Appender clientAppender) {
jobsToBeLogged.add(jobId);
lfs.addAppender(Log4JTaskLogs.getLoggerName(jobId), clientAppender);
}
private void flushTaskLogs(TaskResult tr, Appender a, JobId jobId) {
// if taskResult is not awaited, task is terminated
TaskLogs logs = tr.getOutput();
if (logs instanceof Log4JTaskLogs) {
for (LoggingEvent le : ((Log4JTaskLogs) logs).getAllEvents()) {
// write into socket appender directly to avoid double lines on other listeners
a.doAppend(le);
}
} else {
a.doAppend(createLoggingEvent(jobId, logs.getStdoutLogs(false), Level.INFO));
a.doAppend(createLoggingEvent(jobId, logs.getStderrLogs(false), Level.DEBUG));
}
}
private LoggingEvent createLoggingEvent(JobId jobId, String logs, Priority level) {
return new LoggingEvent(null, Logger.getLogger(Log4JTaskLogs.getLoggerName(jobId)), level, logs, null);
}
}
| agpl-3.0 |
NicolasEYSSERIC/Silverpeas-Core | lib-core/src/main/java/com/silverpeas/domains/silverpeasdriver/SPUser.java | 9606 | /**
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.domains.silverpeasdriver;
import com.google.common.base.CharMatcher;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @author ehugonnet
*/
@Entity
@Table(name = "domainsp_user")
@NamedQueries( {
@NamedQuery(name = "SPUser.findByFirstname", query = "SELECT s FROM SPUser s WHERE s.firstname = :firstname"),
@NamedQuery(name = "SPUser.findByLastname", query = "SELECT s FROM SPUser s WHERE s.lastname = :lastname"),
@NamedQuery(name = "SPUser.findByPhone", query = "SELECT s FROM SPUser s WHERE s.phone = :phone"),
@NamedQuery(name = "SPUser.findByHomephone", query = "SELECT s FROM SPUser s WHERE s.homephone = :homephone"),
@NamedQuery(name = "SPUser.findByCellphone", query = "SELECT s FROM SPUser s WHERE s.cellphone = :cellphone"),
@NamedQuery(name = "SPUser.findByFax", query = "SELECT s FROM SPUser s WHERE s.fax = :fax"),
@NamedQuery(name = "SPUser.findByAddress", query = "SELECT s FROM SPUser s WHERE s.address = :address"),
@NamedQuery(name = "SPUser.findByTitle", query = "SELECT s FROM SPUser s WHERE s.title = :title"),
@NamedQuery(name = "SPUser.findByCompany", query = "SELECT s FROM SPUser s WHERE s.company = :company"),
@NamedQuery(name = "SPUser.findByPosition", query = "SELECT s FROM SPUser s WHERE s.position = :position"),
@NamedQuery(name = "SPUser.findByBoss", query = "SELECT s FROM SPUser s WHERE s.boss = :boss"),
@NamedQuery(name = "SPUser.findByLogin", query = "SELECT s FROM SPUser s WHERE s.login = :login"),
@NamedQuery(name = "SPUser.findByPassword", query = "SELECT s FROM SPUser s WHERE s.password = :password"),
@NamedQuery(name = "SPUser.findByPasswordvalid", query = "SELECT s FROM SPUser s WHERE s.passwordvalid = :passwordvalid"),
@NamedQuery(name = "SPUser.findByLoginmail", query = "SELECT s FROM SPUser s WHERE s.loginmail = :loginmail"),
@NamedQuery(name = "SPUser.findByEmail", query = "SELECT s FROM SPUser s WHERE s.email = :email") })
public class SPUser implements Serializable {
private static final long serialVersionUID = 2645559023438948622L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Size(max = 100)
@Column(name = "firstname")
private String firstname;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "lastname")
private String lastname;
// @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$",
// message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or
// fax number consider using this annotation to enforce field validation
@Size(max = 20)
@Column(name = "phone")
private String phone;
@Size(max = 20)
@Column(name = "homephone")
private String homephone;
@Size(max = 20)
@Column(name = "cellphone")
private String cellphone;
// @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$",
// message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or
// fax number consider using this annotation to enforce field validation
@Size(max = 20)
@Column(name = "fax")
private String fax;
@Size(max = 500)
@Column(name = "address")
private String address;
@Size(max = 100)
@Column(name = "title")
private String title;
@Size(max = 100)
@Column(name = "company")
private String company;
@Size(max = 100)
@Column(name = "position")
private String position;
@Size(max = 100)
@Column(name = "boss")
private String boss;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "login")
private String login;
@Size(max = 32)
@Column(name = "password")
private String password;
@Basic(optional = false)
@NotNull
@Column(name = "passwordvalid")
private char passwordvalid;
@Size(max = 100)
@Column(name = "loginmail")
private String loginmail;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
// message="Invalid email")//if the field contains email address consider using this annotation to
// enforce field validation
@Size(max = 100)
@Column(name = "email")
private String email;
@ManyToMany(mappedBy = "users")
private Set<SPGroup> groups;
@Transient
static final CharMatcher booleanConverter = CharMatcher.is('Y').or(CharMatcher.is('y'));
public SPUser() {
this.title = "";
this.company = "";
this.position = "";
this.boss = "";
this.phone = "";
this.homephone = "";
this.fax = "";
this.cellphone = "";
this.address = "";
this.loginmail = "";
this.password = "";
this.passwordvalid = 'N';
}
public SPUser(Integer id) {
this.id = id;
}
public SPUser(Integer id, String lastname, String login, char passwordvalid) {
this.id = id;
this.lastname = lastname;
this.login = login;
this.passwordvalid = passwordvalid;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getHomephone() {
return homephone;
}
public void setHomephone(String homephone) {
this.homephone = homephone;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getBoss() {
return boss;
}
public void setBoss(String boss) {
this.boss = boss;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isPasswordValid() {
return booleanConverter.matches(passwordvalid);
}
public void setPasswordValid(boolean passwordvalid) {
if (passwordvalid) {
this.passwordvalid = 'Y';
} else {
this.passwordvalid = 'N';
}
}
public String getLoginmail() {
return loginmail;
}
public void setLoginmail(String loginmail) {
this.loginmail = loginmail;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<SPGroup> getGroups() {
return groups;
}
public void setGroups(Set<SPGroup> groups) {
this.groups = groups;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof SPUser)) {
return false;
}
SPUser other = (SPUser) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.silverpeas.domains.silverpeasdriver.SPUser[ id=" + id + " ]";
}
}
| agpl-3.0 |
ging/isabel | components/snmp/app/Agent/DataBaseHandler_t.java | 10604 | /*
* ISABEL: A group collaboration tool for the Internet
* Copyright (C) 2009 Agora System S.A.
*
* This file is part of Isabel.
*
* Isabel is free software: you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Isabel is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Affero GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with Isabel. If not, see <http://www.gnu.org/licenses/>.
*/
//*********************************************************************
//CLASE PERTENECIENTE A: ISABELAgent
//
//DESCRIPCIÓN: Clase encargada de proporcionar acceso a los datos a
// los distintos Threads, de forma que en estas no deban hacerse
// modificaciones para añadir la gestion de nuevos compoenetes
// de Isabel.
//
//CLASES RELACIONADAS:
//
import java.io.*;
public class DataBaseHandler_t {
//CAMPOS:
//1.- Debe haber una base de Datos por cada rama de la MIB implementada:
//----------------------------------------------------------------------
//-->Audio:
audioDataBase_t audioDataBase;
audioDataBaseHandler_t audioDataBaseHandler;
//-->Video:
videoDataBase_t videoDataBase;
videoDataBaseHandler_t videoDataBaseHandler;
//-->SharedDisplay:
shDisplayDataBase_t shDisplayDataBase;
shDisplayDataBaseHandler_t shDisplayDataBaseHandler;
//-->IRouter:
irouterDataBase_t irouterDataBase;
irouterDataBaseHandler_t irouterDataBaseHandler;
DataBaseHandler_t () {
//-->Audio:
audioDataBase = new audioDataBase_t();
audioDataBaseHandler = new audioDataBaseHandler_t(audioDataBase);
//-->Video:
videoDataBase = new videoDataBase_t();
videoDataBaseHandler = new videoDataBaseHandler_t(videoDataBase);
//-->ShDisplay:
shDisplayDataBase = new shDisplayDataBase_t();
shDisplayDataBaseHandler = new shDisplayDataBaseHandler_t(shDisplayDataBase);
//-->IRouter:
irouterDataBase = new irouterDataBase_t();
irouterDataBaseHandler = new irouterDataBaseHandler_t(irouterDataBase);
}
//3.- Funciones que invoca la thread internalCommServer_t:
//--------------------------------------------------------
//Analizar mensajes que llegan de los modulos de ISAEBEL.
//Aqui se distribuyen al modulo de datos que corresponda.
void AnalizeDataMessage(String compId, int channelId, DataInputStream dst) {
try {
//-->Audio:
if (compId.equals("AUD")) {
audioDataBaseHandler.AnalizeMessage(channelId,dst);
return;
}
//-->Video:
if (compId.equals("VID")) {
videoDataBaseHandler.AnalizeMessage(channelId,dst);
return;
}
//-->shDisplay:
if (compId.equals("SHD")) {
shDisplayDataBaseHandler.AnalizeMessage(channelId,dst);
return;
}
//-->Irouter:
if (compId.equals("IRT")) {
irouterDataBaseHandler.AnalizeMessage(channelId,dst);
return;
}
} catch (java.io.IOException e) {
System.out.println("Excepcion en AnalizeDataMessage " +
"de DataBaseHandler:"+e);
};
}
//Analizar mensajes de control que llegan de los modulos de ISABEL.
//Aqui se distribuyen al modulo de datos que corresponda.
void AnalizeControlMessage(String compId, int channelId) {
// A dia de hoy los mensajes de control son unicos
// e indican el borrado de un determinado canal.
//-->Audio:
if (compId.equals("AUD")) {
audioDataBaseHandler.deleteChannel(channelId);
return;
}
//-->Video:
if (compId.equals("VID")) {
videoDataBaseHandler.deleteChannel(channelId);
return;
}
//-->ShDisplay:
if (compId.equals("SHD")) {
shDisplayDataBaseHandler.deleteChannel(channelId);
return;
}
//-->IRouter:
//if (compId.equals("IRT")) {
// irouterDataBaseHandler.AnalizeControlMessage(channelId);
// return;
//}
}
// Para actualizar el tiempo que llevan sin modificarse los datos:
// y borrar aquellos que ya estan obsoletos.
void IncrementAllChannelsTTL() {
audioDataBaseHandler.IncrementAllChannelsTTL();
videoDataBaseHandler.IncrementAllChannelsTTL();
shDisplayDataBaseHandler.IncrementAllChannelsTTL();
irouterDataBaseHandler.IncrementAllChannelsTTL();
}
// Para eliminar de la Base de Datos aquellos canales que no se
// han actualizado en un largo periodo de tiempo y por tanto han
// debido morir
//void DeleteDeadChannels() {
// audioDataBase.DeleteDeadChannels();
// videoDataBase.DeleteDeadChannels();
// shDisplayDataBaseHandler.DeleteDeadChannels();
//}
//4.- Funciones que invoca la Thread SNMPServer_t:
//------------------------------------------------
sck.smi getData(sck.Oid RequestedOid) {
if (!DataBase_t.contains(RequestedOid))
return null;
//-->Audio:
if (RequestedOid.sameTree(DataBase_t.AUDIO)) {
return audioDataBaseHandler.GET(RequestedOid);
}
//-->Video:
if (RequestedOid.sameTree(DataBase_t.VIDEO)) {
return videoDataBaseHandler.GET(RequestedOid);
}
//-->ShDisplay:
if (RequestedOid.sameTree(DataBase_t.SHDISPLAY)) {
return shDisplayDataBaseHandler.GET(RequestedOid);
}
//-->Irouter:
if (RequestedOid.sameTree(DataBase_t.IROUTER)) {
return irouterDataBaseHandler.GET(RequestedOid);
}
return null;
}
//5.- Funciones que invoca la thread de Visualizacion:
//----------------------------------------------------
int getCountOfAudioEntries () {
return audioDataBaseHandler.countEntries();
}
int getCountOfVideoEntries () {
return videoDataBaseHandler.countEntries();
}
int getCountOfShDisplayEntries() {
return shDisplayDataBaseHandler.countEntries();
}
int getCountOfIrouterRCVEntries() {
return irouterDataBaseHandler.countRCVEntries();
}
int getCountOfIrouterSNDEntries() {
return irouterDataBaseHandler.countSNDEntries();
}
int getChIndexFromPos(String compId,int row) {
if (compId.equals("AUD"))
return audioDataBaseHandler.getChIndexFromPos(row);
if (compId.equals("VID"))
return videoDataBaseHandler.getChIndexFromPos(row);
if (compId.equals("SHD"))
return shDisplayDataBaseHandler.getChIndexFromPos(row);
//if (compId.equals("IRT"))
// return irouterDataBaseHandler.getChIndexFromPos(row);
return -1;
}
Object getData (String compId, int row, int dataIndex) {
try {
//-->Audio:
if (compId.equals("AUD")) {
int ChIndex = audioDataBaseHandler.getChIndexFromPos(row);
return getData (new sck.Oid (DataBase_t.AUDIO+".1.1."+dataIndex+"."+ChIndex));
}
//-->Video:
if (compId.equals("VID")) {
int ChIndex = videoDataBaseHandler.getChIndexFromPos(row);
return getData (new sck.Oid (DataBase_t.VIDEO+".1.1."+dataIndex+"."+ChIndex));
}
//-->ShDisplay:
if (compId.equals("SHD")) {
int ChIndex = shDisplayDataBaseHandler.getChIndexFromPos(row);
return getData (new sck.Oid (DataBase_t.SHDISPLAY+".1.1."+dataIndex+"."+ChIndex));
}
//-->Irouter:
if (compId.equals("IRTRCV")) {
String irtMedia= irouterDataBaseHandler.getRCVMediaFromRow(row);
int irtSSRC= irouterDataBaseHandler.getRCVSSRCFromRow(row);
return getData(new sck.Oid (DataBase_t.IROUTER+".1.1."+dataIndex+"."+irtSSRC+"."+irouterMediaID.getMediaID(irtMedia)));
}
if (compId.equals("IRTSND")) {
String irtMedia= irouterDataBaseHandler.getSNDMediaFromRow(row);
int irtSSRC= irouterDataBaseHandler.getSNDSSRCFromRow(row);
return getData(new sck.Oid (DataBase_t.IROUTER+".3.1."+dataIndex+"."+irtSSRC+"."+irouterMediaID.getMediaID(irtMedia)));
}
return null;
} catch (java.io.InvalidObjectException e) {
System.out.println("Excepcion al buscar un data " +
"para la thread visual; "+e);
};
return null;
}
Object getDataFromChannel (String compId, int ChIndex, int dataIndex) {
try {
//-->Audio:
if (compId.equals("AUD")) {
return getData (new sck.Oid (DataBase_t.AUDIO+".1.1."+dataIndex+"."+ChIndex));
}
//-->Video:
if (compId.equals("VID")) {
return getData (new sck.Oid (DataBase_t.VIDEO+".1.1."+dataIndex+"."+ChIndex));
}
//-->ShDisplay:
if (compId.equals("SHD")) {
return getData (new sck.Oid (DataBase_t.SHDISPLAY+".1.1."+dataIndex+"."+ChIndex));
}
//-->Irouter:
// if (compId.equals("IRT")) {
// return getData (new sck.Oid (DataBase_t.IROUTER+".1.1."+dataIndex+"."+ChIndex));
// }
return null;
} catch (java.io.InvalidObjectException e) {
System.out.println("Excepcion al buscar un data " +
"para la thread visual; "+e);
};
return null;
}
audioDataBase_t getAudioDataBase () {
return audioDataBaseHandler.getAudioDataBase();
}
videoDataBase_t getVideoDataBase () {
return videoDataBaseHandler.getVideoDataBase();
}
shDisplayDataBase_t getShDisplayDataBase () {
return shDisplayDataBaseHandler.getShDisplayDataBase();
}
irouterDataBase_t getIrouterDataBase () {
return irouterDataBaseHandler.getIrouterDataBase();
}
}
| agpl-3.0 |
MartinHaeusler/chronos | org.chronos.chronograph/src/main/java/org/chronos/chronograph/internal/impl/index/VertexRecordLongIndexer2.java | 720 | package org.chronos.chronograph.internal.impl.index;
import java.util.Set;
import org.chronos.chronodb.api.indexing.LongIndexer;
import org.chronos.chronograph.internal.impl.structure.record.PropertyRecord;
import org.chronos.common.annotation.PersistentClass;
@PersistentClass("kryo")
public class VertexRecordLongIndexer2 extends VertexRecordPropertyIndexer2<Long> implements LongIndexer {
protected VertexRecordLongIndexer2() {
// default constructor for serialization
}
public VertexRecordLongIndexer2(final String propertyName) {
super(propertyName);
}
@Override
protected Set<Long> getIndexValuesInternal(final PropertyRecord record) {
return GraphIndexingUtils.getLongIndexValues(record);
}
}
| agpl-3.0 |
acheype/malaria-plant-db | src/main/java/nc/ird/malariaplantdb/repository/search/PubSpeciesSearchRepository.java | 354 | package nc.ird.malariaplantdb.repository.search;
import nc.ird.malariaplantdb.domain.PubSpecies;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data ElasticSearch repository for the PubSpecies entity.
*/
public interface PubSpeciesSearchRepository extends ElasticsearchRepository<PubSpecies, Long> {
}
| agpl-3.0 |
aamatin/InfrequentDataMining | MODULES/DataSetGenerator/src/main/java/com/mbzshajib/mining/processor/randomdata/generator/v2/RandomGeneratorInputV2.java | 693 | package com.mbzshajib.mining.processor.randomdata.generator.v2;
import com.mbzshajib.utility.model.Input;
import java.util.List;
/**
* *****************************************************************
* Copyright 2015.
*
* @author - Md. Badi-Uz-Zaman Shajib
* @email - mbzshajib@gmail.com
* @gitHub - https://github.com/mbzshajib
* @date: 9/4/2015
* @time: 6:41 PM
* ****************************************************************
*/
public class RandomGeneratorInputV2 implements Input {
private List<RInputInfo> list;
public List<RInputInfo> getList() {
return list;
}
public void setList(List<RInputInfo> list) {
this.list = list;
}
}
| agpl-3.0 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsf/itemf119.java | 159 | package fr.toss.FF7itemsf;
public class itemf119 extends FF7itemsfbase {
public itemf119(int id) {
super(id);
setUnlocalizedName("itemf119");
}
}
| lgpl-2.1 |