code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
package som.interpreter.nodes.literals;
import com.oracle.truffle.api.frame.VirtualFrame;
public final class StringLiteralNode extends LiteralNode {
private final String value;
public StringLiteralNode(final String value) {
this.value = value;
}
@Override
public String executeString(final VirtualFrame frame) {
return value;
}
@Override
public Object executeGeneric(final VirtualFrame frame) {
return value;
}
}
| richard-roberts/SOMns | src/som/interpreter/nodes/literals/StringLiteralNode.java | Java | mit | 450 |
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.nodejsdbg.ide;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import java.util.Map;
import org.eclipse.che.api.core.jsonrpc.commons.RequestHandlerConfigurator;
import org.eclipse.che.api.core.jsonrpc.commons.RequestHandlerManager;
import org.eclipse.che.api.core.jsonrpc.commons.RequestTransmitter;
import org.eclipse.che.api.promises.client.PromiseProvider;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.debug.BreakpointManager;
import org.eclipse.che.ide.api.debug.DebuggerServiceClient;
import org.eclipse.che.ide.api.notification.NotificationManager;
import org.eclipse.che.ide.debug.DebuggerDescriptor;
import org.eclipse.che.ide.debug.DebuggerManager;
import org.eclipse.che.ide.dto.DtoFactory;
import org.eclipse.che.ide.util.storage.LocalStorageProvider;
import org.eclipse.che.plugin.debugger.ide.DebuggerLocalizationConstant;
import org.eclipse.che.plugin.debugger.ide.debug.AbstractDebugger;
import org.eclipse.che.plugin.debugger.ide.debug.DebuggerLocationHandlerManager;
/**
* The NodeJs Debugger Client.
*
* @author Anatoliy Bazko
*/
public class NodeJsDebugger extends AbstractDebugger {
public static final String ID = "nodejsdbg";
@Inject
public NodeJsDebugger(
DebuggerServiceClient service,
RequestTransmitter transmitter,
RequestHandlerConfigurator configurator,
DtoFactory dtoFactory,
LocalStorageProvider localStorageProvider,
EventBus eventBus,
DebuggerManager debuggerManager,
NotificationManager notificationManager,
BreakpointManager breakpointManager,
AppContext appContext,
DebuggerLocalizationConstant constant,
RequestHandlerManager requestHandlerManager,
DebuggerLocationHandlerManager debuggerLocationHandlerManager,
PromiseProvider promiseProvider) {
super(
service,
transmitter,
configurator,
dtoFactory,
localStorageProvider,
eventBus,
debuggerManager,
notificationManager,
appContext,
breakpointManager,
constant,
requestHandlerManager,
debuggerLocationHandlerManager,
promiseProvider,
ID);
}
@Override
protected DebuggerDescriptor toDescriptor(Map<String, String> connectionProperties) {
StringBuilder sb = new StringBuilder();
for (String propName : connectionProperties.keySet()) {
try {
ConnectionProperties prop = ConnectionProperties.valueOf(propName.toUpperCase());
String connectionInfo = prop.getConnectionInfo(connectionProperties.get(propName));
if (!connectionInfo.isEmpty()) {
if (sb.length() > 0) {
sb.append(',');
}
sb.append(connectionInfo);
}
} catch (IllegalArgumentException ignored) {
// unrecognized connection property
}
}
return new DebuggerDescriptor("", "{ " + sb.toString() + " }");
}
public enum ConnectionProperties {
SCRIPT {
@Override
public String getConnectionInfo(String value) {
return value;
}
};
public abstract String getConnectionInfo(String value);
}
}
| akervern/che | plugins/plugin-nodejs-debugger/che-plugin-nodejs-debugger-ide/src/main/java/org/eclipse/che/plugin/nodejsdbg/ide/NodeJsDebugger.java | Java | epl-1.0 | 3,566 |
/*******************************************************************************
* Copyright (c) 2009 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.javascript.plugin;
import org.eclipse.birt.core.plugin.BIRTPlugin;
import org.eclipse.birt.report.engine.javascript.JavascriptEngineFactory;
import org.osgi.framework.BundleContext;
public class JavaScriptPlugin extends BIRTPlugin
{
public void start( BundleContext context ) throws Exception
{
super.start( context );
JavascriptEngineFactory.initMyFactory( );
}
public void stop( BundleContext context ) throws Exception
{
super.stop( context );
JavascriptEngineFactory.destroyMyFactory( );
}
} | Charling-Huang/birt | data/org.eclipse.birt.report.engine.script.javascript/src/org/eclipse/birt/report/engine/javascript/plugin/JavaScriptPlugin.java | Java | epl-1.0 | 1,088 |
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.jsdt.internal.core.manipulation;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.wst.jsdt.core.manipulation.JavaScriptManipulation;
import org.osgi.framework.BundleContext;
/**
* The main plug-in class to be used in the workbench.
*/
public class JavaManipulationPlugin extends Plugin {
//The shared instance.
private static JavaManipulationPlugin fgDefault;
/**
* The constructor.
*/
public JavaManipulationPlugin() {
fgDefault = this;
}
/**
* This method is called upon plug-in activation
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/**
* This method is called when the plug-in is stopped
*/
public void stop(BundleContext context) throws Exception {
super.stop(context);
fgDefault = null;
}
/**
* Returns the shared instance.
*
* @return the shared instance.
*/
public static JavaManipulationPlugin getDefault() {
return fgDefault;
}
public static String getPluginId() {
return JavaScriptManipulation.ID_PLUGIN;
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), IStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), IStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IStatusConstants.INTERNAL_ERROR, JavaManipulationMessages.JavaManipulationMessages_internalError, e));
}
}
| boniatillo-com/PhaserEditor | source/thirdparty/jsdt/org.eclipse.wst.jsdt.manipulation/src/org/eclipse/wst/jsdt/internal/core/manipulation/JavaManipulationPlugin.java | Java | epl-1.0 | 2,438 |
/*
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2014, PlanetMayo Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package com.visutools.nav.bislider;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Properties;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicBorders;
import javax.swing.plaf.metal.*;
//import javax.swing.plaf.metal.OceanTheme;
/**
* 5 examples of BiSlider in a JFrame to see the widget at work.
* <br><br>
* <table border=1 width = "90%">
* <tr>
* <td>
* Copyright 1997-2005 Frederic Vernier. All Rights Reserved.<br>
* <br>
* Permission to use, copy, modify and distribute this software and its documentation for educational, research and
* non-profit purposes, without fee, and without a written agreement is hereby granted, provided that the above copyright
* notice and the following three paragraphs appear in all copies.<br>
* <br>
* To request Permission to incorporate this software into commercial products contact
* Frederic Vernier, 19 butte aux cailles street, Paris, 75013, France. Tel: (+33) 871 747 387.
* eMail: [email protected] / Web site: http://vernier.frederic.free.fr
* <br>
* IN NO EVENT SHALL FREDERIC VERNIER BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
* DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF FREDERIC
* VERNIER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.<br>
* <br>
* FREDERIC VERNIER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HERE UNDER IS ON AN "AS IS" BASIS, AND
* FREDERIC VERNIER HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.<br>
* </td>
* </tr>
* </table>
* <br>
* <b>Project related :</b> FiCell, FieldExplorer<br>
* <br>
* <b>Dates:</b><br>
* <li>Creation : 1997<br>
* <li>Format : 15/02/2004<br>
* <li>Last Modif : 19/06/2005 <br>
*<br>
* <b>Bugs:</b><br>
* <li><br>
*<br>
* <b>To Do:</b><br>
* <li><br>
*<br>
* @author Frederic Vernier, [email protected]
* @version 1.4.1
**/
public class Test {
// all the properties of the application (parameters)
private static Properties BiSliderProperties = new Properties();
static float LineX = 0f;
public static void main(String[] Args) {
try {
File PropFileName = new File("properties/properties_BiSlider");
System.out.println("Using property file :"+PropFileName);
if (PropFileName.exists()){
FileInputStream FileInputStream1 = new FileInputStream(PropFileName);
BiSliderProperties.load(FileInputStream1);
FileInputStream1.close();
} else {
BiSliderProperties.setProperty("Application.Name", "BiSlider");
BiSliderProperties.setProperty("Application.Version", "1.0");
BiSliderProperties.setProperty("Application.Build", "0001");
FileOutputStream FileOutputStream1 = new FileOutputStream(PropFileName);
BiSliderProperties.store(FileOutputStream1, "Values of the parameters of the application");
FileOutputStream1.close();
}
} catch(IOException IOException_Arg){
//IOException_Arg.printStackTrace();
}
final JFrame JFrame1 = new JFrame(" Examples of "+BiSliderProperties.getProperty("Application.Name")+
" v"+BiSliderProperties.getProperty("Application.Version")+
" build"+BiSliderProperties.getProperty("Application.Build"));
JFrame1.setIconImage(new BiSliderBeanInfo().getIcon(BiSliderBeanInfo.ICON_COLOR_32x32));
JFrame1.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
JFrame1.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
JFrame1.setVisible(false);
JFrame1.dispose();
System.exit(0);
}
});
final SwingBiSlider BiSlider1 = new SwingBiSlider(SwingBiSlider.HSB, null);
BiSlider1.setVisible(true);
BiSlider1.setMinimumValue(-193);
BiSlider1.setMaximumValue(227);
BiSlider1.setSegmentSize(20);
BiSlider1.setMinimumColor(Color.ORANGE);
BiSlider1.setMaximumColor(Color.BLUE);
BiSlider1.setUnit("$");
BiSlider1.setPrecise(true);
final JPopupMenu JPopupMenu1 = BiSlider1.createPopupMenu();
BiSlider1.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent MouseEvent_Arg){
if (MouseEvent_Arg.getButton()==MouseEvent.BUTTON3){
JPopupMenu1.show(BiSlider1, MouseEvent_Arg.getX(), MouseEvent_Arg.getY());
}
}
});
final SwingBiSlider BiSlider2 = new SwingBiSlider(SwingBiSlider.RGB, null);
BiSlider2.setToolTipText("No line to highlight the ticks here");
BiSlider2.setMinimumValue(-5);
BiSlider2.setMaximumValue(5);
BiSlider2.setSegmentSize(3);
BiSlider2.setMinimumColor(Color.RED);
BiSlider2.setMaximumColor(Color.GREEN);
BiSlider2.setColoredValues(-1, 4);
BiSlider2.setUnit("%");
BiSlider2.setBackground(Color.GRAY);
BiSlider2.setSliderBackground(new Color(152, 152, 192));
BiSlider2.setForeground(Color.WHITE);
BiSlider2.setSound(true);
BiSlider2.setArcSize(14);
BiSlider2.setFont(new Font("SansSerif", Font.ITALIC|Font.BOLD, 12));
BiSlider2.setPrecise(true);
BiSlider2.addContentPainterListener(new ContentPainterListener(){
public void paint(ContentPainterEvent ContentPainterEvent_Arg){
Graphics2D Graphics2 = (Graphics2D)ContentPainterEvent_Arg.getGraphics();
Rectangle Rect1 = ContentPainterEvent_Arg.getRectangle();
if (ContentPainterEvent_Arg.getColor()!=null) {
Graphics2.setColor(ContentPainterEvent_Arg.getColor());
Graphics2.setPaint(new GradientPaint(Rect1.x, Rect1.y, ContentPainterEvent_Arg.getColor(),
Rect1.x+(int)(LineX*Rect1.width), Rect1.y, ContentPainterEvent_Arg.getColor().brighter()));
Graphics2.fillRect(Rect1.x, Rect1.y, (int)(LineX*Rect1.width), Rect1.height);
Graphics2.setPaint(new GradientPaint(Rect1.x+(int)(LineX*Rect1.width), Rect1.y, ContentPainterEvent_Arg.getColor().brighter(),
Rect1.x+Rect1.width, Rect1.y, ContentPainterEvent_Arg.getColor()));
Graphics2.fillRect(Rect1.x+(int)(LineX*Rect1.width), Rect1.y, Rect1.width-(int)(LineX*Rect1.width), Rect1.height);
}
}
});
Thread Thread1 = new Thread(){
public void run() {
while (true){
while (LineX<1){
LineX += 0.01f;
try {sleep(20);} catch(InterruptedException InterruptedException_Arg){}
BiSlider2.repaint();
yield();
}
while (LineX>0) {
LineX -= 0.01f;
try {sleep(20);} catch(InterruptedException InterruptedException_Arg){}
BiSlider2.repaint();
yield();
}
}
}
};
Thread1.setPriority(Thread.MIN_PRIORITY);
Thread1.start();
final JPopupMenu JPopupMenu2 = BiSlider2.createPopupMenu();
BiSlider2.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent MouseEvent_Arg){
if (MouseEvent_Arg.getButton()==MouseEvent.BUTTON3){
JPopupMenu2.show(BiSlider2, MouseEvent_Arg.getX(), MouseEvent_Arg.getY());
}
}
});
final SwingBiSlider BiSlider3 = new SwingBiSlider(SwingBiSlider.CENTRAL_BLACK, null);
BiSlider3.setToolTipText("Use a gradient of color to highlight the segments");
BiSlider3.setUniformSegment(true);
BiSlider3.setVisible(true);
BiSlider3.setMinimumValue(0);
BiSlider3.setMaximumValue(100);
BiSlider3.setSegmentSize(10);
BiSlider3.setMinimumColor(Color.YELLOW);
BiSlider3.setMaximumColor(Color.BLUE);
BiSlider3.setColoredValues(20, 70);
BiSlider3.setSound(true);
BiSlider3.setUnit("");
BiSlider3.setPrecise(true);
BiSlider3.setArcSize(18);
BiSlider3.addContentPainterListener(new ContentPainterListener(){
public void paint(ContentPainterEvent ContentPainterEvent_Arg){
Graphics2D Graphics2 = (Graphics2D)ContentPainterEvent_Arg.getGraphics();
Rectangle Rect1 = ContentPainterEvent_Arg.getRectangle();
Rectangle Rect2 = ContentPainterEvent_Arg.getBoundingRectangle();
if (ContentPainterEvent_Arg.getColor()!=null) {
Graphics2.setColor(ContentPainterEvent_Arg.getColor());
Graphics2.setPaint(new GradientPaint(Rect2.x, Rect2.y, ContentPainterEvent_Arg.getColor().brighter(),
Rect2.x+Rect2.width, Rect2.y+Rect2.height, ContentPainterEvent_Arg.getColor().darker()));
Graphics2.fillRect(Rect1.x, Rect1.y, Rect1.width, Rect1.height);
}
}
});
final JPopupMenu JPopupMenu3 = BiSlider3.createPopupMenu();
BiSlider3.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent MouseEvent_Arg){
if (MouseEvent_Arg.getButton()==MouseEvent.BUTTON3){
JPopupMenu3.show(BiSlider3, MouseEvent_Arg.getX(), MouseEvent_Arg.getY());
}
}
});
final SwingBiSlider BiSlider4 = new SwingBiSlider(SwingBiSlider.RGB, null);
BiSlider4.setToolTipText("Like a thermometer");
BiSlider4.setUniformSegment(true);
BiSlider4.setVisible(true);
BiSlider4.setMinimumValue(0);
BiSlider4.setMaximumValue(100);
BiSlider4.setSegmentSize(10);
BiSlider4.setMinimumColor(Color.BLUE);
BiSlider4.setMaximumColor(Color.RED);
BiSlider4.setColoredValues(0, 100);
BiSlider4.setUnit("�");
BiSlider4.setPrecise(true);
BiSlider4.setArcSize(18);
final JPopupMenu JPopupMenu4 = BiSlider4.createPopupMenu();
BiSlider4.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent MouseEvent_Arg){
if (MouseEvent_Arg.getButton()==MouseEvent.BUTTON3){
JPopupMenu4.show(BiSlider4, MouseEvent_Arg.getX(), MouseEvent_Arg.getY());
}
}
});
final SwingBiSlider BiSlider5 = new SwingBiSlider(SwingBiSlider.RGB, null);
BiSlider5.setToolTipText("Like a sea-depth meter");
BiSlider5.setUniformSegment(true);
BiSlider5.setVisible(true);
BiSlider5.setMinimumValue(0);
BiSlider5.setMaximumValue(100);
BiSlider5.setSegmentSize(10);
BiSlider5.setMinimumColor(Color.BLUE);
BiSlider5.setMaximumColor(Color.BLACK);
BiSlider5.setColoredValues(20, 70);
BiSlider5.setBackground(Color.BLACK);
BiSlider5.setSliderBackground(new Color(96, 96, 156));
BiSlider5.setForeground(Color.YELLOW);
BiSlider5.setFont(new Font("Serif", Font.ITALIC|Font.BOLD, 12));
BiSlider5.setUnit("m");
BiSlider5.setPrecise(true);
BiSlider5.setArcSize(10);
BiSlider5.addContentPainterListener(new ContentPainterListener() {
public void paint(ContentPainterEvent ContentPainterEvent_Arg){
Graphics2D Graphics2 = (Graphics2D)ContentPainterEvent_Arg.getGraphics();
Rectangle Rect2 = ContentPainterEvent_Arg.getBoundingRectangle();
double Rand = Math.abs(Math.cos(Math.PI*(Rect2.x+Rect2.width/2) / BiSlider5.getWidth()));
//Rand = (double)(Rect2.x+Rect2.width/2) / BiSlider6.getWidth();
//Rand = Math.random();
float X = ((float)Rect2.x-BiSlider5.getHeight()/2)/BiSlider5.getHeight()*6;
Rand = 1-Math.exp((-1*X*X)/2);
//Rand = ((float)ContentPainterEvent_Arg.getSegmentIndex())/BiSlider6.getSegmentCount();
if (ContentPainterEvent_Arg.getColor()!=null) {
Graphics2.setColor(BiSlider5.getSliderBackground());
//Graphics2.fillRect(Rect2.x, Rect2.y, Rect2.width, (int)((Rand*Rect2.height)));
Graphics2.setColor(ContentPainterEvent_Arg.getColor());
Graphics2.fillRect(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.width+1, 1+(int)(((1-Rand)*Rect2.height)));
}
Graphics2.setColor(Color.WHITE);
//Graphics2.drawRect(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.width-1, (int)(((1-Rand)*Rect2.height)));
Graphics2.drawLine(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.x+Rect2.width-1, Rect2.y+(int)((Rand*Rect2.height)));
Graphics2.drawLine(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.x, Rect2.y+Rect2.height);
Graphics2.drawLine(Rect2.x+Rect2.width, Rect2.y+(int)((Rand*Rect2.height)), Rect2.x+Rect2.width, Rect2.y+Rect2.height);
}
});
final JPopupMenu JPopupMenu5 = BiSlider5.createPopupMenu();
BiSlider5.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent MouseEvent_Arg){
if (MouseEvent_Arg.getButton()==MouseEvent.BUTTON3){
JPopupMenu5.show(BiSlider5, MouseEvent_Arg.getX(), MouseEvent_Arg.getY());
}
}
});
final SwingBiSlider BiSlider6 = new SwingBiSlider(SwingBiSlider.CENTRAL_BLACK, null);
BiSlider6.setToolTipText("When the background is a distribution histogram");
BiSlider6.setUniformSegment(true);
BiSlider6.setVisible(true);
BiSlider6.setMinimumValue(0);
BiSlider6.setMaximumValue(100);
BiSlider6.setSegmentSize(10);
BiSlider6.setMinimumColor(Color.RED);
BiSlider6.setMaximumColor(Color.RED);
BiSlider6.setColoredValues(0, 100);
BiSlider6.setUnit("");
BiSlider6.setPrecise(true);
BiSlider6.setArcSize(0);
BiSlider6.addContentPainterListener(new ContentPainterListener() {
public void paint(ContentPainterEvent ContentPainterEvent_Arg){
Graphics2D Graphics2 = (Graphics2D)ContentPainterEvent_Arg.getGraphics();
Rectangle Rect2 = ContentPainterEvent_Arg.getBoundingRectangle();
double Rand = Math.abs(Math.cos(Math.PI*(Rect2.x+Rect2.width/2) / BiSlider6.getWidth()));
//Rand = (double)(Rect2.x+Rect2.width/2) / BiSlider6.getWidth();
//Rand = Math.random();
float X = ((float)Rect2.x-BiSlider6.getWidth()/2)/BiSlider6.getWidth()*6;
Rand = 1-Math.exp((-1*X*X)/2);
//Rand = ((float)ContentPainterEvent_Arg.getSegmentIndex())/BiSlider6.getSegmentCount();
if (ContentPainterEvent_Arg.getColor()!=null) {
if (ContentPainterEvent_Arg.getSegmentIndex()%2==0)
Graphics2.setColor(BiSlider6.getBackground());
else
Graphics2.setColor(BiSlider6.getSliderBackground());
Graphics2.fillRect(Rect2.x+1, Rect2.y, Rect2.width, 1+(int)(((Rand)*Rect2.height)));
Graphics2.setColor(ContentPainterEvent_Arg.getColor());
Graphics2.fillRect(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.width, 1+(int)(((1-Rand)*Rect2.height)));
}else {
if (ContentPainterEvent_Arg.getSegmentIndex()%2==0)
Graphics2.setColor(BiSlider6.getBackground().darker());
else
Graphics2.setColor(BiSlider6.getSliderBackground().darker());
Graphics2.fillRect(Rect2.x+1, Rect2.y, Rect2.width, 1+(int)(((Rand)*Rect2.height)));
}
Graphics2.setColor(Color.BLACK);
//Graphics2.drawRect(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.width-1, (int)(((1-Rand)*Rect2.height)));
Graphics2.drawLine(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.x+Rect2.width-1, Rect2.y+(int)((Rand*Rect2.height)));
Graphics2.drawLine(Rect2.x, Rect2.y+(int)((Rand*Rect2.height)), Rect2.x, Rect2.y+Rect2.height);
Graphics2.drawLine(Rect2.x+Rect2.width, Rect2.y+(int)((Rand*Rect2.height)), Rect2.x+Rect2.width, Rect2.y+Rect2.height);
}
});
final JPopupMenu JPopupMenu6 = BiSlider6.createPopupMenu();
BiSlider6.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent MouseEvent_Arg){
if (MouseEvent_Arg.getButton()==MouseEvent.BUTTON3){
JPopupMenu6.show(BiSlider6, MouseEvent_Arg.getX(), MouseEvent_Arg.getY());
}
}
});
JFrame1.getContentPane().setLayout(new BorderLayout(2, 2));
JPanel JPanel1= new JPanel();
JPanel1.setLayout(new BoxLayout(JPanel1, BoxLayout.Y_AXIS));
JSplitPane JSplitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, JPanel1, BiSlider6);
JSplitPane JSplitPane1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, JSplitPane2, BiSlider5);
JFrame1.getContentPane().add(BorderLayout.CENTER, JSplitPane1);
JFrame1.getContentPane().add(BorderLayout.WEST, BiSlider4);
JTextArea JTextArea1 = new JTextArea(
"* Six Examples of BiSlider Bean by Frederic Vernier. October 2005. Version 1.4.1\n"+
"* This bean can be imported in a graphical java Interface Builder.\n"+
"* Read the ReadMe.txt File for legal notice and javadoc for API.\n"+
"* Right click to bring a popup menu with user's options.\n"+
"* Double click the triangles to bring a popup slider to set values with precision since version 1.3.5."
);
JTextArea1.setEditable(false);
JPanel1.add(JTextArea1);
JPanel1.add(BiSlider1);
JTextArea JTextArea2 = new JTextArea(
"+ It now works for integer or double values since version 1.3.3\n"+
"+ We force the gaps to be uniform in the 3rd, 4th and 5th exemples (= int division).\n"+
"+ There are 3 different kinds of color interpolation: HSB, CENTRAL_BLACK and RGB\n"+
"+ If SegmentCount equals the range this bean behaves like a range slider.\n"+
"+ Since v1.3.5 corners can be rounded and foreground color can be changed."
);
JTextArea2.setEditable(false);
JPanel1.add(JTextArea2);
JPanel1.add(BiSlider2);
JTextArea JTextArea3 = new JTextArea(
"- Double click a non-colored gap to select it as a the segment.\n"+
"- Click and drag the maximum or the minimum triangle to change them.\n"+
"- Shift+double click to extend the selection with a new gap.\n"+
"- Shift click triangle or segment will align it on graduation.\n"+
"- While dragging a triangle, turn 90� to open the precision popup without releasing the mouse button."
);
JTextArea3.setEditable(false);
JPanel1.add(JTextArea3);
JPanel1.add(BiSlider3);
JTextArea JTextArea4 = new JTextArea(
"- Alt+click+drag a triangle to select a range around the central value.\n"+
"- Drag&Drop the minimum value (text in bold) of the legend to set the SegmentCount.\n"+
"- Shift Drag&Drop the minimum value (text) to stay on the int values.\n"+
"- Double click the minimum or maximum value (text) to change the scope of the bean.\n"+
"- Font painting is now anti-aliased and font can be changed since v1.3.5"
);
JTextArea4.setEditable(false);
JPanel1.add(JTextArea4);
JSlider JSlider1 = new JSlider();
JSlider1.setPaintLabels(true);
JSlider1.setPaintTicks(true);
JSlider1.setPaintTrack(true);
JSlider1.setSnapToTicks(true);
JSlider1.setMajorTickSpacing(10);
JSlider1.setMinorTickSpacing(1);
JPanel1.add(JSlider1);
JTextArea4.setEditable(false);
JPanel1.add(JTextArea4);
//System.out.println("BiSlider1 = "+BiSlider1);
JMenuBar JMenuBar1 = new JMenuBar();
JMenu JMenuPLaF = new JMenu("Look&Feel");
ButtonGroup LnFButtonGroup = new ButtonGroup();
JMenuPLaF.getAccessibleContext().setAccessibleDescription("This menu supports looks and feel selection");
JMenuPLaF.setMnemonic(KeyEvent.VK_L);
//boolean FirstMetal = true;
class PLaFAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private String LnFClassName;
private String Title;
public PLaFAction (String LnFClassName_Arg, String Title_Arg){
super(Title_Arg);
LnFClassName = LnFClassName_Arg;
Title = Title_Arg;
}
public void actionPerformed(ActionEvent ActionEvent_Arg) {
try {
if (Title.startsWith("Metal") && Title.endsWith("Steel")) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
} else if (Title.startsWith("Metal") && Title.endsWith("Ocean")) {
Class<?> Class1 = Class.forName("javax.swing.plaf.metal.OceanTheme");
Object Object1 = Class1.newInstance();
MetalLookAndFeel.setCurrentTheme((MetalTheme)Object1);
} else if (Title.startsWith("Metal") && Title.endsWith("Aqua")) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme(){
public String getName() { return "Aqua"; }
private final ColorUIResource primary1 = new ColorUIResource(102, 153, 153);
private final ColorUIResource primary2 = new ColorUIResource(128, 192, 192);
private final ColorUIResource primary3 = new ColorUIResource(159, 235, 235);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
});
} else if (Title.startsWith("Metal") && Title.endsWith("Charcoal")) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme(){
public String getName() { return "Charcoal"; }
private final ColorUIResource primary1 = new ColorUIResource(66, 33, 66);
private final ColorUIResource primary2 = new ColorUIResource(90, 86, 99);
private final ColorUIResource primary3 = new ColorUIResource(99, 99, 99);
private final ColorUIResource secondary1 = new ColorUIResource(0, 0, 0);
private final ColorUIResource secondary2 = new ColorUIResource(51, 51, 51);
private final ColorUIResource secondary3 = new ColorUIResource(102, 102, 102);
private final ColorUIResource black = new ColorUIResource(222, 222, 222);
private final ColorUIResource white = new ColorUIResource(0, 0, 0);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
protected ColorUIResource getSecondary1() { return secondary1; }
protected ColorUIResource getSecondary2() { return secondary2; }
protected ColorUIResource getSecondary3() { return secondary3; }
protected ColorUIResource getBlack() { return black; }
protected ColorUIResource getWhite() { return white; }
});
} else if (Title.startsWith("Metal") && Title.endsWith("Contrast")) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme() {
public String getName() { return "Contrast"; }
private final ColorUIResource primary1 = new ColorUIResource(0, 0, 0);
private final ColorUIResource primary2 = new ColorUIResource(204, 204, 204);
private final ColorUIResource primary3 = new ColorUIResource(255, 255, 255);
private final ColorUIResource primaryHighlight = new ColorUIResource(102,102,102);
private final ColorUIResource secondary2 = new ColorUIResource(204, 204, 204);
private final ColorUIResource secondary3 = new ColorUIResource(255, 255, 255);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
public ColorUIResource getPrimaryControlHighlight() { return primaryHighlight;}
protected ColorUIResource getSecondary2() { return secondary2; }
protected ColorUIResource getSecondary3() { return secondary3; }
public ColorUIResource getControlHighlight() { return super.getSecondary3(); }
public ColorUIResource getFocusColor() { return getBlack(); }
public ColorUIResource getTextHighlightColor() { return getBlack(); }
public ColorUIResource getHighlightedTextColor() { return getWhite(); }
public ColorUIResource getMenuSelectedBackground() { return getBlack(); }
public ColorUIResource getMenuSelectedForeground() { return getWhite(); }
public ColorUIResource getAcceleratorForeground() { return getBlack(); }
public ColorUIResource getAcceleratorSelectedForeground() { return getWhite(); }
public void addCustomEntriesToTable(UIDefaults table) {
Border blackLineBorder = new BorderUIResource(new LineBorder( getBlack() ));
Object textBorder = new BorderUIResource( new CompoundBorder(
blackLineBorder,
new BasicBorders.MarginBorder()));
table.put( "ToolTip.border", blackLineBorder);
table.put( "TitledBorder.border", blackLineBorder);
table.put( "TextField.border", textBorder);
table.put( "PasswordField.border", textBorder);
table.put( "TextArea.border", textBorder);
table.put( "TextPane.border", textBorder);
table.put( "EditorPane.border", textBorder);
}
});
} else if (Title.startsWith("Metal") && Title.endsWith("Ruby")) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme() {
private final ColorUIResource primary1 = new ColorUIResource(80, 10, 22);
private final ColorUIResource primary2 = new ColorUIResource(193, 10, 44);
private final ColorUIResource primary3 = new ColorUIResource(244, 10, 66);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
});
} else if (Title.startsWith("Metal") && Title.endsWith("Emerald")) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme() {
public String getName() { return "Emerald"; }
private final ColorUIResource primary1 = new ColorUIResource(51, 142, 71);
private final ColorUIResource primary2 = new ColorUIResource(102, 193, 122);
private final ColorUIResource primary3 = new ColorUIResource(153, 244, 173);
protected ColorUIResource getPrimary1() { return primary1; }
protected ColorUIResource getPrimary2() { return primary2; }
protected ColorUIResource getPrimary3() { return primary3; }
});
}
UIManager.setLookAndFeel(LnFClassName);
SwingUtilities.updateComponentTreeUI(JFrame1);
JFrame1.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JFrame1.setLocation((screenSize.width-JFrame1.getWidth())/2,(screenSize.height-JFrame1.getHeight())/2);
} catch (Exception Exception_Arg) {
System.out.println("Failed loading L&F: " + LnFClassName);
Exception_Arg.printStackTrace();
}
}
}
boolean FirstMetal = true;
UIManager.LookAndFeelInfo[] lafis = UIManager.getInstalledLookAndFeels();
//for (int i = 0; i < lafis.length; i++)
//System.out.println("Plaf: " + lafis[i].getClassName());
if (lafis != null)
for (int i = 0; i < lafis.length; i++)
try {
final LookAndFeel currLAF = (LookAndFeel)Class.forName(lafis[i].getClassName()).newInstance();
// System.out.println("Plaf: " + lafis[i].getClassName());
if (currLAF.isSupportedLookAndFeel()) {
JRadioButtonMenuItem jMenuItemLnF = new JRadioButtonMenuItem(lafis[i].getName());
final String LnFClassName = lafis[i].getClassName();
LnFButtonGroup.add(jMenuItemLnF);
if (currLAF instanceof MetalLookAndFeel && FirstMetal && System.getProperty("java.version").startsWith("1.5")) {
jMenuItemLnF.setSelected(true);
jMenuItemLnF.setText("Metal Ocean");
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
FirstMetal = false;
i--;
JMenuPLaF.add(jMenuItemLnF);
}
else if (currLAF instanceof MetalLookAndFeel && !FirstMetal) {
jMenuItemLnF.setText("Metal Steel");
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
JMenuPLaF.add(jMenuItemLnF);
jMenuItemLnF = new JRadioButtonMenuItem("Metal Aqua");
LnFButtonGroup.add(jMenuItemLnF);
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
JMenuPLaF.add(jMenuItemLnF);
jMenuItemLnF = new JRadioButtonMenuItem("Metal Charcoal");
LnFButtonGroup.add(jMenuItemLnF);
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
JMenuPLaF.add(jMenuItemLnF);
jMenuItemLnF = new JRadioButtonMenuItem("Metal High Contrast");
LnFButtonGroup.add(jMenuItemLnF);
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
JMenuPLaF.add(jMenuItemLnF);
jMenuItemLnF = new JRadioButtonMenuItem("Metal Ruby");
LnFButtonGroup.add(jMenuItemLnF);
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
JMenuPLaF.add(jMenuItemLnF);
jMenuItemLnF = new JRadioButtonMenuItem("Metal Emerald");
LnFButtonGroup.add(jMenuItemLnF);
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
JMenuPLaF.add(jMenuItemLnF);
} else{
jMenuItemLnF.setAction(new PLaFAction(LnFClassName, jMenuItemLnF.getText()));
JMenuPLaF.add(jMenuItemLnF);
}
}
} catch (Exception Exception_Arg) {
System.out.println("Failed loading L&F list ");
Exception_Arg.printStackTrace();
}
JMenuBar1.add(JMenuPLaF);
JFrame1.setJMenuBar(JMenuBar1);
//System.out.println("BiSlider1 = "+BiSlider1);
JFrame1.pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JFrame1.setLocation((screenSize.width-JFrame1.getWidth())/2,(screenSize.height-JFrame1.getHeight())/2);
JFrame1.setVisible(true);
}// main()
} | theanuradha/debrief | org.mwc.cmap.TimeController/src/com/visutools/nav/bislider/Test.java | Java | epl-1.0 | 32,465 |
/**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.binding.hue;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
/**
* The {@link HueBindingConstants} class defines common constants, which are
* used across the whole binding.
*
* @author Kai Kreuzer - Initial contribution
* @author Jochen Hiller - Added OSRAM Classic A60 RGBW
*/
public class HueBindingConstants {
public static final String BINDING_ID = "hue";
// List all Thing Type UIDs, related to the Hue Binding
public final static ThingTypeUID THING_TYPE_BRIDGE = new ThingTypeUID(BINDING_ID, "bridge");
public final static ThingTypeUID THING_TYPE_LCT001 = new ThingTypeUID(BINDING_ID, "LCT001");
public final static ThingTypeUID THING_TYPE_LCT002 = new ThingTypeUID(BINDING_ID, "LCT002");
public final static ThingTypeUID THING_TYPE_LCT003 = new ThingTypeUID(BINDING_ID, "LCT003");
public final static ThingTypeUID THING_TYPE_LLC001 = new ThingTypeUID(BINDING_ID, "LLC001");
public final static ThingTypeUID THING_TYPE_LLC006 = new ThingTypeUID(BINDING_ID, "LLC006");
public final static ThingTypeUID THING_TYPE_LLC007 = new ThingTypeUID(BINDING_ID, "LLC007");
public final static ThingTypeUID THING_TYPE_LLC010 = new ThingTypeUID(BINDING_ID, "LLC010");
public final static ThingTypeUID THING_TYPE_LLC011 = new ThingTypeUID(BINDING_ID, "LLC011");
public final static ThingTypeUID THING_TYPE_LLC012 = new ThingTypeUID(BINDING_ID, "LLC012");
public final static ThingTypeUID THING_TYPE_LLC013 = new ThingTypeUID(BINDING_ID, "LLC013");
public final static ThingTypeUID THING_TYPE_LST001 = new ThingTypeUID(BINDING_ID, "LST001");
public final static ThingTypeUID THING_TYPE_LWB004 = new ThingTypeUID(BINDING_ID, "LWB004");
public final static ThingTypeUID THING_TYPE_LWL001 = new ThingTypeUID(BINDING_ID, "LWL001");
public final static ThingTypeUID THING_TYPE_CLASSIC_A60_RGBW = new ThingTypeUID(BINDING_ID, "Classic_A60_RGBW");
public final static ThingTypeUID THING_TYPE_SURFACE_LIGHT_TW = new ThingTypeUID(BINDING_ID, "Surface_Light_TW");
public final static ThingTypeUID THING_TYPE_ZLL_LIGHT = new ThingTypeUID(BINDING_ID, "ZLL_Light");
// List all channels
public static final String CHANNEL_COLORTEMPERATURE = "color_temperature";
public static final String CHANNEL_COLOR = "color";
public static final String CHANNEL_BRIGHTNESS = "brightness";
// Bridge config properties
public static final String HOST = "ipAddress";
public static final String USER_NAME = "userName";
public static final String SERIAL_NUMBER = "serialNumber";
// Light config properties
public static final String LIGHT_ID = "lightId";
}
| clinique/smarthome | extensions/binding/org.eclipse.smarthome.binding.hue/src/main/java/org/eclipse/smarthome/binding/hue/HueBindingConstants.java | Java | epl-1.0 | 3,009 |
/*-
* Copyright (c) 2012, 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.january.dataset;
import org.eclipse.january.dataset.CompoundDataset;
import org.eclipse.january.dataset.Dataset;
import org.eclipse.january.dataset.DatasetFactory;
import org.eclipse.january.dataset.SingleInputBroadcastIterator;
import org.eclipse.january.dataset.Slice;
import org.junit.Assert;
import org.junit.Test;
public class SingleInputBroadcastIteratorTest {
@Test
public void testBroadcastWithNoOutput() {
Dataset a, b, c;
SingleInputBroadcastIterator it;
a = DatasetFactory.createRange(5, Dataset.FLOAT64).reshape(5, 1);
b = DatasetFactory.createRange(2, 8, 1, Dataset.FLOAT64);
it = new SingleInputBroadcastIterator(b, null);
Assert.assertArrayEquals("Broadcast shape", new int[] {6}, it.getShape());
c = DatasetFactory.zeros(it.getShape(), Dataset.FLOAT64);
for (int j = 0; j < 6; j++) {
Assert.assertTrue(it.hasNext());
c.set(it.aDouble, j);
Assert.assertEquals(b.getDouble(j), it.aDouble, 1e-15);
}
// zero-rank dataset
a = DatasetFactory.createFromObject(1);
it = new SingleInputBroadcastIterator(a, null);
it.setOutputDouble(true);
Assert.assertArrayEquals("Broadcast shape", new int[] {}, it.getShape());
c = DatasetFactory.zeros(it.getShape(), Dataset.FLOAT64);
Assert.assertTrue(it.hasNext());
c.set(it.aDouble);
Assert.assertEquals(a.getDouble(), it.aDouble, 1e-15);
// also sliced views
a = DatasetFactory.createRange(5, Dataset.FLOAT64).reshape(5, 1);
b = DatasetFactory.createRange(2, 8, 1, Dataset.FLOAT64).getSliceView(new Slice(null, null, 2));
it = new SingleInputBroadcastIterator(b, null);
Assert.assertArrayEquals("Broadcast shape", new int[] {3}, it.getShape());
c = DatasetFactory.zeros(it.getShape(), Dataset.FLOAT64);
for (int j = 0; j < 3; j++) {
Assert.assertTrue(it.hasNext());
c.set(it.aDouble, j);
Assert.assertEquals(b.getDouble(j), it.aDouble, 1e-15);
Assert.assertEquals(c.getDouble(j), (2*j + 2.0), 1e-15);
}
}
@Test
public void testBroadcastWithOutput() {
Dataset a, c;
SingleInputBroadcastIterator it;
a = DatasetFactory.createRange(10, Dataset.FLOAT64);
c = DatasetFactory.zeros(new int[] {10}, Dataset.FLOAT64);
it = new SingleInputBroadcastIterator(a, c);
Assert.assertArrayEquals("Broadcast shape", new int[] {10}, it.getShape());
for (int i = 0; i < 10; i++) {
Assert.assertTrue(it.hasNext());
Assert.assertEquals(a.getDouble(i), it.aDouble, 1e-15);
c.setObjectAbs(it.oIndex, it.aDouble);
Assert.assertEquals(c.getDouble(i), i, 1e-15);
}
// same output
a = DatasetFactory.createRange(120, Dataset.FLOAT64).reshape(10, 12);
c = a;
it = new SingleInputBroadcastIterator(a, c);
Assert.assertArrayEquals("Broadcast shape", new int[] {10, 12}, it.getShape());
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 12; j++) {
Assert.assertTrue(it.hasNext());
Assert.assertEquals(a.getDouble(i, j), it.aDouble, 1e-15);
c.setObjectAbs(it.oIndex, it.aDouble);
Assert.assertEquals(c.getDouble(i, j), (i*12+j), 1e-15);
}
}
// sliced input/output view
a = DatasetFactory.createRange(240, Dataset.FLOAT64).reshape(20, 12).getSliceView(new Slice(null, null, 2));
c = a;
it = new SingleInputBroadcastIterator(a, c);
Assert.assertArrayEquals("Broadcast shape", new int[] {10, 12}, it.getShape());
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 12; j++) {
Assert.assertTrue(it.hasNext());
Assert.assertEquals(a.getDouble(i, j), it.aDouble, 1e-15);
c.setObjectAbs(it.oIndex, it.aDouble);
Assert.assertEquals(c.getDouble(i, j), (24*i+j), 1e-15);
}
}
// independent output
a = DatasetFactory.createRange(12, Dataset.FLOAT64);
c = DatasetFactory.zeros(new int[] {10, 12}, Dataset.FLOAT64);
it = new SingleInputBroadcastIterator(a, c);
Assert.assertArrayEquals("Broadcast shape", new int[] {10, 12}, it.getShape());
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 12; j++) {
Assert.assertTrue(it.hasNext());
Assert.assertEquals(a.getDouble(j), it.aDouble, 1e-15);
c.setObjectAbs(it.oIndex, it.aDouble);
Assert.assertEquals(c.getDouble(i, j), j, 1e-15);
}
}
// compound output
c = DatasetFactory.zeros(3, new int[] {10, 12}, Dataset.FLOAT64);
it = new SingleInputBroadcastIterator(a, c);
Assert.assertArrayEquals("Broadcast shape", new int[] {10, 12}, it.getShape());
CompoundDataset cc = (CompoundDataset) c;
int isc = c.getElementsPerItem();
double[] ca = new double[isc];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 12; j++) {
Assert.assertTrue(it.hasNext());
Assert.assertEquals(a.getDouble(j), it.aDouble, 1e-15);
c.setObjectAbs(it.oIndex, it.aDouble);
Assert.assertEquals(c.getDouble(i, j), j, 1e-15);
cc.getDoubleArray(ca, i, j);
for (int k = 1; k < isc; k++) {
Assert.assertEquals(ca[k], ca[0], 1e-15);
}
}
}
}
}
| IanMayo/january | org.eclipse.january.test/src/org/eclipse/january/dataset/SingleInputBroadcastIteratorTest.java | Java | epl-1.0 | 5,184 |
/**
* Copyright 2011 Intuit Inc. All Rights Reserved
*/
package com.intuit.tank.proxy.settings.ui;
/*
* #%L
* proxy-extension
* %%
* Copyright (C) 2011 - 2015 Intuit Inc.
* %%
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
* #L%
*/
/**
* IncludeType
*
* @author dangleton
*
*/
public enum IncludeType {
TRANSACTION_INCLUDE("Inclusions"),
TRANSACTION_EXCLUDE("Exclusions"),
BODY_INCLUDE("Body Inclusions"),
BODY_EXCLUDE("Body Exclustions");
private String display;
/**
* @param display
*/
private IncludeType(String display) {
this.display = display;
}
/**
* @return the display
*/
public String getDisplay() {
return display;
}
}
| kevinmcgoldrick/Tank | proxy-parent/proxy-extension/src/main/java/com/intuit/tank/proxy/settings/ui/IncludeType.java | Java | epl-1.0 | 932 |
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.jpa.containers;
import org.jboss.forge.addon.javaee.jpa.DatabaseType;
/**
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*
*/
public class WildflyContainer extends JavaEEDefaultContainer
{
private static final String EXAMPLE_DS = "java:jboss/datasources/ExampleDS";
@Override
public DatabaseType getDefaultDatabaseType()
{
return DatabaseType.H2;
}
@Override
public String getDefaultDataSource()
{
return EXAMPLE_DS;
}
@Override
public String getName(boolean isGUI)
{
return isGUI ? "Wildfly Application Server" : "WILDFLY";
}
}
| oscerd/core | javaee/impl/src/main/java/org/jboss/forge/addon/javaee/jpa/containers/WildflyContainer.java | Java | epl-1.0 | 841 |
/*******************************************************************************
* Copyright (c) 2016, 2018 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.kura.util.collection;
import static java.util.Objects.requireNonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* The Class CollectionUtil contains all necessary static factory methods to
* deal with different collection instances
*/
public final class CollectionUtil {
/** Constructor */
private CollectionUtil() {
// Static Factory Methods container. No need to instantiate.
}
/**
* Converts legacy {@link Dictionary} ADT to {@link Map}
*
* @param dictionary
* The legacy {@link Dictionary} object to transform
* @throws NullPointerException
* if argument is null
* @return the {@link Map} instance wrapping all the key-value association
* from the {@link Dictionary}
*/
public static <K, V> Map<K, V> dictionaryToMap(final Dictionary<K, V> dictionary) {
requireNonNull(dictionary, "Dictionary cannot be null.");
final Map<K, V> map = new HashMap<K, V>(dictionary.size());
final Enumeration<K> keys = dictionary.keys();
while (keys.hasMoreElements()) {
final K key = keys.nextElement();
map.put(key, dictionary.get(key));
}
return map;
}
/**
* Creates a <i>mutable</i>, empty {@code ArrayList} instance.
*
* @param <E>
* the element type
* @return empty ArrayList instance
*/
public static <E> List<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates an {@code ArrayList} instance backed by an array with the
* specified initial size; simply delegates to
* {@link ArrayList#ArrayList(int)}.
*
* @param <E>
* the element type
* @param initialArraySize
* the initial capacity
* @return empty {@code ArrayList} instance with the provided capacity
* @throws IllegalArgumentException
* if argument is less than 0
*/
public static <E> List<E> newArrayListWithCapacity(final int initialArraySize) {
if (initialArraySize < 0) {
throw new IllegalArgumentException("Initial Array size must not be less than 0.");
}
return new ArrayList<E>(initialArraySize);
}
/**
* Creates a <i>mutable</i>, empty {@code ConcurrentHashMap} instance.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @return a new, empty {@code ConcurrentHashMap}
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap() {
return new ConcurrentHashMap<K, V>();
}
/**
* Creates a <i>mutable</i>, empty {@code ConcurrentHashMap} instance.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @param map
* the map to contain
* @return a new, empty {@code ConcurrentHashMap}
* @throws NullPointerException
* if argument is null
*/
public static <K, V> ConcurrentMap<K, V> newConcurrentHashMap(final Map<K, V> map) {
requireNonNull(map, "Map cannot be null.");
return new ConcurrentHashMap<K, V>(map);
}
/**
* Creates an empty {@code CopyOnWriteArrayList} instance.
*
* @param <E>
* the element type
* @return a new, empty {@code CopyOnWriteArrayList}
*/
public static <E> List<E> newCopyOnWriteArrayList() {
return new CopyOnWriteArrayList<E>();
}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @return a new, empty {@code HashMap}
*/
public static <K, V> Map<K, V> newHashMap() {
return new HashMap<K, V>();
}
/**
* Creates a <i>mutable</i> {@code HashMap} instance with the same mappings
* as the specified map.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @param map
* map the mappings to be inserted
* @return a new {@code HashMap}
* @throws NullPointerException
* if argument is null
*/
public static <K, V> Map<K, V> newHashMap(final Map<? extends K, ? extends V> map) {
requireNonNull(map, "Map cannot be null.");
return new HashMap<K, V>(map);
}
/**
* Creates a <i>mutable</i>, initially empty {@code HashSet} instance.
*
* @param <E>
* the element type
* @return a new, empty {@code HashSet}
*/
public static <E> Set<E> newHashSet() {
return new HashSet<E>();
}
/**
* Creates a <i>mutable</i>, {@code HashSet} instance containing the
* provided collection of values.
*
* @param collection
* the collection of values to wrap
* @param <E>
* the element type
* @return a new, empty {@code HashSet}
* @throws NullPointerException
* if argument is null
*/
public static <E> Set<E> newHashSet(final Collection<? extends E> collection) {
requireNonNull(collection, "Collection cannot be null.");
return new HashSet<E>(collection);
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap}
* instance.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @return a new, empty {@code LinkedHashMap}
*/
public static <K, V> Map<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
/**
* Creates a <i>mutable</i>, empty {@code LinkedList} instance (for Java 6
* and earlier).
*
* @param <E>
* the element type
* @return the Linked List
*/
public static <E> List<E> newLinkedList() {
return new LinkedList<E>();
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the
* natural ordering of its elements.
*
* @param <K>
* the key type
* @param <V>
* the value type
* @return a new, empty {@code TreeMap}
*/
public static <K extends Comparable<K>, V> Map<K, V> newTreeMap() {
return new TreeMap<K, V>();
}
}
| darionct/kura | kura/org.eclipse.kura.util/src/main/java/org/eclipse/kura/util/collection/CollectionUtil.java | Java | epl-1.0 | 7,304 |
/*
* Copyright (c) 2012,2013 Big Switch Networks, Inc.
*
* Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
*
* 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.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Originally created by David Erickson, Stanford University
*
* 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.sdnplatform.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator over all values in an iterator of iterators
*
* @param <T> the type of elements returned by this iterator
*/
public class MultiIterator<T> implements Iterator<T> {
Iterator<Iterator<T>> subIterator;
Iterator<T> current = null;
public MultiIterator(Iterator<Iterator<T>> subIterator) {
super();
this.subIterator = subIterator;
}
@Override
public boolean hasNext() {
if (current == null) {
if (subIterator.hasNext()) {
current = subIterator.next();
} else {
return false;
}
}
while (!current.hasNext() && subIterator.hasNext()) {
current = subIterator.next();
}
return current.hasNext();
}
@Override
public T next() {
if (hasNext())
return current.next();
throw new NoSuchElementException();
}
@Override
public void remove() {
if (hasNext())
current.remove();
throw new NoSuchElementException();
}
}
| mandeepdhami/netvirt-ctrl | sdnplatform/src/main/java/org/sdnplatform/util/MultiIterator.java | Java | epl-1.0 | 2,555 |
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.jsdt.internal.ui.refactoring;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
import org.eclipse.ltk.ui.refactoring.TextEditChangeNode;
import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.wst.jsdt.internal.corext.refactoring.changes.MultiStateCompilationUnitChange;
public class RefactoringAdapterFactory implements IAdapterFactory {
private static final Class[] ADAPTER_LIST= new Class[] {
TextEditChangeNode.class
};
public Class[] getAdapterList() {
return ADAPTER_LIST;
}
public Object getAdapter(Object object, Class key) {
if (!TextEditChangeNode.class.equals(key))
return null;
if (!(object instanceof CompilationUnitChange) && !(object instanceof MultiStateCompilationUnitChange))
return null;
return new CompilationUnitChangeNode((TextEditBasedChange)object);
}
}
| boniatillo-com/PhaserEditor | source/thirdparty/jsdt/org.eclipse.wst.jsdt.ui/src/org/eclipse/wst/jsdt/internal/ui/refactoring/RefactoringAdapterFactory.java | Java | epl-1.0 | 1,482 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
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.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.vm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class fdivrp_ST0_ST0 extends Executable
{
public fdivrp_ST0_ST0(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(0);
double freg1 = cpu.fpu.ST(0);
if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1)))
cpu.fpu.setInvalidOperation();
if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1))
cpu.fpu.setZeroDivide();
cpu.fpu.setST(0, freg1/freg0);
cpu.fpu.pop();
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/vm/fdivrp_ST0_ST0.java | Java | gpl-2.0 | 2,072 |
/*
* 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-2017.
*/
package org.telegram.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.LayoutHelper;
import java.io.File;
import java.util.ArrayList;
public class SecretPhotoViewer implements NotificationCenter.NotificationCenterDelegate {
private class FrameLayoutDrawer extends FrameLayout {
public FrameLayoutDrawer(Context context) {
super(context);
setWillNotDraw(false);
}
@Override
protected void onDraw(Canvas canvas) {
getInstance().onDraw(canvas);
}
}
private class SecretDeleteTimer extends FrameLayout {
private String currentInfoString;
private int infoWidth;
private TextPaint infoPaint = null;
private StaticLayout infoLayout = null;
private Paint deleteProgressPaint;
private RectF deleteProgressRect = new RectF();
private Drawable drawable = null;
public SecretDeleteTimer(Context context) {
super(context);
setWillNotDraw(false);
infoPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
infoPaint.setTextSize(AndroidUtilities.dp(15));
infoPaint.setColor(0xffffffff);
deleteProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
deleteProgressPaint.setColor(0xffe6e6e6);
drawable = getResources().getDrawable(R.drawable.circle1);
}
private void updateSecretTimeText() {
if (currentMessageObject == null) {
return;
}
String str = currentMessageObject.getSecretTimeString();
if (str == null) {
return;
}
if (currentInfoString == null || !currentInfoString.equals(str)) {
currentInfoString = str;
infoWidth = (int)Math.ceil(infoPaint.measureText(currentInfoString));
CharSequence str2 = TextUtils.ellipsize(currentInfoString, infoPaint, infoWidth, TextUtils.TruncateAt.END);
infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
invalidate();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
deleteProgressRect.set(getMeasuredWidth() - AndroidUtilities.dp(30), AndroidUtilities.dp(2), getMeasuredWidth() - AndroidUtilities.dp(2), AndroidUtilities.dp(30));
}
@Override
protected void onDraw(Canvas canvas) {
if (currentMessageObject == null || currentMessageObject.messageOwner.destroyTime == 0) {
return;
}
if (drawable != null) {
drawable.setBounds(getMeasuredWidth() - AndroidUtilities.dp(32), 0, getMeasuredWidth(), AndroidUtilities.dp(32));
drawable.draw(canvas);
}
long msTime = System.currentTimeMillis() + ConnectionsManager.getInstance().getTimeDifference() * 1000;
float progress = Math.max(0, (long)currentMessageObject.messageOwner.destroyTime * 1000 - msTime) / (currentMessageObject.messageOwner.ttl * 1000.0f);
canvas.drawArc(deleteProgressRect, -90, -360 * progress, true, deleteProgressPaint);
if (progress != 0) {
int offset = AndroidUtilities.dp(2);
invalidate((int)deleteProgressRect.left - offset, (int)deleteProgressRect.top - offset, (int)deleteProgressRect.right + offset * 2, (int)deleteProgressRect.bottom + offset * 2);
}
updateSecretTimeText();
if (infoLayout != null) {
canvas.save();
canvas.translate(getMeasuredWidth() - AndroidUtilities.dp(38) - infoWidth, AndroidUtilities.dp(7));
infoLayout.draw(canvas);
canvas.restore();
}
}
}
private Activity parentActivity;
private WindowManager.LayoutParams windowLayoutParams;
private FrameLayout windowView;
private FrameLayoutDrawer containerView;
private ImageReceiver centerImage = new ImageReceiver();
private SecretDeleteTimer secretDeleteTimer;
private boolean isVisible = false;
private MessageObject currentMessageObject = null;
@SuppressLint("StaticFieldLeak")
private static volatile SecretPhotoViewer Instance = null;
public static SecretPhotoViewer getInstance() {
SecretPhotoViewer localInstance = Instance;
if (localInstance == null) {
synchronized (PhotoViewer.class) {
localInstance = Instance;
if (localInstance == null) {
Instance = localInstance = new SecretPhotoViewer();
}
}
}
return localInstance;
}
@SuppressWarnings("unchecked")
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.messagesDeleted) {
if (currentMessageObject == null) {
return;
}
int channelId = (Integer) args[1];
if (channelId != 0) {
return;
}
ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>)args[0];
if (markAsDeletedMessages.contains(currentMessageObject.getId())) {
closePhoto();
}
} else if (id == NotificationCenter.didCreatedNewDeleteTask) {
if (currentMessageObject == null || secretDeleteTimer == null) {
return;
}
SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>)args[0];
for(int i = 0; i < mids.size(); i++) {
int key = mids.keyAt(i);
ArrayList<Integer> arr = mids.get(key);
for (Integer mid : arr) {
if (currentMessageObject.getId() == mid) {
currentMessageObject.messageOwner.destroyTime = key;
secretDeleteTimer.invalidate();
return;
}
}
}
}
}
public void setParentActivity(Activity activity) {
if (parentActivity == activity) {
return;
}
parentActivity = activity;
windowView = new FrameLayout(activity);
windowView.setBackgroundColor(0xff000000);
windowView.setFocusable(true);
windowView.setFocusableInTouchMode(true);
if (Build.VERSION.SDK_INT >= 23) {
windowView.setFitsSystemWindows(true);
}
containerView = new FrameLayoutDrawer(activity);
containerView.setFocusable(false);
windowView.addView(containerView);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)containerView.getLayoutParams();
layoutParams.width = LayoutHelper.MATCH_PARENT;
layoutParams.height = LayoutHelper.MATCH_PARENT;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
containerView.setLayoutParams(layoutParams);
containerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_POINTER_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
closePhoto();
}
return true;
}
});
secretDeleteTimer = new SecretDeleteTimer(activity);
containerView.addView(secretDeleteTimer);
layoutParams = (FrameLayout.LayoutParams)secretDeleteTimer.getLayoutParams();
layoutParams.gravity = Gravity.TOP | Gravity.RIGHT;
layoutParams.width = AndroidUtilities.dp(100);
layoutParams.height = AndroidUtilities.dp(32);
layoutParams.rightMargin = AndroidUtilities.dp(19);
layoutParams.topMargin = AndroidUtilities.dp(19);
secretDeleteTimer.setLayoutParams(layoutParams);
windowLayoutParams = new WindowManager.LayoutParams();
windowLayoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
windowLayoutParams.format = PixelFormat.TRANSLUCENT;
windowLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
windowLayoutParams.gravity = Gravity.TOP;
windowLayoutParams.type = WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
windowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
centerImage.setParentView(containerView);
}
public void openPhoto(MessageObject messageObject) {
if (parentActivity == null || messageObject == null || messageObject.messageOwner.media == null || messageObject.messageOwner.media.photo == null) {
return;
}
NotificationCenter.getInstance().addObserver(this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didCreatedNewDeleteTask);
TLRPC.PhotoSize sizeFull = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, AndroidUtilities.getPhotoSize());
int size = sizeFull.size;
if (size == 0) {
size = -1;
}
BitmapDrawable drawable = ImageLoader.getInstance().getImageFromMemory(sizeFull.location, null, null);
if (drawable == null) {
File file = FileLoader.getPathToAttach(sizeFull);
Bitmap bitmap = null;
BitmapFactory.Options options = null;
if (Build.VERSION.SDK_INT < 21) {
options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inPurgeable = true;
options.inSampleSize = 1;
options.inMutable = true;
}
try {
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
} catch (Throwable e) {
FileLog.e(e);
}
if (bitmap != null) {
drawable = new BitmapDrawable(bitmap);
ImageLoader.getInstance().putImageToCache(drawable, sizeFull.location.volume_id + "_" + sizeFull.location.local_id);
}
}
if (drawable != null) {
centerImage.setImageBitmap(drawable);
} else {
centerImage.setImage(sizeFull.location, null, null, size, null, false);
}
currentMessageObject = messageObject;
AndroidUtilities.lockOrientation(parentActivity);
try {
if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(windowView);
}
} catch (Exception e) {
FileLog.e(e);
}
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.addView(windowView, windowLayoutParams);
secretDeleteTimer.invalidate();
isVisible = true;
}
public boolean isVisible() {
return isVisible;
}
public void closePhoto() {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didCreatedNewDeleteTask);
if (parentActivity == null) {
return;
}
currentMessageObject = null;
isVisible = false;
AndroidUtilities.unlockOrientation(parentActivity);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
centerImage.setImageBitmap((Bitmap)null);
}
});
try {
if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(windowView);
}
} catch (Exception e) {
FileLog.e(e);
}
}
public void destroyPhotoViewer() {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.messagesDeleted);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didCreatedNewDeleteTask);
isVisible = false;
currentMessageObject = null;
if (parentActivity == null || windowView == null) {
return;
}
try {
if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeViewImmediate(windowView);
}
windowView = null;
} catch (Exception e) {
FileLog.e(e);
}
Instance = null;
}
private void onDraw(Canvas canvas) {
canvas.save();
canvas.translate(containerView.getWidth() / 2, containerView.getHeight() / 2);
Bitmap bitmap = centerImage.getBitmap();
if (bitmap != null) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
float scaleX = (float) containerView.getWidth() / (float) bitmapWidth;
float scaleY = (float) containerView.getHeight() / (float) bitmapHeight;
float scale = scaleX > scaleY ? scaleY : scaleX;
int width = (int) (bitmapWidth * scale);
int height = (int) (bitmapHeight * scale);
centerImage.setImageCoords(-width / 2, -height / 2, width, height);
centerImage.draw(canvas);
}
canvas.restore();
}
}
| Menziess/Telegram-ASV | TMessagesProj/src/main/java/org/telegram/ui/SecretPhotoViewer.java | Java | gpl-2.0 | 15,214 |
/**
* Copyright (C) 2009-2010 Wilfred Springer
*
* This file is part of Preon.
*
* Preon 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, or (at your option) any later version.
*
* Preon 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
* Preon; see the file COPYING. 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 obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package org.codehaus.preon.emitter;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* A homegrown hexdump tool. Different from the others out there for taking an
* {@link Appendable}, allowing you to use it directly on System.out or
* System.in, use a StringBuilder, or whatever.
*
*/
public class HexUtils {
/**
* Hexidecimal symbols.
*/
private static final char[] symbols = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final int ADDRESS_LENGTH = 6;
/**
* Characters to be printed, indexed by byte.
*/
private static final char[] asc = new char[256];
private static final char SPACE = ' ';
private static final char EXTRA_SPACE = SPACE;
static {
for (int i = 0; i <= 255; i++) {
if (Character.isLetter((char) i)) {
asc[i] = (char) i;
} else {
asc[i] = '.';
}
}
}
/**
* Dumps the byte array to the {@link Appendable} passed in. Think
* {@link #dump(byte[], Appendable, boolean)} with third parameter set to
* <code>false</code>.
*
* @param buffer
* The buffer to be dumped.
* @param out
* The object receiving the dump.
* @throws IOException
* If we cannot write to the {@link Appendable}.
*/
public static void dump(byte[] buffer, Appendable out) throws IOException {
dump(buffer, out, false);
}
/**
* Dumps the byte array to the {@link Appendable} passed in.
*
* @param buffer
* The buffer to be dumped.
* @param out
* The object receiving the dump.
* @param prependAddress
* Whether or not the starting address should be included in the
* output.
* @throws IOException
* If we cannot write to the {@link Appendable}.
*/
public static void dump(byte[] buffer, Appendable out,
boolean prependAddress) throws IOException {
dump(ByteBuffer.wrap(buffer), out, 8, prependAddress);
}
/**
* Dumps the byte array to the {@link Appendable} passed in.
*
* @param buffer
* The buffer to be dumped.
* @param out
* The object receiving the dump.
* @param bytesPerLine
* The number of bytes per line.
* @throws IOException
* If we cannot write to the {@link Appendable}.
*/
public static void dump(byte[] buffer, Appendable out, int bytesPerLine)
throws IOException {
dump(ByteBuffer.wrap(buffer), out, bytesPerLine, false);
}
public static void dump(byte[] buffer, Appendable out, int bytesPerLine, boolean prependAddress)
throws IOException {
dump(ByteBuffer.wrap(buffer), out, bytesPerLine, true);
}
/**
* Dumps the byte array to the {@link Appendable} passed in.
*
* @param buffer
* The buffer to be dumped.
* @param out
* The object receiving the dump.
* @param bytesPerLine
* The number of bytes per line.
* @param prependAddress
* Whether or not the starting address should be included in the
* output.
* @throws IOException
* If we cannot write to the {@link Appendable}.
*/
public static void dump(ByteBuffer buffer, Appendable out, int bytesPerLine,
boolean prependAddress) throws IOException {
byte[] current = new byte[bytesPerLine];
int pos = 0;
int line = 0;
prependAddress(prependAddress, line, bytesPerLine, out);
while (buffer.hasRemaining()) {
current[pos] = buffer.get();
if (pos != 0 && pos % 8 == 0) {
out.append(EXTRA_SPACE);
}
out.append(symbols[hiword(current[pos])]);
out.append(symbols[loword(current[pos])]);
out.append(SPACE);
if (pos == bytesPerLine - 1) {
appendAscii(current, bytesPerLine, out, bytesPerLine);
prependAddress(prependAddress, line, bytesPerLine, out);
pos = 0;
line += 1;
} else {
pos++;
}
}
if (pos != 0) {
for (int i = pos; i < bytesPerLine; i++) {
out.append(" ");
out.append(SPACE);
if (i % 8 == 0) {
out.append(EXTRA_SPACE);
}
}
appendAscii(current, pos, out, bytesPerLine);
}
}
private static void prependAddress(boolean prependAddress, int line, int bytesPerLine, Appendable out) throws IOException {
if (prependAddress) {
String address = Integer.toString(line * bytesPerLine);
for (int i = ADDRESS_LENGTH - address.length(); i >= 0; i--) {
out.append('0');
}
out.append(address);
out.append(EXTRA_SPACE);
}
}
/**
* Appends the ASCII representation of a byte to the line.
*
* @param buffer
* @param nrBytes
* @param out
* @param bytesPerLine
* @throws IOException
*/
private static void appendAscii(byte[] buffer, int nrBytes, Appendable out, int bytesPerLine)
throws IOException {
out.append(" |");
for (int i = 0; i < nrBytes; i++) {
out.append(asc[0xff & buffer[i]]);
}
for (int i = nrBytes; i < bytesPerLine; i++) {
out.append(EXTRA_SPACE);
}
out.append("|\n");
}
/**
* Returns the value of the first 4 bits of a byte.
*
* @param b
* The byte for which we need the first 4 bits.
* @return The value of the first 4 bits of a byte.
*/
private static int hiword(byte b) {
return (0xf0 & b) >> 4;
}
/**
* Returns the value of the last 4 bits of a byte.
*
* @param b
* The byte for which we need the last 4 bits.
* @return The value of the last 4 bits of a byte.
*/
private static int loword(byte b) {
return (0x0f & b);
}
}
| dubrousky/preon | preon-emitter/src/main/java/org/codehaus/preon/emitter/HexUtils.java | Java | gpl-2.0 | 8,088 |
/*
* Copyright 2017 Viktor Csomor
*
* 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.viktorc.pp4j.api;
/**
* An interface that defines an executor that encapsulates a process and allows for executing submissions in this process.
*
* @author Viktor Csomor
*/
public interface ProcessExecutor {
/**
* It has the process sequentially execute the commands contained in the submission and blocks until the execution of every command is
* complete. The result of the submission, if there is one, can be subsequently accessed by calling the
* {@link Submission#getResult()} method.
*
* @param submission The submission to execute.
* @throws FailedCommandException If one of the submission's commands fails.
* @throws DisruptedExecutionException If the executor is stopped before it could complete the execution of the submission, or if there
* is any other error unrelated to the submission that leaves the execution of the submission incomplete. Implementations of
* <code>ProcessExecutor</code> are encouraged to terminate the executor when throwing this exception.
*/
void execute(Submission<?> submission) throws FailedCommandException, DisruptedExecutionException;
} | ViktorC/PSPPool | src/main/java/net/viktorc/pp4j/api/ProcessExecutor.java | Java | gpl-2.0 | 1,729 |
package stochastic_gradient_descent;
/**
* Wrapper object that consists all necessary information for calculating tfidf value for each term.
* Use method getValue() to get the actual tfidf value.
* @author Aniket
*
*/
public class TFIDF implements Comparable<TFIDF>
{
private Number numOfOccurrences;
private Number totalTermsInDocument;
private Number totalDocuments;
private Number numOfDocumentsWithTerm;
public TFIDF(Number occ, Number totTerms, Number totDocs, Number docsWithTerms)
{
numOfOccurrences = occ;
totalTermsInDocument = totTerms;
totalDocuments = totDocs;
numOfDocumentsWithTerm = docsWithTerms;
}
/**
* Calculates the tf-idf value of the current term. For description of tf-idf
* refer to <a href="http://en.wikipedia.org/wiki/Tfidf">^ wikipedia.org/Tfidf</a> <br />
* Because there can be many cases where the current term is not present in any other
* document in the repository, Float.MIN_VALUE is added to the denominator to avoid
* DivideByZero exception
* @return
*/
public Float getValue()
{
float tf = numOfOccurrences.floatValue() / (Float.MIN_VALUE + totalTermsInDocument.floatValue());
float idf = (float) Math.log10(totalDocuments.floatValue() / (Float.MIN_VALUE + numOfDocumentsWithTerm.floatValue()));
return (tf * idf);
}
public int getNumOfOccurrences()
{
return this.numOfOccurrences.intValue();
}
public String toString()
{
return this.getValue().toString();
// return "numOfOccurrences : " + this.numOfOccurrences.intValue() + "\n"
// + "totalTermsInDocument : " + this.totalTermsInDocument.intValue() + "\n"
// + "numOfDocumentsWithTerm : " + this.numOfDocumentsWithTerm.intValue() + "\n"
// + "totalDocuments : " + this.totalDocuments.intValue() + "\n"
// + "TFIDF : " + this.Value();
}
@Override
public int compareTo(TFIDF o)
{
return (int) ((this.getValue() - o.getValue()) * 100);
}
}
| h1395010/stochastic_gradient_descent | src/stochastic_gradient_descent/TFIDF.java | Java | gpl-2.0 | 2,410 |
/*
*
*
* Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included at /legal/license.txt).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
package java.util;
import com.sun.squawk.Java5Marker;
/**
* The <code>Stack</code> class represents a last-in-first-out
* (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
* operations that allow a vector to be treated as a stack. The usual
* <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
* method to <tt>peek</tt> at the top item on the stack, a method to test
* for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
* the stack for an item and discover how far it is from the top.
* <p>
* When a stack is first created, it contains no items.
*
* @version 12/17/01 (CLDC 1.1)
* @since JDK1.0, CLDC 1.0
*/
@Java5Marker
public class Stack<E> extends Vector<E> {
////public class Stack extends Vector {
/**
* Creates an empty Stack.
*/
public Stack() {
}
/**
* Pushes an item onto the top of this stack. This has exactly
* the same effect as:
* <blockquote><pre>
* addElement(item)</pre></blockquote>
*
* @param item the item to be pushed onto this stack.
* @return the <code>item</code> argument.
* @see java.util.Vector#addElement
*/
public E push(E item) {
//// public Object push(Object item) {
addElement(item);
return item;
}
/**
* Removes the object at the top of this stack and returns that
* object as the value of this function.
*
* @return The object at the top of this stack (the last item
* of the <tt>Vector</tt> object).
* @exception EmptyStackException if this stack is empty.
*/
@SuppressWarnings("unchecked")
public synchronized E pop() {
//// public synchronized Object pop() {
Object obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return (E) obj;
//// return obj;
}
/**
* Looks at the object at the top of this stack without removing it
* from the stack.
*
* @return the object at the top of this stack (the last item
* of the <tt>Vector</tt> object).
* @exception EmptyStackException if this stack is empty.
*/
public synchronized Object peek() {
int len = size();
if (len == 0) {
throw new EmptyStackException();
}
return elementAt(len - 1);
}
/**
* Tests if this stack is empty.
*
* @return <code>true</code> if and only if this stack contains
* no items; <code>false</code> otherwise.
*/
public boolean empty() {
return size() == 0;
}
/**
* Returns the 1-based position where an object is on this stack.
* If the object <tt>o</tt> occurs as an item in this stack, this
* method returns the distance from the top of the stack of the
* occurrence nearest the top of the stack; the topmost item on the
* stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt>
* method is used to compare <tt>o</tt> to the
* items in this stack.
*
* @param o the desired object.
* @return the 1-based position from the top of the stack where
* the object is located; the return value <code>-1</code>
* indicates that the object is not on the stack.
*/
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
}
| sics-sse/moped | squawk/cldc/preprocessed/java/util/Stack.java | Java | gpl-2.0 | 4,612 |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package ai;
import com.aionemu.commons.network.util.ThreadPoolManager;
import com.aionemu.gameserver.ai2.AI2Actions;
import com.aionemu.gameserver.ai2.AIName;
import com.aionemu.gameserver.ai2.NpcAI2;
import com.aionemu.gameserver.controllers.observer.ItemUseObserver;
import com.aionemu.gameserver.model.EmotionType;
import com.aionemu.gameserver.model.TaskId;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION;
import static com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE.*;
import com.aionemu.gameserver.network.aion.serverpackets.SM_USE_OBJECT;
import com.aionemu.gameserver.utils.PacketSendUtility;
/**
* @author xTz
* @modified vlog
* @Modified Majka Ajural
*/
@AIName("useitem")
public class ActionItemNpcAI2 extends NpcAI2 {
protected int startBarAnimation = 1;
protected int cancelBarAnimation = 2;
@Override
protected void handleDialogStart(Player player) {
handleUseItemStart(player);
}
protected void handleUseItemStart(final Player player) {
// If the npc is busy for some quest send a message to player
if(getOwner() instanceof Npc && getOwner().getIsQuestBusy()) {
PacketSendUtility.sendPacket(player, STR_ITEM_CANT_USE_UNTIL_DELAY_TIME);
handleUseItemFinish(player);
return;
}
final int delay = getTalkDelay();
if (delay > 1) {
final ItemUseObserver observer = new ItemUseObserver() {
@Override
public void abort() {
player.getController().cancelTask(TaskId.ACTION_ITEM_NPC);
PacketSendUtility.broadcastPacket(player, new SM_EMOTION(player, EmotionType.END_QUESTLOOT, 0, getObjectId()), true);
PacketSendUtility.sendPacket(player, new SM_USE_OBJECT(player.getObjectId(), getObjectId(), 0, cancelBarAnimation));
player.getObserveController().removeObserver(this);
}
};
player.getObserveController().attach(observer);
PacketSendUtility.sendPacket(player, new SM_USE_OBJECT(player.getObjectId(), getObjectId(), getTalkDelay(), startBarAnimation));
PacketSendUtility.broadcastPacket(player, new SM_EMOTION(player, EmotionType.START_QUESTLOOT, 0, getObjectId()), true);
player.getController().addTask(TaskId.ACTION_ITEM_NPC, ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
PacketSendUtility.broadcastPacket(player, new SM_EMOTION(player, EmotionType.END_QUESTLOOT, 0, getObjectId()), true);
PacketSendUtility.sendPacket(player, new SM_USE_OBJECT(player.getObjectId(), getObjectId(), getTalkDelay(), cancelBarAnimation));
player.getObserveController().removeObserver(observer);
handleUseItemFinish(player);
}
}, delay));
} else {
handleUseItemFinish(player);
}
}
protected void handleUseItemFinish(Player player) {
if (getOwner().isInInstance()) {
AI2Actions.handleUseItemFinish(this, player);
}
}
protected int getTalkDelay() {
return getObjectTemplate().getTalkDelay() * 1000;
}
}
| GiGatR00n/Aion-Core-v4.7.5 | AC-Game/data/scripts/system/handlers/ai/ActionItemNpcAI2.java | Java | gpl-2.0 | 4,708 |
/*
* Copyright 2014 by SCSK Corporation.
*
* This file is part of PrimeCloud Controller(TM).
*
* PrimeCloud Controller(TM) 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.
*
* PrimeCloud Controller(TM) 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 PrimeCloud Controller(TM). If not, see <http://www.gnu.org/licenses/>.
*/
package jp.primecloud.auto.dao.crud;
/**
* <p>
* cloudstack_volumeに対応したDAOインタフェースです。
* </p>
*
*/
public interface CloudstackVolumeDao extends BaseCloudstackVolumeDao {
}
| aigamo/primecloud-controller | auto-project/auto-data/src/main/java/jp/primecloud/auto/dao/crud/CloudstackVolumeDao.java | Java | gpl-2.0 | 998 |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package quest.orichalcum_key;
import com.aionemu.gameserver.configs.main.GroupConfig;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.team2.group.PlayerGroup;
import static com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE.*;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.utils.MathUtil;
import com.aionemu.gameserver.utils.PacketSendUtility;
/**
* @author Cheatkiller
*
*/
public class _37107CoolBlueWater extends QuestHandler {
private final static int questId = 37107;
public _37107CoolBlueWater() {
super(questId);
}
public void register() {
qe.addHandlerSideQuestDrop(questId, 700967, 182210040, 5, 100);
qe.registerQuestNpc(700967).addOnTalkEvent(questId);
qe.registerQuestNpc(799901).addOnTalkEvent(questId);
}
@Override
public boolean onDialogEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
DialogAction dialog = env.getDialog();
int targetId = env.getTargetId();
if (qs == null || qs.getStatus() == QuestStatus.NONE || qs.canRepeat()) {
if (targetId == 0) {
if (dialog == DialogAction.QUEST_ACCEPT_1) {
QuestService.startQuest(env);
return closeDialogWindow(env);
}
}
}
if (qs != null && qs.getStatus() == QuestStatus.START) {
if (targetId == 700967) {
if (player.isInGroup2()) {
PlayerGroup group = player.getPlayerGroup2();
for (Player member : group.getMembers()) {
if (member.isMentor() && MathUtil.getDistance(player, member) < GroupConfig.GROUP_MAX_DISTANCE) {
return true;
} else {
PacketSendUtility.sendPacket(player, STR_MSG_DailyQuest_Ask_Mentee);
}
}
}
}
if (targetId == 799901) {
if (dialog == DialogAction.QUEST_SELECT) {
if (qs.getQuestVarById(0) == 0) {
return sendQuestDialog(env, 2375);
}
} else if (dialog == DialogAction.CHECK_USER_HAS_QUEST_ITEM) {
return checkQuestItems(env, 0, 1, true, 5, 2716);
}
}
} else if (qs != null && qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 799901) {
if (dialog == DialogAction.USE_OBJECT) {
return sendQuestDialog(env, 5);
} else {
return sendQuestEndDialog(env);
}
}
}
return false;
}
}
| GiGatR00n/Aion-Core-v4.7.5 | AC-Game/data/scripts/system/handlers/quest/orichalcum_key/_37107CoolBlueWater.java | Java | gpl-2.0 | 4,517 |
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* This is not a test. Actual tests are implemented by concrete subclasses.
* The abstract class AbstractThrowingPushPromises provides a base framework
* to test what happens when push promise handlers and their
* response body handlers and subscribers throw unexpected exceptions.
* Concrete tests that extend this abstract class will need to include
* the following jtreg tags:
*
* @library /test/lib http2/server
* @build jdk.test.lib.net.SimpleSSLContext HttpServerAdapters
* ReferenceTracker AbstractThrowingPushPromises
* <concrete-class-name>
* @modules java.base/sun.net.www.http
* java.net.http/jdk.internal.net.http.common
* java.net.http/jdk.internal.net.http.frame
* java.net.http/jdk.internal.net.http.hpack
* @run testng/othervm -Djdk.internal.httpclient.debug=true <concrete-class-name>
*/
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.ITestContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.BodySubscriber;
import java.net.http.HttpResponse.PushPromiseHandler;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.lang.System.out;
import static java.lang.System.err;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public abstract class AbstractThrowingPushPromises implements HttpServerAdapters {
SSLContext sslContext;
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
static final int ITERATION_COUNT = 1;
// a shared executor helps reduce the amount of threads created by the test
static final Executor executor = new TestExecutor(Executors.newCachedThreadPool());
static final ConcurrentMap<String, Throwable> FAILURES = new ConcurrentHashMap<>();
static volatile boolean tasksFailed;
static final AtomicLong serverCount = new AtomicLong();
static final AtomicLong clientCount = new AtomicLong();
static final long start = System.nanoTime();
public static String now() {
long now = System.nanoTime() - start;
long secs = now / 1000_000_000;
long mill = (now % 1000_000_000) / 1000_000;
long nan = now % 1000_000;
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private volatile HttpClient sharedClient;
static class TestExecutor implements Executor {
final AtomicLong tasks = new AtomicLong();
Executor executor;
TestExecutor(Executor executor) {
this.executor = executor;
}
@Override
public void execute(Runnable command) {
long id = tasks.incrementAndGet();
executor.execute(() -> {
try {
command.run();
} catch (Throwable t) {
tasksFailed = true;
out.printf(now() + "Task %s failed: %s%n", id, t);
err.printf(now() + "Task %s failed: %s%n", id, t);
FAILURES.putIfAbsent("Task " + id, t);
throw t;
}
});
}
}
protected boolean stopAfterFirstFailure() {
return Boolean.getBoolean("jdk.internal.httpclient.debug");
}
@BeforeMethod
void beforeMethod(ITestContext context) {
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
throw new RuntimeException("some tests failed");
}
}
@AfterClass
static final void printFailedTests() {
out.println("\n=========================");
try {
out.printf("%n%sCreated %d servers and %d clients%n",
now(), serverCount.get(), clientCount.get());
if (FAILURES.isEmpty()) return;
out.println("Failed tests: ");
FAILURES.entrySet().forEach((e) -> {
out.printf("\t%s: %s%n", e.getKey(), e.getValue());
e.getValue().printStackTrace(out);
e.getValue().printStackTrace();
});
if (tasksFailed) {
out.println("WARNING: Some tasks failed");
}
} finally {
out.println("\n=========================\n");
}
}
private String[] uris() {
return new String[] {
http2URI_fixed,
http2URI_chunk,
https2URI_fixed,
https2URI_chunk,
};
}
@DataProvider(name = "sanity")
public Object[][] sanity() {
String[] uris = uris();
Object[][] result = new Object[uris.length * 2][];
int i = 0;
for (boolean sameClient : List.of(false, true)) {
for (String uri: uris()) {
result[i++] = new Object[] {uri, sameClient};
}
}
assert i == uris.length * 2;
return result;
}
enum Where {
BODY_HANDLER, ON_SUBSCRIBE, ON_NEXT, ON_COMPLETE, ON_ERROR, GET_BODY, BODY_CF,
BEFORE_ACCEPTING, AFTER_ACCEPTING;
public Consumer<Where> select(Consumer<Where> consumer) {
return new Consumer<Where>() {
@Override
public void accept(Where where) {
if (Where.this == where) {
consumer.accept(where);
}
}
};
}
}
private Object[][] variants(List<Thrower> throwers) {
String[] uris = uris();
// reduce traces by always using the same client if
// stopAfterFirstFailure is requested.
List<Boolean> sameClients = stopAfterFirstFailure()
? List.of(true)
: List.of(false, true);
Object[][] result = new Object[uris.length * sameClients.size() * throwers.size()][];
int i = 0;
for (Thrower thrower : throwers) {
for (boolean sameClient : sameClients) {
for (String uri : uris()) {
result[i++] = new Object[]{uri, sameClient, thrower};
}
}
}
assert i == uris.length * sameClients.size() * throwers.size();
return result;
}
@DataProvider(name = "ioVariants")
public Object[][] ioVariants(ITestContext context) {
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
return new Object[0][];
}
return variants(List.of(
new UncheckedIOExceptionThrower()));
}
@DataProvider(name = "customVariants")
public Object[][] customVariants(ITestContext context) {
if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) {
return new Object[0][];
}
return variants(List.of(
new UncheckedCustomExceptionThrower()));
}
private HttpClient makeNewClient() {
clientCount.incrementAndGet();
return TRACKER.track(HttpClient.newBuilder()
.proxy(HttpClient.Builder.NO_PROXY)
.executor(executor)
.sslContext(sslContext)
.build());
}
HttpClient newHttpClient(boolean share) {
if (!share) return makeNewClient();
HttpClient shared = sharedClient;
if (shared != null) return shared;
synchronized (this) {
shared = sharedClient;
if (shared == null) {
shared = sharedClient = makeNewClient();
}
return shared;
}
}
// @Test(dataProvider = "sanity")
protected void testSanityImpl(String uri, boolean sameClient)
throws Exception {
HttpClient client = null;
out.printf("%ntestNoThrows(%s, %b)%n", uri, sameClient);
for (int i=0; i< ITERATION_COUNT; i++) {
if (!sameClient || client == null)
client = newHttpClient(sameClient);
HttpRequest req = HttpRequest.newBuilder(URI.create(uri))
.build();
BodyHandler<Stream<String>> handler =
new ThrowingBodyHandler((w) -> {},
BodyHandlers.ofLines());
Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> pushPromises =
new ConcurrentHashMap<>();
PushPromiseHandler<Stream<String>> pushHandler = new PushPromiseHandler<>() {
@Override
public void applyPushPromise(HttpRequest initiatingRequest,
HttpRequest pushPromiseRequest,
Function<BodyHandler<Stream<String>>,
CompletableFuture<HttpResponse<Stream<String>>>>
acceptor) {
pushPromises.putIfAbsent(pushPromiseRequest, acceptor.apply(handler));
}
};
HttpResponse<Stream<String>> response =
client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get();
String body = response.body().collect(Collectors.joining("|"));
assertEquals(URI.create(body).getPath(), URI.create(uri).getPath());
for (HttpRequest promised : pushPromises.keySet()) {
out.printf("%s Received promise: %s%n\tresponse: %s%n",
now(), promised, pushPromises.get(promised).get());
String promisedBody = pushPromises.get(promised).get().body()
.collect(Collectors.joining("|"));
assertEquals(promisedBody, promised.uri().toASCIIString());
}
assertEquals(3, pushPromises.size());
}
}
// @Test(dataProvider = "variants")
protected void testThrowingAsStringImpl(String uri,
boolean sameClient,
Thrower thrower)
throws Exception
{
String test = format("testThrowingAsString(%s, %b, %s)",
uri, sameClient, thrower);
testThrowing(test, uri, sameClient, BodyHandlers::ofString,
this::checkAsString, thrower);
}
//@Test(dataProvider = "variants")
protected void testThrowingAsLinesImpl(String uri,
boolean sameClient,
Thrower thrower)
throws Exception
{
String test = format("testThrowingAsLines(%s, %b, %s)",
uri, sameClient, thrower);
testThrowing(test, uri, sameClient, BodyHandlers::ofLines,
this::checkAsLines, thrower);
}
//@Test(dataProvider = "variants")
protected void testThrowingAsInputStreamImpl(String uri,
boolean sameClient,
Thrower thrower)
throws Exception
{
String test = format("testThrowingAsInputStream(%s, %b, %s)",
uri, sameClient, thrower);
testThrowing(test, uri, sameClient, BodyHandlers::ofInputStream,
this::checkAsInputStream, thrower);
}
private <T,U> void testThrowing(String name, String uri, boolean sameClient,
Supplier<BodyHandler<T>> handlers,
Finisher finisher, Thrower thrower)
throws Exception
{
out.printf("%n%s%s%n", now(), name);
try {
testThrowing(uri, sameClient, handlers, finisher, thrower);
} catch (Error | Exception x) {
FAILURES.putIfAbsent(name, x);
throw x;
}
}
private <T,U> void testThrowing(String uri, boolean sameClient,
Supplier<BodyHandler<T>> handlers,
Finisher finisher, Thrower thrower)
throws Exception
{
HttpClient client = null;
for (Where where : Where.values()) {
if (where == Where.ON_ERROR) continue;
if (!sameClient || client == null)
client = newHttpClient(sameClient);
HttpRequest req = HttpRequest.
newBuilder(URI.create(uri))
.build();
ConcurrentMap<HttpRequest, CompletableFuture<HttpResponse<T>>> promiseMap =
new ConcurrentHashMap<>();
Supplier<BodyHandler<T>> throwing = () ->
new ThrowingBodyHandler(where.select(thrower), handlers.get());
PushPromiseHandler<T> pushHandler = new ThrowingPromiseHandler<>(
where.select(thrower),
PushPromiseHandler.of((r) -> throwing.get(), promiseMap));
out.println("try throwing in " + where);
HttpResponse<T> response = null;
try {
response = client.sendAsync(req, handlers.get(), pushHandler).join();
} catch (Error | Exception x) {
throw x;
}
if (response != null) {
finisher.finish(where, req.uri(), response, thrower, promiseMap);
}
}
}
interface Thrower extends Consumer<Where>, Predicate<Throwable> {
}
interface Finisher<T,U> {
U finish(Where w, URI requestURI, HttpResponse<T> resp, Thrower thrower,
Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises);
}
final <T,U> U shouldHaveThrown(Where w, HttpResponse<T> resp, Thrower thrower) {
String msg = "Expected exception not thrown in " + w
+ "\n\tReceived: " + resp
+ "\n\tWith body: " + resp.body();
System.out.println(msg);
throw new RuntimeException(msg);
}
final List<String> checkAsString(Where w, URI reqURI,
HttpResponse<String> resp,
Thrower thrower,
Map<HttpRequest, CompletableFuture<HttpResponse<String>>> promises) {
Function<HttpResponse<String>, List<String>> extractor =
(r) -> List.of(r.body());
return check(w, reqURI, resp, thrower, promises, extractor);
}
final List<String> checkAsLines(Where w, URI reqURI,
HttpResponse<Stream<String>> resp,
Thrower thrower,
Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> promises) {
Function<HttpResponse<Stream<String>>, List<String>> extractor =
(r) -> r.body().collect(Collectors.toList());
return check(w, reqURI, resp, thrower, promises, extractor);
}
final List<String> checkAsInputStream(Where w, URI reqURI,
HttpResponse<InputStream> resp,
Thrower thrower,
Map<HttpRequest, CompletableFuture<HttpResponse<InputStream>>> promises)
{
Function<HttpResponse<InputStream>, List<String>> extractor = (r) -> {
List<String> result;
try (InputStream is = r.body()) {
result = new BufferedReader(new InputStreamReader(is))
.lines().collect(Collectors.toList());
} catch (Throwable t) {
throw new CompletionException(t);
}
return result;
};
return check(w, reqURI, resp, thrower, promises, extractor);
}
private final <T> List<String> check(Where w, URI reqURI,
HttpResponse<T> resp,
Thrower thrower,
Map<HttpRequest, CompletableFuture<HttpResponse<T>>> promises,
Function<HttpResponse<T>, List<String>> extractor)
{
List<String> result = extractor.apply(resp);
for (HttpRequest req : promises.keySet()) {
switch (w) {
case BEFORE_ACCEPTING:
throw new RuntimeException("No push promise should have been received" +
" for " + reqURI + " in " + w + ": got " + promises.keySet());
default:
break;
}
HttpResponse<T> presp;
try {
presp = promises.get(req).join();
} catch (Error | Exception x) {
Throwable cause = findCause(x, thrower);
if (cause != null) {
out.println(now() + "Got expected exception in "
+ w + ": " + cause);
continue;
}
throw x;
}
switch (w) {
case BEFORE_ACCEPTING:
case AFTER_ACCEPTING:
case BODY_HANDLER:
case GET_BODY:
case BODY_CF:
return shouldHaveThrown(w, presp, thrower);
default:
break;
}
List<String> presult = null;
try {
presult = extractor.apply(presp);
} catch (Error | Exception x) {
Throwable cause = findCause(x, thrower);
if (cause != null) {
out.println(now() + "Got expected exception for "
+ req + " in " + w + ": " + cause);
continue;
}
throw x;
}
throw new RuntimeException("Expected exception not thrown for "
+ req + " in " + w);
}
final int expectedCount;
switch (w) {
case BEFORE_ACCEPTING:
expectedCount = 0;
break;
default:
expectedCount = 3;
}
assertEquals(promises.size(), expectedCount,
"bad promise count for " + reqURI + " with " + w);
assertEquals(result, List.of(reqURI.toASCIIString()));
return result;
}
private static Throwable findCause(Throwable x,
Predicate<Throwable> filter) {
while (x != null && !filter.test(x)) x = x.getCause();
return x;
}
static final class UncheckedCustomExceptionThrower implements Thrower {
@Override
public void accept(Where where) {
out.println(now() + "Throwing in " + where);
throw new UncheckedCustomException(where.name());
}
@Override
public boolean test(Throwable throwable) {
return UncheckedCustomException.class.isInstance(throwable);
}
@Override
public String toString() {
return "UncheckedCustomExceptionThrower";
}
}
static final class UncheckedIOExceptionThrower implements Thrower {
@Override
public void accept(Where where) {
out.println(now() + "Throwing in " + where);
throw new UncheckedIOException(new CustomIOException(where.name()));
}
@Override
public boolean test(Throwable throwable) {
return UncheckedIOException.class.isInstance(throwable)
&& CustomIOException.class.isInstance(throwable.getCause());
}
@Override
public String toString() {
return "UncheckedIOExceptionThrower";
}
}
static final class UncheckedCustomException extends RuntimeException {
UncheckedCustomException(String message) {
super(message);
}
UncheckedCustomException(String message, Throwable cause) {
super(message, cause);
}
}
static final class CustomIOException extends IOException {
CustomIOException(String message) {
super(message);
}
CustomIOException(String message, Throwable cause) {
super(message, cause);
}
}
static final class ThrowingPromiseHandler<T> implements PushPromiseHandler<T> {
final Consumer<Where> throwing;
final PushPromiseHandler<T> pushHandler;
ThrowingPromiseHandler(Consumer<Where> throwing, PushPromiseHandler<T> pushHandler) {
this.throwing = throwing;
this.pushHandler = pushHandler;
}
@Override
public void applyPushPromise(HttpRequest initiatingRequest,
HttpRequest pushPromiseRequest,
Function<BodyHandler<T>,
CompletableFuture<HttpResponse<T>>> acceptor) {
throwing.accept(Where.BEFORE_ACCEPTING);
pushHandler.applyPushPromise(initiatingRequest, pushPromiseRequest, acceptor);
throwing.accept(Where.AFTER_ACCEPTING);
}
}
static final class ThrowingBodyHandler<T> implements BodyHandler<T> {
final Consumer<Where> throwing;
final BodyHandler<T> bodyHandler;
ThrowingBodyHandler(Consumer<Where> throwing, BodyHandler<T> bodyHandler) {
this.throwing = throwing;
this.bodyHandler = bodyHandler;
}
@Override
public BodySubscriber<T> apply(HttpResponse.ResponseInfo rinfo) {
throwing.accept(Where.BODY_HANDLER);
BodySubscriber<T> subscriber = bodyHandler.apply(rinfo);
return new ThrowingBodySubscriber(throwing, subscriber);
}
}
static final class ThrowingBodySubscriber<T> implements BodySubscriber<T> {
private final BodySubscriber<T> subscriber;
volatile boolean onSubscribeCalled;
final Consumer<Where> throwing;
ThrowingBodySubscriber(Consumer<Where> throwing, BodySubscriber<T> subscriber) {
this.throwing = throwing;
this.subscriber = subscriber;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
//out.println("onSubscribe ");
onSubscribeCalled = true;
throwing.accept(Where.ON_SUBSCRIBE);
subscriber.onSubscribe(subscription);
}
@Override
public void onNext(List<ByteBuffer> item) {
// out.println("onNext " + item);
assertTrue(onSubscribeCalled);
throwing.accept(Where.ON_NEXT);
subscriber.onNext(item);
}
@Override
public void onError(Throwable throwable) {
//out.println("onError");
assertTrue(onSubscribeCalled);
throwing.accept(Where.ON_ERROR);
subscriber.onError(throwable);
}
@Override
public void onComplete() {
//out.println("onComplete");
assertTrue(onSubscribeCalled, "onComplete called before onSubscribe");
throwing.accept(Where.ON_COMPLETE);
subscriber.onComplete();
}
@Override
public CompletionStage<T> getBody() {
throwing.accept(Where.GET_BODY);
try {
throwing.accept(Where.BODY_CF);
} catch (Throwable t) {
return CompletableFuture.failedFuture(t);
}
return subscriber.getBody();
}
}
@BeforeTest
public void setup() throws Exception {
sslContext = new SimpleSSLContext().get();
if (sslContext == null)
throw new AssertionError("Unexpected null sslContext");
// HTTP/2
HttpTestHandler h2_fixedLengthHandler = new HTTP_FixedLengthHandler();
HttpTestHandler h2_chunkedHandler = new HTTP_ChunkedHandler();
http2TestServer = HttpTestServer.of(new Http2TestServer("localhost", false, 0));
http2TestServer.addHandler(h2_fixedLengthHandler, "/http2/fixed");
http2TestServer.addHandler(h2_chunkedHandler, "/http2/chunk");
http2URI_fixed = "http://" + http2TestServer.serverAuthority() + "/http2/fixed/x";
http2URI_chunk = "http://" + http2TestServer.serverAuthority() + "/http2/chunk/x";
https2TestServer = HttpTestServer.of(new Http2TestServer("localhost", true, sslContext));
https2TestServer.addHandler(h2_fixedLengthHandler, "/https2/fixed");
https2TestServer.addHandler(h2_chunkedHandler, "/https2/chunk");
https2URI_fixed = "https://" + https2TestServer.serverAuthority() + "/https2/fixed/x";
https2URI_chunk = "https://" + https2TestServer.serverAuthority() + "/https2/chunk/x";
serverCount.addAndGet(2);
http2TestServer.start();
https2TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
String sharedClientName =
sharedClient == null ? null : sharedClient.toString();
sharedClient = null;
Thread.sleep(100);
AssertionError fail = TRACKER.check(500);
try {
http2TestServer.stop();
https2TestServer.stop();
} finally {
if (fail != null) {
if (sharedClientName != null) {
System.err.println("Shared client name is: " + sharedClientName);
}
throw fail;
}
}
}
static final BiPredicate<String,String> ACCEPT_ALL = (x, y) -> true;
private static void pushPromiseFor(HttpTestExchange t,
URI requestURI,
String pushPath,
boolean fixed)
throws IOException
{
try {
URI promise = new URI(requestURI.getScheme(),
requestURI.getAuthority(),
pushPath, null, null);
byte[] promiseBytes = promise.toASCIIString().getBytes(UTF_8);
out.printf("TestServer: %s Pushing promise: %s%n", now(), promise);
err.printf("TestServer: %s Pushing promise: %s%n", now(), promise);
HttpHeaders headers;
if (fixed) {
String length = String.valueOf(promiseBytes.length);
headers = HttpHeaders.of(Map.of("Content-Length", List.of(length)),
ACCEPT_ALL);
} else {
headers = HttpHeaders.of(Map.of(), ACCEPT_ALL); // empty
}
t.serverPush(promise, headers, promiseBytes);
} catch (URISyntaxException x) {
throw new IOException(x.getMessage(), x);
}
}
static class HTTP_FixedLengthHandler implements HttpTestHandler {
@Override
public void handle(HttpTestExchange t) throws IOException {
out.println("HTTP_FixedLengthHandler received request to " + t.getRequestURI());
try (InputStream is = t.getRequestBody()) {
is.readAllBytes();
}
URI requestURI = t.getRequestURI();
for (int i = 1; i<2; i++) {
String path = requestURI.getPath() + "/before/promise-" + i;
pushPromiseFor(t, requestURI, path, true);
}
byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);
t.sendResponseHeaders(200, resp.length); //fixed content length
try (OutputStream os = t.getResponseBody()) {
int bytes = resp.length/3;
for (int i = 0; i<2; i++) {
String path = requestURI.getPath() + "/after/promise-" + (i + 2);
os.write(resp, i * bytes, bytes);
os.flush();
pushPromiseFor(t, requestURI, path, true);
}
os.write(resp, 2*bytes, resp.length - 2*bytes);
}
}
}
static class HTTP_ChunkedHandler implements HttpTestHandler {
@Override
public void handle(HttpTestExchange t) throws IOException {
out.println("HTTP_ChunkedHandler received request to " + t.getRequestURI());
byte[] resp = t.getRequestURI().toString().getBytes(StandardCharsets.UTF_8);
try (InputStream is = t.getRequestBody()) {
is.readAllBytes();
}
URI requestURI = t.getRequestURI();
for (int i = 1; i<2; i++) {
String path = requestURI.getPath() + "/before/promise-" + i;
pushPromiseFor(t, requestURI, path, false);
}
t.sendResponseHeaders(200, -1); // chunked/variable
try (OutputStream os = t.getResponseBody()) {
int bytes = resp.length/3;
for (int i = 0; i<2; i++) {
String path = requestURI.getPath() + "/after/promise-" + (i + 2);
os.write(resp, i * bytes, bytes);
os.flush();
pushPromiseFor(t, requestURI, path, false);
}
os.write(resp, 2*bytes, resp.length - 2*bytes);
}
}
}
}
| md-5/jdk10 | test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java | Java | gpl-2.0 | 31,855 |
package net.minecraft.block.material;
public class MaterialPortal extends Material
{
private static final String __OBFID = "CL_00000545";
public MaterialPortal(MapColor p_i2118_1_)
{
super(p_i2118_1_);
}
public boolean isSolid()
{
return false;
}
/**
* Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true
*/
public boolean getCanBlockGrass()
{
return false;
}
/**
* Returns if this material is considered solid or not
*/
public boolean blocksMovement()
{
return false;
}
}
| Myrninvollo/Server | src/net/minecraft/block/material/MaterialPortal.java | Java | gpl-2.0 | 636 |
/*
* Copyright (C) 2016 Enrique Cabrerizo Fernández, Guillermo Ruiz Álvarez
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.uam.eps.bmi.search;
/**
* Class used to store a scored text document resulting from a query.
*
* @author Enrique Cabrerizo Fernández
* @author Guillermo Ruiz Álvarez
*/
public class ScoredTextDocument implements Comparable {
/* Attributes */
private final int docID;
private double score;
/**
* Default constructor for <code>ScoredTextDocument</code> class.
*
* @param docID Unique ID for the text document.
* @param score Score of the text document.
*/
public ScoredTextDocument(int docID, double score) {
this.docID = docID;
this.score = score;
}
/**
* Returns the document id.
*
* @return the document id.
*/
public int getDocID() {
return docID;
}
/**
* Returns the score of the document.
*
* @return the score of the document.
*/
public double getScore() {
return score;
}
/**
* Sets the given value to the current score value.
*
* @param score Value to set to the current value.
*/
public void setScore(double score) {
this.score = score;
}
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object. If the argument is
* not a <code>ScoredTextDocument</code> then returns -1. When -1 is
* received, the caller must discern whether the argument is a
* <code>ScoredTextDocument</code> and the distance with this object is 1,
* or the argument is not at <code>ScoredTextDocument</code> instance.
*
*
* @param t The object to be compared.
* @return a negative integer, zero, or a positive integer as this object is
* less than, equal to, or greater than the specified object. If the
* argument is not a <code>ScoredTextDocument</code> then returns -1.
*/
@Override
public int compareTo(Object t) {
// Null argument.
if (t == null) {
return -1;
}
// Not an ScoredTextDocument
if (t.getClass() != this.getClass()) {
return -1;
}
// Return the values (if the difference is, for instance, 0.1, the
// function returns Math.ceil(0.1) = 1, because the documents are not
// equal.
ScoredTextDocument scoredTextDocument = (ScoredTextDocument) t;
return Double.compare(this.score, scoredTextDocument.score);
}
}
| guillermoruizalv/DataMining | bmi-p4-03/src/es/uam/eps/bmi/search/ScoredTextDocument.java | Java | gpl-3.0 | 3,290 |
package org.georchestra.mapfishapp.ws.classif;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.georchestra.mapfishapp.ws.DocServiceException;
import org.georchestra.mapfishapp.ws.classif.ClassifierCommand.E_ClassifType;
import org.geotools.data.DataSourceException;
import org.geotools.data.FeatureSource;
import org.geotools.data.wfs.WFSDataStore;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.styling.FeatureTypeStyle;
import org.geotools.styling.Rule;
import org.geotools.styling.SLDTransformer;
import org.geotools.styling.Style;
import org.geotools.styling.StyleFactory;
import org.geotools.styling.StyledLayerDescriptor;
import org.geotools.styling.Symbolizer;
import org.geotools.styling.NamedLayer;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
/**
* Provides automatic styling by generating a SLD file given a parameterizable request on a WFS. <br />
* Types of display: polygons filled with colors or proportional symbols <br />
* Types of classification: on continuous or discrete values (Quantile method only) <br />
* Check ClassifierCommand to see all the parameters that need to be provided.
* @see ClassifierCommand
* @author [email protected]
*
*/
public class SLDClassifier {
private ClassifierCommand _command = null;
private StyledLayerDescriptor _sld = null;
private Map<String, UsernamePasswordCredentials> _credentials;
private WFSDataStoreFactory _factory = new WFSDataStoreFactory();
public void setWFSDataStoreFactory(WFSDataStoreFactory f) { _factory = f; }
/**
* This classifier can only be requested by a ClassifierCommand given the wide range of cases and different
* parameters. The SLD is directly generated and be accessed via {@link SLDClassifier#getSLD()}
* @param command ClassifierCommand provides the type of classification and display
* @throws DocServiceException When client request is not valid
*/
public SLDClassifier(Map<String, UsernamePasswordCredentials> credentials, final ClassifierCommand command, WFSDataStoreFactory fac) throws DocServiceException {
this._credentials = credentials;
_command = command;
if (fac != null)
_factory = fac;
// turn off logger
Handler[] handlers = Logger.getLogger("").getHandlers();
for (int index = 0; index < handlers.length; index++ ) {
handlers[index].setLevel( Level.OFF );
}
// start directly the classification
doClassification();
}
/**
* Gets the generated SLD file content
* @return SLD content as String
*/
public String getSLD() {
if (_sld == null) {
throw new RuntimeException("sld has not been generated yet");
}
// transform SLD object into String
SLDTransformer aTransformer = new SLDTransformer();
aTransformer.setIndentation(4);
String xml = "";
String oldTransformer = System.getProperty("javax.xml.transform.TransformerFactory");
try {
System.setProperty("javax.xml.transform.TransformerFactory", org.apache.xalan.processor.TransformerFactoryImpl.class.getName());
xml = aTransformer.transform(_sld);
} catch (TransformerException e) {
e.printStackTrace();
} finally {
if(oldTransformer != null) {
System.setProperty("javax.xml.transform.TransformerFactory", oldTransformer);
}
}
return xml;
}
/**
* Upload all the features from the WFS and then prepare the factories to fulfill the different type of
* classifications and displays
* @throws DocServiceException
*/
private void doClassification() throws DocServiceException {
try {
// connect to the remote WFS
WFSDataStore wfs = connectToWFS(_command.getWFSUrl());
// check if property name exists
int index = wfs.getSchema(_command.getFeatureTypeName()).indexOf(_command.getPropertyName());
if(index == -1) {
throw new DocServiceException(_command.getPropertyName() + " is not an attribute of " + _command.getFeatureTypeName(),
HttpServletResponse.SC_BAD_REQUEST);
}
// Load all the features
FeatureSource<SimpleFeatureType, SimpleFeature> source = wfs.getFeatureSource(_command.getFeatureTypeName());
FeatureCollection<SimpleFeatureType, SimpleFeature> featuresCollection = source.getFeatures();
// We need a display (Symbolizers) and a value (Filters) fatories to generate a SLD file
I_SymbolizerFactory symbolizerFact = null; // create symbols
I_FilterFactory filterFact = null; // create filters
// execute different type of classification given the type requested by user
if (_command.getClassifType() == E_ClassifType.CHOROPLETHS ||
_command.getClassifType() == E_ClassifType.PROP_SYMBOLS) {
// Classification on continuous values. Sorting is needed to classify:
// Double values are mandatory (for now)
if (getDataType(wfs) == String.class) {
// choropleths and prop symbols use quantile classification
// therefore classify on string type has no purpose
throw new DocServiceException("Classification on continous values (" + _command.getClassifType()+ ").\n" +
"Attribute " + _command.getPropertyName() + " is string type." +
" Therefore no classification on contiuous values can be done." +
" It needs be a meaningful comparable type (numerical, date...)." +
" Use unique values classification instead." ,
HttpServletResponse.SC_BAD_REQUEST);
} else if ((getDataType(wfs) != Double.class) &&
(getDataType(wfs) != Float.class) &&
(getDataType(wfs) != Integer.class) &&
(getDataType(wfs) != Long.class) &&
(getDataType(wfs) != Short.class)) {
// for now, only double, float, integer, and short types are supported
// FIXME deal with others numerical types, dates...
// they all must be comparable type as sorting is required for classification
throw new DocServiceException("Classification on " + getDataType(wfs).getName() +
" type is not supported.",
HttpServletResponse.SC_NOT_IMPLEMENTED);
}
// get values to classify
ArrayList<Double> values = getDoubleValues(featuresCollection.features(), _command.getPropertyName());
filterFact = new ContinuousFilterFactory(values, _command.getClassCount(), _command.getPropertyName());
if (_command.getClassifType() == E_ClassifType.CHOROPLETHS) {
switch (_command.getSymbolType()) {
case POLYGON:
symbolizerFact = new PolygonSymbolizerFactory(_command.getClassCount(), _command.getFirstColor(), _command.getLastColor());
break;
case LINE:
symbolizerFact = new LineSymbolizerFactory(_command.getClassCount(), _command.getFirstColor(), _command.getLastColor());
break;
case POINT:
symbolizerFact = new PointSymbolizerFactory(_command.getClassCount(), _command.getFirstColor(), _command.getLastColor());
break;
default:
throw new DocServiceException("Choropleths classification on symbol type: " + _command.getSymbolType() +
" is not supported.", HttpServletResponse.SC_BAD_REQUEST);
}
}
else if (_command.getClassifType() == E_ClassifType.PROP_SYMBOLS) {
switch (_command.getSymbolType()) {
case LINE:
symbolizerFact = new LineSymbolizerFactory(_command.getClassCount(), _command.getMinSize(), _command.getMaxSize());
// customizing is possible
// symbolizerFact.setColor(Color.BLUE);
break;
case POINT:
symbolizerFact = new PointSymbolizerFactory(_command.getClassCount(), _command.getMinSize(), _command.getMaxSize());
// customizing is possible
// symbolizerFact.setColor(Color.BLUE);
// symbolizerFact.setSymbol(StyleBuilder.MARK_CROSS);
break;
default:
throw new DocServiceException("Proportional symbols classification on symbol type: " + _command.getSymbolType() +
" is not supported.", HttpServletResponse.SC_BAD_REQUEST);
}
}
}
else if (_command.getClassifType() == E_ClassifType.UNIQUE_VALUES ) {
// no needs to classify on Unique Values. They can be kept as Strings.
Set<String> values = getUniqueStringValues(featuresCollection.features(), _command.getPropertyName());
filterFact = new DiscreteFilterFactory(values, _command.getPropertyName());
switch (_command.getSymbolType()) {
case POLYGON:
symbolizerFact = new PolygonSymbolizerFactory(_command.getPaletteID(), values.size());
break;
case LINE:
symbolizerFact = new LineSymbolizerFactory(_command.getPaletteID(), values.size());
break;
case POINT:
symbolizerFact = new PointSymbolizerFactory(_command.getPaletteID(), values.size());
break;
default:
throw new DocServiceException("Unique values classification on symbol type: " + _command.getSymbolType() +
" is not supported.", HttpServletResponse.SC_BAD_REQUEST);
}
}
else {
throw new DocServiceException("Unknown classification type: " + _command.getClassifType(),
HttpServletResponse.SC_BAD_REQUEST);
}
assert(symbolizerFact != null);
assert(filterFact != null);
// With those 2 factories a FeatureTypeStyle can be created
FeatureTypeStyle fts = createFeatureTypeStyle(filterFact, symbolizerFact);
// Use FeatureTypeStyle to generate a complete SLD object
_sld = createSLD(fts);
}
catch (IOException e) {
e.printStackTrace(); // could happened when communicating with WFS
}
}
/**
* Creates a FeatureTypeStyle (core part of a SLD file). It is composed by Rules (tag <sld:Rule>) and each Rule
* can contain one Filter (filters values) and one Symbolizer (what's displayed). It Needs 2 factories: <br />
* - I_FilterFactory: gives Filters (tag <ogc:Filter>) <br />
* - I_SymbolizerFactory: gives Symbolizers (tag: <sld:PolygonSymbolizer> or <sld:PointSymbolizer>) <br />
* @param filterFact Filters Factory
* @param symbolizerFact Symbolizers Factory
* @return FeatureTypeStyle (List of Rules)
*/
private FeatureTypeStyle createFeatureTypeStyle(I_FilterFactory filterFact, I_SymbolizerFactory symbolizerFact) {
StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null);
FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle();
Iterator<Symbolizer> symbolizers = symbolizerFact.iterator();
Iterator<Filter> filters = filterFact.iterator();
// use each factory iterator to get their items (Filter and Symbolizer)
// there should be as many symbolizers as many filters
while(symbolizers.hasNext() && filters.hasNext()) {
// create a Rule. A Rule is composed by one Filter and one Symbolizer
Rule rule = styleFactory.createRule();
Filter filter = filters.next();
rule.setSymbolizers(new Symbolizer[] {symbolizers.next()});
rule.setFilter(filter.getGISFilter());
rule.setName(filter.getName());
rule.setTitle(filter.getName());
fts.addRule(rule);
}
if(filters.hasNext()) {
throw new RuntimeException("BUG: more filters than symbolizers");
}
/*
* This piece of code can be added to add a stroke around the polygons.
* This rule does not include a filter, therefore, it is globally applied.
*/
/*
StyleBuilder styleBuilder = new StyleBuilder();
Rule rule = styleFactory.createRule();
Stroke stroke = styleFactory.createStroke(
styleBuilder.literalExpression(Color.BLACK), // color
styleBuilder.literalExpression(1), // width
styleBuilder.literalExpression(1.0)); // opacity
LineSymbolizer ls = styleFactory.createLineSymbolizer(stroke, "");
rule.setSymbolizers(new Symbolizer[] {ls});
fts.addRule(rule);
*/
return fts;
}
/**
* Get the data type of the command attribute
* @param wfs datastore
* @return data type as Class
*/
private Class<?> getDataType(WFSDataStore wfs) {
SimpleFeatureType schema;
Class<?> clazz = null;
try {
schema = wfs.getSchema(_command.getFeatureTypeName()); // get schema
clazz = schema.getType(_command.getPropertyName()).getBinding(); // get data type as Class
} catch (IOException e) {
e.printStackTrace();
}
if (clazz == null) {
throw new RuntimeException("Should never happen, we need to know what type is the attribute of");
}
return clazz;
}
/**
* Gives a connection to a remote WFS
* @param wfsUrl URL of the WFS. Should be a GetCapabilities request
* @return Virtual DataStore. All features can be extracted from it.
* @throws DocServiceException
*/
@SuppressWarnings("unchecked")
private WFSDataStore connectToWFS(final URL wfsUrl) throws DocServiceException {
WFSDataStore wfs = null;
Map m = new HashMap();
try {
UsernamePasswordCredentials credentials = findCredentials(wfsUrl);
if(credentials != null) {
m.put(WFSDataStoreFactory.USERNAME.key, credentials.getUserName());
m.put(WFSDataStoreFactory.PASSWORD.key, credentials.getPassword());
}
// connect to remote WFS
m.put(WFSDataStoreFactory.URL.key, wfsUrl);
m.put(WFSDataStoreFactory.TIMEOUT.key, 60000); // default: 3000
// TODO : .key necessary for those two ?
m.put(WFSDataStoreFactory.TRY_GZIP, true); // try to optimize communication
m.put(WFSDataStoreFactory.ENCODING, "UTF-8"); // try to force UTF-8
// TODO : configurable ?
m.put(WFSDataStoreFactory.MAXFEATURES.key, 2000);
wfs = _factory.createDataStore(m);
}
catch(SocketTimeoutException e) {
throw new DocServiceException("WFS is unavailable", HttpServletResponse.SC_GATEWAY_TIMEOUT);
}
catch(DataSourceException e) {
// happens when wfs url is wrong (missing request or service parameters...)
throw new DocServiceException(e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
}
catch (IOException e) {
e.printStackTrace();
}
return wfs;
}
private UsernamePasswordCredentials findCredentials(URL wfsUrl) {
String targetHost = wfsUrl.getHost();
String ipAddress;
try {
ipAddress = InetAddress.getByName(targetHost).getHostAddress();
} catch (UnknownHostException e) {
ipAddress = "";
}
for(Map.Entry<String, UsernamePasswordCredentials> cred:_credentials.entrySet()) {
String host = cred.getKey();
try {
if(host.equalsIgnoreCase(targetHost) || InetAddress.getByName(host).getHostAddress().equals(ipAddress)) {
return cred.getValue();
}
} catch (UnknownHostException e) {
continue;
}
}
return null;
}
/**
* Extract values as Double from the given features and property name. Executes the same job as
* {@link SLDClassifier#getStringValues(FeatureIterator, String)} provides comparable values: useful to sort.
* @param features Iterator to access all the Features from the WFS request
* @param propertyName Property Name. Property from which values has to be extracted
* @return List of Double values
*/
private ArrayList<Double> getDoubleValues(final FeatureIterator<SimpleFeature> features, final String propertyName) {
ArrayList<Double> values = new ArrayList<Double>();
while(features.hasNext()) {
SimpleFeature feature = features.next();
if (feature.getProperty(_command.getPropertyName()).getValue() == null) {
continue;
}
String val = feature.getProperty(_command.getPropertyName()).getValue().toString();
if(! val.trim().isEmpty() ) { // don't take into account attributes that are empty, it would corrupt the sld file
values.add(Double.parseDouble(val));
}
}
return values;
}
/**
* Extract values as String from the given features and property name. Executes the same job as
* {@link SLDClassifier#getDoubleValues(FeatureIterator, String)} but it is regardless from the type.
* Values are stored in a Set, it guarantees unique values.
* @param features Iterator to access all the Features from the WFS request
* @param propertyName Property Name. Property from which values has to be extracted
* @return List of String values
*/
private Set<String> getUniqueStringValues(final FeatureIterator<SimpleFeature> features, final String propertyName) {
Set<String> values = new HashSet<String>();
while(features.hasNext()) {
SimpleFeature feature = features.next();
String val;
if (feature.getProperty(_command.getPropertyName()).getValue() == null) {
continue;
} else {
val = feature.getProperty(_command.getPropertyName()).getValue().toString();
}
if (! val.trim().isEmpty() ) { // don't take into account attributes that are empty, it would corrupt the sld file
values.add(val);
}
}
return values;
}
/**
* Generate SLD file. Creates everything but the FeatureTypeStyle that must be provided.
* @param fts FeatureTypeStyle. Contains all the rules and therefore the filters and symbolizers
* @return StyledLayerDescriptor SLD file
*/
private StyledLayerDescriptor createSLD(FeatureTypeStyle fts) {
// create SLD
StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null);
StyledLayerDescriptor sld = styleFactory.createStyledLayerDescriptor();
// add named layer
NamedLayer layer = styleFactory.createNamedLayer();
layer.setName(_command.getFeatureTypeName()); // name must match the layer name
fts.setName(_command.getFeatureTypeName());
sld.addStyledLayer(layer);
// add a custom style to the user layer
Style style = styleFactory.createStyle();
style.setName(_command.getFeatureTypeName());
style.setTitle(_command.getFeatureTypeName()+"_classification");
style.addFeatureTypeStyle(fts);
layer.addStyle(style);
return sld;
}
}
| debard/georchestra-ird | mapfishapp/src/main/java/org/georchestra/mapfishapp/ws/classif/SLDClassifier.java | Java | gpl-3.0 | 21,558 |
package org.ovirt.engine.ui.webadmin.widget.vnicProfile;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.ui.common.widget.ScrollableAddRemoveRowWidget;
import org.ovirt.engine.ui.uicommonweb.models.profiles.NetworkProfilesModel;
import org.ovirt.engine.ui.uicommonweb.models.profiles.NewVnicProfileModel;
import org.ovirt.engine.ui.uicommonweb.models.profiles.VnicProfileModel;
import org.ovirt.engine.ui.uicompat.Event;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.IEventListener;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
public class VnicProfilesEditor extends ScrollableAddRemoveRowWidget<NetworkProfilesModel, VnicProfileModel, VnicProfileWidget> {
interface WidgetUiBinder extends UiBinder<Widget, VnicProfilesEditor> {
WidgetUiBinder uiBinder = GWT.create(WidgetUiBinder.class);
}
private Guid dcId;
public VnicProfilesEditor() {
initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this));
}
@Override
public void edit(final NetworkProfilesModel model) {
super.edit(model);
model.getDcId().getEntityChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
dcId = model.getDcId().getEntity();
}
});
}
@Override
protected VnicProfileWidget createWidget(VnicProfileModel value) {
VnicProfileWidget vnicProfileWidget = new VnicProfileWidget();
vnicProfileWidget.edit(value);
return vnicProfileWidget;
}
@Override
protected VnicProfileModel createGhostValue() {
VnicProfileModel profile = new NewVnicProfileModel();
profile.initNetworkQoSList(dcId);
return profile;
}
@Override
protected boolean isGhost(VnicProfileModel value) {
String name = (String) value.getName().getEntity();
return (name == null || name.isEmpty());
}
@Override
protected void toggleGhost(VnicProfileModel value, VnicProfileWidget widget, boolean becomingGhost) {
widget.publicUseEditor.setEnabled(!becomingGhost && value.getPublicUse().getIsChangable());
widget.networkQoSEditor.setEnabled(!becomingGhost && value.getNetworkQoS().getIsChangable());
}
}
| jtux270/translate | ovirt/frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/widget/vnicProfile/VnicProfilesEditor.java | Java | gpl-3.0 | 2,409 |
/**
* License Agreement for OpenSearchServer
*
* Copyright (C) 2010-2014 Emmanuel Keller / Jaeksoft
*
* http://www.open-search-server.com
*
* This file is part of OpenSearchServer.
*
* OpenSearchServer 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.
*
* OpenSearchServer 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 OpenSearchServer.
* If not, see <http://www.gnu.org/licenses/>.
**/
package com.jaeksoft.searchlib.crawler.file.process;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import com.jaeksoft.searchlib.SearchLibException;
import com.jaeksoft.searchlib.crawler.file.database.FilePathItem;
import com.jaeksoft.searchlib.crawler.file.database.FileTypeEnum;
import com.jaeksoft.searchlib.util.IOUtils;
public abstract class FileInstanceAbstract {
protected FileInstanceAbstract parent;
protected FilePathItem filePathItem;
private String path;
private URI uri;
final public static FileInstanceAbstract create(FilePathItem filePathItem,
FileInstanceAbstract parent, String path) throws SearchLibException {
FileInstanceAbstract fileInstance;
try {
fileInstance = filePathItem.getType().getNewInstance();
fileInstance.init(filePathItem, parent, path);
return fileInstance;
} catch (InstantiationException e) {
throw new SearchLibException(e);
} catch (IllegalAccessException e) {
throw new SearchLibException(e);
} catch (URISyntaxException e) {
throw new SearchLibException(e);
} catch (UnsupportedEncodingException e) {
throw new SearchLibException(e);
}
}
protected FileInstanceAbstract() {
}
final protected void init(FilePathItem filePathItem,
FileInstanceAbstract parent, String path)
throws URISyntaxException, SearchLibException,
UnsupportedEncodingException {
this.filePathItem = filePathItem;
this.parent = parent;
this.path = path;
this.uri = init();
}
public abstract URI init() throws SearchLibException, URISyntaxException,
UnsupportedEncodingException;
public URI getURI() {
return uri;
}
public abstract FileTypeEnum getFileType() throws SearchLibException;
public abstract FileInstanceAbstract[] listFilesAndDirectories()
throws URISyntaxException, SearchLibException,
UnsupportedEncodingException;
public abstract FileInstanceAbstract[] listFilesOnly()
throws URISyntaxException, SearchLibException,
UnsupportedEncodingException;
public abstract String getFileName() throws SearchLibException;
public abstract Long getLastModified() throws SearchLibException;
public abstract Long getFileSize() throws SearchLibException;
public abstract InputStream getInputStream() throws IOException;
public String check() throws SearchLibException, URISyntaxException,
UnsupportedEncodingException {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
int limit = 10;
FileInstanceAbstract[] files = listFilesAndDirectories();
if (files != null)
for (FileInstanceAbstract file : files) {
pw.println(file.getPath());
if (--limit == 0) {
pw.println("...");
break;
}
}
return sw.toString();
} finally {
IOUtils.close(pw, sw);
}
}
public FilePathItem getFilePathItem() {
return filePathItem;
}
public FileInstanceAbstract getParent() {
return parent;
}
public String getPath() {
return path;
}
public static interface SecurityInterface {
public List<SecurityAccess> getSecurity() throws IOException;
}
public String getURL() throws MalformedURLException {
if (uri == null)
return null;
return uri.toASCIIString();
}
}
| nvoron23/opensearchserver | src/main/java/com/jaeksoft/searchlib/crawler/file/process/FileInstanceAbstract.java | Java | gpl-3.0 | 4,305 |
package cc.blynk.server.core.model.widgets;
import cc.blynk.server.core.model.enums.PinType;
/**
* The Blynk Project.
* Created by Dmitriy Dumanskiy.
* Created on 21.04.16.
*/
public abstract class NoPinWidget extends Widget {
@Override
public boolean updateIfSame(int deviceId, byte pin, PinType type, String values) {
return false;
}
@Override
public boolean isSame(int deviceId, byte pin, PinType type) {
return false;
}
@Override
public String getJsonValue() {
return null;
}
@Override
public String getModeType() {
return null;
}
@Override
public String getValue(byte pin, PinType type) {
return null;
}
@Override
public boolean hasValue(String searchValue) {
return false;
}
@Override
public void append(StringBuilder sb, int deviceId) {
}
}
| Gspin96/blynk-server | server/core/src/main/java/cc/blynk/server/core/model/widgets/NoPinWidget.java | Java | gpl-3.0 | 894 |
/*
* RealmSpeak is the Java application for playing the board game Magic Realm.
* Copyright (c) 2005-2015 Robin Warren
* E-mail: [email protected]
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
*
* http://www.gnu.org/licenses/
*/
package com.robin.magic_realm.components;
import java.awt.Graphics;
import com.robin.game.objects.GameObject;
import com.robin.general.graphics.TextType;
import com.robin.general.graphics.TextType.Alignment;
import com.robin.general.util.StringUtilities;
import com.robin.magic_realm.components.utility.Constants;
public class GuildChitComponent extends StateChitComponent {
protected GuildChitComponent(GameObject obj) {
super(obj);
darkColor = MagicRealmColor.getColor(obj.getThisAttribute("chit_color"));
}
public String getName() {
return GUILD;
}
public void flip() {
setFaceUp();
}
public void setLightSideUp() {
if (isDarkSideUp()) {
super.setLightSideUp();
updateSize();
}
}
public void setDarkSideUp() {
if (isLightSideUp()) {
super.setDarkSideUp();
updateSize();
}
}
public int getChitSize() {
return isFaceUp()?H_CHIT_SIZE:super.getChitSize();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
TextType tt;
if (getGameObject().hasThisAttribute(Constants.ALWAYS_VISIBLE) || isFaceUp()) {
updateSize();
String icon_type = "house";// gameObject.getThisAttribute(Constants.ICON_TYPE);
String iconDir = "dwellings_c";//gameObject.getThisAttribute(Constants.ICON_FOLDER);
drawIcon(g, iconDir, icon_type, 0.7);
String guild = getGameObject().getName();
tt = new TextType(StringUtilities.capitalize(guild),getChitSize(),"BOLD");
tt.draw(g,0,H_CHIT_SIZE-20,Alignment.Center);
}
}
} | tonycrider/RealmSpeak | magic_realm/utility/components/source/com/robin/magic_realm/components/GuildChitComponent.java | Java | gpl-3.0 | 2,294 |
/*
* Copyright (C) 2015 Dominik Schürmann <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.ui;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.SecretKeyType;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.util.ExportHelper;
public class BackupFragment extends Fragment {
// This ids for multiple key export.
private ArrayList<Long> mIdsForRepeatAskPassphrase;
// This index for remembering the number of master key.
private int mIndex;
static final int REQUEST_REPEAT_PASSPHRASE = 1;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.backup_fragment, container, false);
View backupAll = view.findViewById(R.id.backup_all);
View backupPublicKeys = view.findViewById(R.id.backup_public_keys);
backupAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exportToFile(true);
}
});
backupPublicKeys.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exportToFile(false);
}
});
return view;
}
private void exportToFile(boolean includeSecretKeys) {
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
if (!includeSecretKeys) {
ExportHelper exportHelper = new ExportHelper(activity);
exportHelper.showExportKeysDialog(null, Constants.Path.APP_DIR_FILE, false);
return;
}
new AsyncTask<ContentResolver,Void,ArrayList<Long>>() {
@Override
protected ArrayList<Long> doInBackground(ContentResolver... resolver) {
ArrayList<Long> askPassphraseIds = new ArrayList<>();
Cursor cursor = resolver[0].query(
KeyRings.buildUnifiedKeyRingsUri(), new String[] {
KeyRings.MASTER_KEY_ID,
KeyRings.HAS_SECRET,
}, KeyRings.HAS_SECRET + " != 0", null, null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
SecretKeyType secretKeyType = SecretKeyType.fromNum(cursor.getInt(1));
switch (secretKeyType) {
// all of these make no sense to ask
case PASSPHRASE_EMPTY:
case GNU_DUMMY:
case DIVERT_TO_CARD:
case UNAVAILABLE:
continue;
default: {
long keyId = cursor.getLong(0);
askPassphraseIds.add(keyId);
}
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return askPassphraseIds;
}
@Override
protected void onPostExecute(ArrayList<Long> askPassphraseIds) {
super.onPostExecute(askPassphraseIds);
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
mIdsForRepeatAskPassphrase = askPassphraseIds;
mIndex = 0;
if (mIdsForRepeatAskPassphrase.size() != 0) {
startPassphraseActivity();
return;
}
ExportHelper exportHelper = new ExportHelper(activity);
exportHelper.showExportKeysDialog(null, Constants.Path.APP_DIR_FILE, true);
}
}.execute(activity.getContentResolver());
}
private void startPassphraseActivity() {
Activity activity = getActivity();
if (activity == null) {
return;
}
Intent intent = new Intent(activity, PassphraseDialogActivity.class);
long masterKeyId = mIdsForRepeatAskPassphrase.get(mIndex++);
intent.putExtra(PassphraseDialogActivity.EXTRA_SUBKEY_ID, masterKeyId);
startActivityForResult(intent, REQUEST_REPEAT_PASSPHRASE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_REPEAT_PASSPHRASE) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (mIndex < mIdsForRepeatAskPassphrase.size()) {
startPassphraseActivity();
return;
}
ExportHelper exportHelper = new ExportHelper(getActivity());
exportHelper.showExportKeysDialog(null, Constants.Path.APP_DIR_FILE, true);
}
}
}
| iseki-masaya/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/BackupFragment.java | Java | gpl-3.0 | 6,416 |
/******************************************************************************
* Compilation: javac SequentialSearchST.java
* Execution: java SequentialSearchST
* Dependencies: StdIn.java StdOut.java
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with sequential search in an
* unordered linked list of key-value pairs.
*
* % more tinyST.txt
* S E A R C H E X A M P L E
*
* % java SequentialSearchST < tinyST.txt
* L 11
* P 10
* M 9
* X 7
* H 5
* C 4
* R 3
* A 8
* E 12
* S 0
*
******************************************************************************/
package edu.princeton.cs.algs4;
/**
* The {@code SequentialSearchST} class represents an (unordered)
* symbol table of generic key-value pairs.
* It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>,
* <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods.
* It also provides a <em>keys</em> method for iterating over all of the keys.
* A symbol table implements the <em>associative array</em> abstraction:
* when associating a value with a key that is already in the symbol table,
* the convention is to replace the old value with the new value.
* The class also uses the convention that values cannot be {@code null}. Setting the
* value associated with a key to {@code null} is equivalent to deleting the key
* from the symbol table.
* <p>
* It relies on the {@code equals()} method to test whether two keys
* are equal. It does not call either the {@code compareTo()} or
* {@code hashCode()} method.
* <p>
* This implementation uses a <em>singly linked list</em> and
* <em>sequential search</em>.
* The <em>put</em> and <em>delete</em> operations take Θ(<em>n</em>).
* The <em>get</em> and <em>contains</em> operations takes Θ(<em>n</em>)
* time in the worst case.
* The <em>size</em>, and <em>is-empty</em> operations take Θ(1) time.
* Construction takes Θ(1) time.
* <p>
* For additional documentation, see
* <a href="https://algs4.cs.princeton.edu/31elementary">Section 3.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class SequentialSearchST<Key, Value> {
private int n; // number of key-value pairs
private Node first; // the linked list of key-value pairs
// a helper linked list data type
private class Node {
private Key key;
private Value val;
private Node next;
public Node(Key key, Value val, Node next) {
this.key = key;
this.val = val;
this.next = next;
}
}
/**
* Initializes an empty symbol table.
*/
public SequentialSearchST() {
}
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return n;
}
/**
* Returns true if this symbol table is empty.
*
* @return {@code true} if this symbol table is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Returns true if this symbol table contains the specified key.
*
* @param key the key
* @return {@code true} if this symbol table contains {@code key};
* {@code false} otherwise
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public boolean contains(Key key) {
if (key == null) throw new IllegalArgumentException("argument to contains() is null");
return get(key) != null;
}
/**
* Returns the value associated with the given key in this symbol table.
*
* @param key the key
* @return the value associated with the given key if the key is in the symbol table
* and {@code null} if the key is not in the symbol table
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public Value get(Key key) {
if (key == null) throw new IllegalArgumentException("argument to get() is null");
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key))
return x.val;
}
return null;
}
/**
* Inserts the specified key-value pair into the symbol table, overwriting the old
* value with the new value if the symbol table already contains the specified key.
* Deletes the specified key (and its associated value) from this symbol table
* if the specified value is {@code null}.
*
* @param key the key
* @param val the value
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void put(Key key, Value val) {
if (key == null) throw new IllegalArgumentException("first argument to put() is null");
if (val == null) {
delete(key);
return;
}
for (Node x = first; x != null; x = x.next) {
if (key.equals(x.key)) {
x.val = val;
return;
}
}
first = new Node(key, val, first);
n++;
}
/**
* Removes the specified key and its associated value from this symbol table
* (if the key is in this symbol table).
*
* @param key the key
* @throws IllegalArgumentException if {@code key} is {@code null}
*/
public void delete(Key key) {
if (key == null) throw new IllegalArgumentException("argument to delete() is null");
first = delete(first, key);
}
// delete key in linked list beginning at Node x
// warning: function call stack too large if table is large
private Node delete(Node x, Key key) {
if (x == null) return null;
if (key.equals(x.key)) {
n--;
return x.next;
}
x.next = delete(x.next, key);
return x;
}
/**
* Returns all keys in the symbol table as an {@code Iterable}.
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in the symbol table
*/
public Iterable<Key> keys() {
Queue<Key> queue = new Queue<Key>();
for (Node x = first; x != null; x = x.next)
queue.enqueue(x.key);
return queue;
}
/**
* Unit tests the {@code SequentialSearchST} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
SequentialSearchST<String, Integer> st = new SequentialSearchST<String, Integer>();
for (int i = 0; !StdIn.isEmpty(); i++) {
String key = StdIn.readString();
st.put(key, i);
}
for (String s : st.keys())
StdOut.println(s + " " + st.get(s));
}
}
/******************************************************************************
* Copyright 2002-2020, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar 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.
*
* algs4.jar 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 algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
| kevin-wayne/algs4 | src/main/java/edu/princeton/cs/algs4/SequentialSearchST.java | Java | gpl-3.0 | 8,175 |
package com.baselet.control.enums;
/**
* priority enum, must be ordered from highest to lowest priority!
* if a specific ordering is necessary but not possible with the current Priorities, just insert a new one in between
*/
public enum Priority {
HIGHEST, HIGH, DEFAULT, LOW, LOWEST
} | schuellerf/umlet | umlet-elements/src/main/java/com/baselet/control/enums/Priority.java | Java | gpl-3.0 | 298 |
package com.chanapps.four.fragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.WindowManager;
import com.chanapps.four.activity.R;
import com.chanapps.four.data.BoardSortType;
/**
* Created with IntelliJ IDEA.
* User: arley
* Date: 12/14/12
* Time: 12:44 PM
* To change this template use File | Settings | File Templates.
*/
public class BoardSortOrderDialogFragment extends DialogFragment {
public interface NotifySortOrderListener {
void onSortOrderChanged(BoardSortType boardSortType);
}
public static final String TAG = BoardSortOrderDialogFragment.class.getSimpleName();
private BoardSortType sortType;
private CharSequence[] array;
private NotifySortOrderListener notifySortOrderListener;
public BoardSortOrderDialogFragment(){}
public BoardSortOrderDialogFragment(BoardSortType sortType) {
super();
this.sortType = sortType;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
array = getResources().getTextArray(R.array.sort_order_types);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setTitle(R.string.sort_order_menu)
.setSingleChoiceItems(array, sortType.ordinal(), selectSortOrderListener)
;
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
return dialog;
}
public BoardSortOrderDialogFragment setNotifySortOrderListener(NotifySortOrderListener notifySortOrderListener) {
this.notifySortOrderListener = notifySortOrderListener;
return this;
}
private DialogInterface.OnClickListener selectSortOrderListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
CharSequence item = array[which];
sortType = BoardSortType.valueOfDisplayString(getActivity(), item.toString());
if (notifySortOrderListener != null)
notifySortOrderListener.onSortOrderChanged(sortType);
dismiss();
}
};
@Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
}
| Greznor/chanu | app/src/main/java/com/chanapps/four/fragment/BoardSortOrderDialogFragment.java | Java | gpl-3.0 | 2,487 |
/*
* Symphony - A modern community (forum/SNS/blog) platform written in Java.
* Copyright (C) 2012-2017, b3log.org & hacpai.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 org.b3log.symphony.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Set;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.model.User;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.JSONRenderer;
import org.b3log.latke.util.Requests;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.service.ArticleQueryService;
import org.b3log.symphony.service.CommentMgmtService;
import org.b3log.symphony.service.CommentQueryService;
import org.b3log.symphony.service.UserQueryService;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Comment processor.
*
* <ul>
* <li>(/api/v1/stories/{id}/reply), POST</li>
* </ul>
*
* @author <a href="http://wdx.me">DX</a>
* @version 1.0.0.2, Jan 21, 2017
* @since 1.3.0
*/
@RequestProcessor
public class CommentProcessor {
/**
* Article query service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* Comment query service.
*/
@Inject
private CommentQueryService commentQueryService;
/**
* Comment management service.
*/
@Inject
private CommentMgmtService commentMgmtService;
/**
* Reply.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param id the story's id
* @throws ServletException servlet exception
* @throws JSONException json ex
* @throws IOException io ex
* @throws ServiceException service ex
*/
@RequestProcessing(value = "/api/v1/comments/{id}/reply", method = HTTPRequestMethod.POST)
public void reply(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response,
final String id) throws ServletException, JSONException, IOException, ServiceException {
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final JSONObject comment = commentQueryService.getCommentById(avatarViewMode, id);
comment(context, request, response, comment.optString(Comment.COMMENT_ON_ARTICLE_ID));
}
/**
* Comment.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @param id the story's id
* @throws ServletException servlet exception
* @throws JSONException json ex
* @throws IOException io ex
*/
@RequestProcessing(value = "/api/v1/stories/{id}/reply", method = HTTPRequestMethod.POST)
public void comment(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response,
final String id) throws ServletException, JSONException, IOException {
final String auth = request.getHeader("Authorization");
if (auth == null) {//TODO validate
return;
}
final String email = new JSONObject(auth.substring("Bearer ".length())).optString("userEmail");
final String httpBody = getBody(request);
final String content = httpBody.substring("comment[body]=".length());
final String ip = Requests.getRemoteAddr(request);
final String ua = request.getHeader("User-Agent");
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
final JSONObject ret = new JSONObject();
renderer.setJSONObject(ret);
final JSONObject comment = new JSONObject();
comment.put(Comment.COMMENT_CONTENT, content);
comment.put(Comment.COMMENT_ON_ARTICLE_ID, id);
comment.put(Comment.COMMENT_IP, "");
if (StringUtils.isNotBlank(ip)) {
comment.put(Comment.COMMENT_IP, ip);
}
comment.put(Comment.COMMENT_UA, "");
if (StringUtils.isNotBlank(ua)) {
comment.put(Comment.COMMENT_UA, ua);
}
try {
final JSONObject currentUser = userQueryService.getUserByEmail(email);
if (null == currentUser) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
final String currentUserName = currentUser.optString(User.USER_NAME);
final JSONObject article = articleQueryService.getArticle(id);
final String articleContent = article.optString(Article.ARTICLE_CONTENT);
final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID);
final JSONObject articleAuthor = userQueryService.getUser(articleAuthorId);
final String articleAuthorName = articleAuthor.optString(User.USER_NAME);
final Set<String> userNames = userQueryService.getUserNames(articleContent);
if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
&& !articleAuthorName.equals(currentUserName)) {
boolean invited = false;
for (final String userName : userNames) {
if (userName.equals(currentUserName)) {
invited = true;
break;
}
}
if (!invited) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
comment.put(Comment.COMMENT_AUTHOR_ID, currentUser.optString(Keys.OBJECT_ID));
comment.put(Comment.COMMENT_T_COMMENTER, currentUser);
final String newId = commentMgmtService.addComment(comment);
final JSONObject commentObj = new JSONObject();
commentObj.put("id", Long.valueOf(newId)); //FIXME need the comment id.
commentObj.put("body_html", content);
commentObj.put("depth", 0);
commentObj.put("user_display_name", currentUser.optString(User.USER_NAME));
commentObj.put("user_job", currentUser.optString(UserExt.USER_INTRO));
commentObj.put("vote_count", 0);
commentObj.put("created_at", formatDate(new Date()));
commentObj.put("user_portrait_url", comment.optString(Comment.COMMENT_T_ARTICLE_AUTHOR_THUMBNAIL_URL));
ret.put("comment", commentObj);
} catch (final ServiceException e) {
ret.put("error", "invalid");
}
}
/**
* The demand format date.
*
* @param date the original date
* @return the format date like "2015-08-03T07:26:57Z"
*/
private String formatDate(final Object date) {
return DateFormatUtils.format(((Date) date).getTime(), "yyyy-MM-dd")
+ "T" + DateFormatUtils.format(((Date) date).getTime(), "HH:mm:ss") + "Z";
}
/**
* Get request body.
*
* @param request req
* @return body
* @throws IOException io exception
*/
public String getBody(final HttpServletRequest request) throws IOException {
final StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
final InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
final char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (final IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException ex) {
throw ex;
}
}
}
return stringBuilder.toString();
}
}
| gaozhenhong/symphony | src/main/java/org/b3log/symphony/api/CommentProcessor.java | Java | gpl-3.0 | 9,549 |
/*
* moco, the Monty Compiler
* Copyright (c) 2013-2014, Monty's Coconut, All rights reserved.
*
* This file is part of moco, the Monty Compiler.
*
* moco 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.0 of the License, or (at your option) any later version.
*
* moco 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.
*
* Linking this program and/or its accompanying libraries statically or
* dynamically with other modules is making a combined work based on this
* program. Thus, the terms and conditions of the GNU General Public License
* cover the whole combination.
*
* As a special exception, the copyright holders of moco give
* you permission to link this programm and/or its accompanying libraries
* 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 program and/or its accompanying libraries.
* If you modify this library, you may extend this exception to your version of
* the program or library, but you are not obliged to do so. If you do not wish
* to do so, delete this exception statement from your version.
*
* You should have received a copy of the GNU General Public
* License along with this library.
*/
package de.uni.bremen.monty.moco.ast;
import java.util.BitSet;
/** Baseclass for every node in the AST. */
public abstract class BasicASTNode implements ASTNode {
public static final int NUMBER_OF_VISITORS = 6;
/** Sourcecode position of this node. */
private final Position position;
/** Parent node. */
private ASTNode parentNode;
/** Associated scope. */
private Scope scope;
private BitSet visitedFlags = new BitSet(NUMBER_OF_VISITORS);
private boolean isNativeNode = false;
/** Constructor.
*
* @param position
* Position of this node */
public BasicASTNode(Position position) {
this.position = position;
}
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName();
}
/** Get parent node.
*
* @return the parent node */
@Override
public ASTNode getParentNode() {
return parentNode;
}
/** Get parent node.
*
* @return the parent node */
public ASTNode getParentNodeByType(Class type) {
ASTNode n = getParentNode();
while ((!type.isInstance(n)) && (n != null)) {
n = n.getParentNode();
}
return n;
}
/** Set parent node.
*
* @param parentNode
* the parent node */
@Override
public void setParentNode(ASTNode parentNode) {
this.parentNode = parentNode;
}
/** Get the sourcecode position.
*
* @return the position */
@Override
public Position getPosition() {
return position;
}
/** Set the associated scope.
*
* @param scope
* the associated scope */
@Override
public void setScope(Scope scope) {
this.scope = scope;
}
/** Get the accociated scope.
*
* @return the scope */
@Override
public Scope getScope() {
return scope;
}
@Override
public BitSet getVisitedFlags() {
return visitedFlags;
}
public boolean isNative() {
return isNativeNode;
}
public void setNative(boolean isNative) {
isNativeNode = isNative;
}
}
| MontysCoconut/moco | src/main/java/de/uni/bremen/monty/moco/ast/BasicASTNode.java | Java | gpl-3.0 | 3,737 |
package com.idega.data.query;
/**
* Used for adding CRITERIA1 OR CRITERIA2 to a statement.
* <p/>
* <pre>
* SelectQuery select = ...
* ...
* Criteria a = new MatchCriteria(table, col1, "=", 1);
* Criteria b = new MatchCriteria(table, col2, "=", 2);
* select.addCriteria(new OR(a, b));
* // ( table.col1 = 1 OR table.col2 = 2 )
* </pre>
*
* @author <a href="mailto:[email protected]">Joe Walnes</a>
*/
public class OR extends BaseLogicGroup {
public OR(Criteria left, Criteria right) {
super("OR", left, right);
}
}
| idega/com.idega.core | src/java/com/idega/data/query/OR.java | Java | gpl-3.0 | 574 |
import java.io.IOException;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Enumeration;
/**
* The Player class represents the physical appearance data of a Player which
* can be seen by other Players.
*
* @author Darryl
*
*/
public class Player extends SOEObject {
public final static long serialVersionUID = 1l;
private final static byte iNumberOfHams = 9;
// Variables
// Numbers
private boolean bActive = false;
private int iCurrentTerminalID = 0;
private long lAccountID = 0;
// private long lCellID = 0;
private long lGuildID = 0;
// private boolean bIsGM = false;
private int moodID = 0;
private int emoteID = 0;
private int iFlourishID = 0;
private int iTellCount = 0;
private boolean bClearPerformedAnimation = false;
private byte iStance = Constants.STANCE_STANDING;
private int iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_STANDING;
private int iRaceID = 0; // Human Male
private int spawnCRC = 0; // This is the CRC value of the character's
// species??
private int iBankCredits = 0;
private int iInventoryCredits = 0;
private int iIncapTimer = 0;
private float fScale = 0.0f;
private int iBattleFatigue = 0;
private float fCurrentVelocity = 0.0f;
private float fMaxVelocity = Constants.MAX_PLAYER_RUN_SPEED_METERS_SEC;
private float fCurrentAcceleration = 1.0f;
private long lTargetID = 0;
private float fTurnRadius = Constants.DEFAULT_TURN_RADIUS;
private short iConLevel = 0;
private int iDanceID = 0;
private int iSongID = 0;
private int iUnknownCREO3Bitmask = Constants.BITMASK_CREO3_PLAYER;
private int iServerID = 0; // PlanetID for the Combined program, cluster
// sub-server for the clustered program.
private String sPlayerCluster;
private int iTotalLots = 10;
private int iUsedLots = 0;
public long devLastShuttleID;
// Objects
// Arrays
private int[] iCurrentHam;
private int[] iMaxHam;
private int[] iHamWounds;
private int[] iHamEncumberance;
private int[] iHamMigrationTarget;
private int iHamMigrationPoints = 0;
private final static int HAM_MIGRATION_TIME_MINIMUM_MS = 300000;
private final static int HAM_MIGRATION_TIME_MAXIMUM_MS = 600000;
private final static long HAM_MIGRATION_TIME_MINIMUM_KK_MS = PacketUtils
.toKK(HAM_MIGRATION_TIME_MINIMUM_MS);
private final static long HAM_MIGRATION_TIME_MAXIMUM_KK_MS = PacketUtils
.toKK(HAM_MIGRATION_TIME_MAXIMUM_MS);
private long lState; // Vectors
private Vector<TangibleItem> vInventoryItemsList;
private Vector<SkillMods> vSkillModsList; // This one has to be there.
private Vector<PlayerFactions> vFactionList; // This one kinda has to be
// here... need the faction
// AND the faction amount.
// Strings
private String sFirstName;
private String sLastName;
private String sPerformedAnimation;
private String sClientEffectString;
private String sMoodString = "none";
private String sPerformanceString;
private String sBiography;
private String sStartingPlanetName = null;
private String sStartingProfession = null;
private float[] fStartingCoordinates;
private float[] fHouseCoordinates;
private float[] fBankCoordinates;
private int iBankPlanetID = -1;
private int iHomePlanetID = -1;
// SOE Objects / extensions
private TangibleItem tHairObject;
private TangibleItem tPlayerInventory;
private TangibleItem tDatapad;
private TangibleItem tBank;
private TangibleItem tMissionBag;
private Weapon equippedWeapon;
private Weapon defaultWeapon;
private Instrument equippedInstrument;
private PlayerItem thePlayer;
// Server related
private int iRebelFactionPoints = 0; // These could be part of the
// PlayerFactions vector...
private int iImperialFactionPoints = 0;
private ConcurrentHashMap<Long, Structure> vPlayerStructures;
private boolean bIsDeleted;
private long lTotalPlayerOnlineTime;
private long lPlayerCreationDate;
private boolean bEnteringTutorial;
private TutorialObject tutorial;
private boolean bIsJedi = false;
/**************************************************************/
/************ These Values will vary with skills **************/
private int iMaxCalledDroids; // def 2
private int iMaxCalledAnimalPets; // def 1
private int iMaxCalledFactionPets; // def 2
private int iMaxDataPadDroids; // def 4
private int iMaxDataPadAnimalPets; // def 3
private int iMaxDataPadFactionPets; // def 2
private int iMaxCalledPets; // def 2
private int iMaxDataPadPets; // def 9
/**************************************************************/
/************************************************************
***************** TRANSIENT VARIABLES **********************
************************************************************/
private transient int iDefenderListUpdateCounter = 0;
private transient int iCurrentHamUpdateCount = 0;
private transient int iMaxHamUpdateCount = 0;
private transient int iHamModifiersUpdateCount = 0;
private transient int iHamWoundsUpdateCount = 0;
private transient int iHamEncumberanceUpdateCount = 0;
private transient boolean bIsMounted = false;
private transient int iEquippedItemUpdateCount = 0;
private transient long lCurrentDeedInPlacementMode;
// private transient boolean isWarping = false;
// private transient boolean isLoading = false;
public transient int iWarpOperation; // YAK! Why public? It was public for
// testing, warp will be revamped on
// the next patch MUAHAHAHAHA!
private transient boolean bOnlineStatus;
private transient int iFriendsListUpdateCounter;
private transient long lBurstRunexpiryTimer = 0;
private transient boolean bBurstRunning = false;
private transient long lBurstRunRechargeTimer = 0;
private transient long lNextHeightMapUpdate;
private transient boolean bHeightMapCollect;
private transient int iGroupInviteCounter;
private transient long lGroupHost;
private transient long lGroupTime;
private transient int iGroupUpdateCounter;
private transient int iSkillModsUpdateCount = 0;
private transient int LastSUIBox;
private transient int iLastSuiWindowType;
private transient boolean bIsTraveling = false;
private transient long lCurrentMount = 0;
private transient long lLastConversationNPC = 0;
private transient int iSkillBeingPurchasedIndex;
private transient int iSkillListUpdateCount = 0;
private transient int iTradeRequestCounter;
private transient boolean bPlayerRequestedLogout;
private transient long lLogoutTimer;
private transient long lLogoutSpamTimer;
// private transient int currentTimeOn;
private transient long heartbeatTimer;
private transient long lHealDelayMS = 0;
private transient boolean bHasOutstandingTeachingOffer = false;
private transient boolean bDisconnectIgnore;
private transient int iPlaySoundUpdateCounter;
private transient long lListeningToID;
private transient boolean bIsInCamp;
private transient long forageCooldown;
private transient boolean isForaging;
private transient byte forageType;
private transient LinkedList<CommandQueueItem> vCommandQueue;
private transient String sLastSuiWindowType;
private transient Hashtable<Integer, SOEObject> SUIListWindowObjectList;
private transient ConcurrentHashMap<Integer, SUIWindow> PendingSUIWindowList;
private transient String[] sLastConversationMenu;
private transient Vector<DialogOption> vLastConversationMenuOptions;
private transient Vector<TradeObject> vTradeRequests;
private transient Vector<Long> vIncomingTradeRequest;
private transient TradeObject currentTradeObject;
private transient Player teachingStudent = null;
private transient Player teacher;
private transient Skills skillOfferedByTeacher = null;
private transient SOEObject synchronizedObject = null;
private transient Vector<CraftingSchematic> vLastCreatedCraftingSchematicList = null;
private transient Camp currentCampObject;
private transient Vector<CreaturePet> vCalledPets;
private transient Vector<CreaturePet> vFriendPets;
private transient Waypoint lastForageArea;
private transient ManufacturingSchematic currentManufacturingSchematic;
private transient Vector<Player> vPlayersListening;
private transient Vector<Player> vPlayersWatching;
private transient Player playerBeingListened;
private transient Player playerBeingWatched;
private transient boolean isDancing;
private transient boolean isPlayingMusic;
private transient long lDancetick;
private transient long lMusicTick;
private transient int iFlourishBonus;
private transient long lFlourishTick;
private transient long lEffectTick;
private transient long lRandomWatchPlayerTick;
private transient long lMaskScentDelayTime;
private transient int iPerformanceID;
private transient boolean C60X11;
private transient int[] iHamModifiers; // Buffs
private transient long[] lHamMigrationRateKKMS;
private transient long[] lMaxHamKK; // Bitsets
private transient long[] iHamRegenerationKKMS;
private transient long[] lPoisonTickTimeMS;
private transient long[] lBleedTickTimeMS;
private transient long[] lDiseaseTickTimeMS;
private transient long[] lFireTickTimeMS;
private transient int[] iPoisonPotency;
private transient int[] iBleedPotency;
private transient int[] iDiseasePotency;
private transient int[] iFirePotency;
private transient long[] lPoisonTimeMS;
private transient long[] lDiseaseTimeMS;
private transient long[] lFireTimeMS;
private transient long[] lBleedTimeMS;
private transient long[] lStateTimer;
private transient Vector<Long> vDefenderList; // This can be a Vector<Long>
private transient Vector<Long> vAllSpawnedObjectIDs;
private transient Vector<SOEObject> vDelayedSpawnObjects; // This is an
// extremely bad
// way of doing
// this.
private transient Vector<Long> lNextDelayedSpawn;
private transient TangibleItem lastUsedSurveyTool = null;
private transient ZoneServer server;
private transient ZoneClient client;
private transient Group myGroup;
private transient Terminal LastUsedTravelTerminal;
private transient BuffEffect[] vBuffEffects;
private transient boolean bIsSampling;
/**
* private boolean bEnteringTutorial; private TutorialObject tutorial;
*
* private transient boolean bDisconnectIgnore;
*/
/**
* Constructs a new Player for use on the given Zone Server.
*
* @param server
* -- The Zone Server this Player belongs on.
*/
public Player(ZoneServer server) {
super();
// System.out.println("Creating New Player Object");
/*
* StackTraceElement [] ste = Thread.currentThread().getStackTrace();
* for(int i = 0; i < ste.length;i++) { System.out.println("ST: " + i +
* " | " + ste[i].toString()); }
*/
iPlaySoundUpdateCounter = -1;
heartbeatTimer = 0;
lPlayerCreationDate = System.currentTimeMillis();
bPlayerRequestedLogout = false;
bIsDeleted = false;
if (server != null) {
this.server = server;
setServerID(server.getServerID());
sPlayerCluster = server.getClusterName();
thePlayer = new PlayerItem(this);
// setSTFFileName(SOEObject.PLAYER_STF);
}
iCurrentHam = new int[iNumberOfHams];
iMaxHam = new int[iNumberOfHams];
iHamRegenerationKKMS = new long[iNumberOfHams];
iHamModifiers = new int[iNumberOfHams];
iHamWounds = new int[iNumberOfHams];
iHamEncumberance = new int[iNumberOfHams];
iHamMigrationTarget = new int[iNumberOfHams];
lHamMigrationRateKKMS = new long[iNumberOfHams];
lMaxHamKK = new long[iNumberOfHams];
vBuffEffects = new BuffEffect[Constants.BUFF_EFFECTS.length];
lPoisonTickTimeMS = new long[iNumberOfHams];
lBleedTickTimeMS = new long[iNumberOfHams];
lDiseaseTickTimeMS = new long[iNumberOfHams];
lFireTickTimeMS = new long[iNumberOfHams];
lPoisonTimeMS = new long[iNumberOfHams];
lBleedTimeMS = new long[iNumberOfHams];
lDiseaseTimeMS = new long[iNumberOfHams];
lFireTimeMS = new long[iNumberOfHams];
iPoisonPotency = new int[iNumberOfHams];
iBleedPotency = new int[iNumberOfHams];
iDiseasePotency = new int[iNumberOfHams];
iFirePotency = new int[iNumberOfHams];
lStateTimer = new long[Constants.NUM_STATES];
lState = 0;
// Vectors
vAllSpawnedObjectIDs = new Vector<Long>();
vInventoryItemsList = new Vector<TangibleItem>();
// vCommandQueue = new LinkedList<CommandQueueItem>();
vSkillModsList = new Vector<SkillMods>();
vDefenderList = new Vector<Long>();
vFactionList = new Vector<PlayerFactions>();
vCommandQueue = new LinkedList<CommandQueueItem>();
// Strings
sFirstName = "";
sLastName = "";
sPerformedAnimation = "";
sClientEffectString = "";
sMoodString = "none";
sPerformanceString = "";
sBiography = "";
sStartingPlanetName = "";
sStartingProfession = "";
// SOE Objects / extensions
tHairObject = null;
tPlayerInventory = null;
equippedWeapon = null;
myGroup = null;
// Server related
client = null;
bOnlineStatus = false;
iFriendsListUpdateCounter = 0;
fStartingCoordinates = new float[3];
fBankCoordinates = new float[3];
fHouseCoordinates = new float[3];
LastSUIBox = 0;
SUIListWindowObjectList = new Hashtable<Integer, SOEObject>();
PendingSUIWindowList = new ConcurrentHashMap<Integer, SUIWindow>();
sLastConversationMenu = new String[7];
vLastConversationMenuOptions = new Vector<DialogOption>();
lNextDelayedSpawn = new Vector<Long>();
/*
* vMissionBag = new Vector<MissionObject>(); for(int i = 0; i < 15;
* i++) { MissionObject m = new MissionObject();
* m.setID(client.getServer().getNextObjectID());
* m.setSMissionSTFString(""); m.setSMissionTag1("");
* m.setSMissionGiver(new String [1]); m.setSMissionTag2("");
* m.setIDisplayObjectCRC(0xE191DBAB); m.setOrigX(0); m.setOrigY(0);
* m.setOrigZ(0); m.setX(0); m.setY(0); m.setZ(0); vMissionBag.add(m); }
*/
/* Set Default Pet values */
iMaxCalledDroids = 2; // def 2
iMaxCalledAnimalPets = 1; // def 1
iMaxCalledFactionPets = 2; // def 2
iMaxDataPadDroids = 4; // def 4
iMaxDataPadAnimalPets = 3; // def 3
iMaxDataPadFactionPets = 2; // def 2
iMaxCalledPets = 2; // def 2
iMaxDataPadPets = 9; // def 9
/*----------------*/
}
public boolean isEnteringTutorial() {
return bEnteringTutorial;
}
public void setEnteringTutorial(boolean bEnteringTutorial) {
this.bEnteringTutorial = bEnteringTutorial;
}
public TutorialObject getTutorial() {
return tutorial;
}
public void setTutorial(TutorialObject tutorial) {
this.tutorial = tutorial;
}
public void setFriendsListUpdateCounter(int i) {
iFriendsListUpdateCounter = i;
}
public int getFriendsListUpdateCounter(boolean bIncrement) {
if (bIncrement) {
iFriendsListUpdateCounter++;
}
return iFriendsListUpdateCounter;
}
public void setOnlineStatus(boolean s) {
bOnlineStatus = s;
}
public boolean getOnlineStatus() {
return bOnlineStatus;
}
public String getPlayerCluster() {
return sPlayerCluster;
}
public void fixPlayerCluster(String sClusterName) {
sPlayerCluster = sClusterName;
}
/**
* Returns the location this Player first appeared at in the SWG world.
*
* @return The player's birthplace.
*/
public String getBirthplace() {
return sStartingPlanetName;
}
/**
* Initializes the player's birthplace for biographical purposes.
*
* @param s
* -- The point where the Player first appeared at in the SWG
* world.
*/
public void initializeBirthplace(String s) {
sStartingPlanetName = s;
}
/**
* Sets the player's birthplace for biographical purposes. If the birthplace
* has already been set, this function does nothing.
*
* @param s
* -- The birthplace.
*/
public void setBirthplace(String s) {
if (sStartingPlanetName == null || sStartingPlanetName.equals("")) {
sStartingPlanetName = s;
}
}
// Important note: Since an array variable is a pointer, these CANNOT point
// to the exact same object.
// Therefore, we MUST make a copy of the object.
/**
* This function initializes the Player's HAM bars.
*
* @param i
* -- The HAM.
*/
public void setHam(int[] hams) {
iMaxHam = hams;
for (int i = 0; i < hams.length; i++) {
lMaxHamKK[i] = PacketUtils.toKK(hams[i]);
iCurrentHam[i] = iMaxHam[i];
}
iCurrentHam = Arrays.copyOf(hams, hams.length);
iHamMigrationTarget = Arrays.copyOf(hams, hams.length);
for (int i = 0; i <= iMaxHam.length - 3; i += 3) {
iHamRegenerationKKMS[i] = PacketUtils.toKK(iMaxHam[i + 2])
/ TIME_DIVIDER_ON_REGENERATION_RATE_MS; // Regenerate rate
// -- if Action,
// regenerate your
// Stamina in action
// every 100
// seconds.
}
}
/**
* This function updates the current HAM bar of index with the new value.
*
* @param index
* -- The sub HAM bar to update.
* @param newHam
* -- The new value of the given sub HAM bar.
*/
protected synchronized int updateCurrentHam(int index, int newHam) {
int iDifference = 0;
if (iStance != Constants.STANCE_DEAD) {
int iPreviousHam = iCurrentHam[index];
iCurrentHam[index] = Math
.min(
(iCurrentHam[index] + newHam),
((iMaxHam[index] + iHamModifiers[index]) - iHamWounds[index]));
iDifference = iCurrentHam[index] - iPreviousHam;
// System.out.println("Update current ham. Previous: " +
// iPreviousHam + ", current: " + iCurrentHam[index]);
if (iCurrentHam[index] != iPreviousHam) {
// Deltas message.
// System.out.println("New currentHam["+index+"] = " +
// iCurrentHam[index]);
if (client != null) {
try {
client.insertPacket(PacketFactory.buildHAMDelta(this,
(byte) 6, (short) 13, index,
iCurrentHam[index], true),
Constants.PACKET_RANGE_CHAT_RANGE);
} catch (Exception e) {
// D'oh!
DataLog.logEntry("Error building ham deltas message: "
+ e.toString(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.bLogToConsole, false);
// System.out.println("Error building ham deltas message: "
// + e.toString());
e.printStackTrace();
}
}
}
if (iCurrentHam[index] < 0) {
// Incapacitate me!
if (iStance == Constants.STANCE_INCAPACITATED) {
// We're still incapacitated.
lIncapacitationRemainingTimeMS = Math.max(PacketUtils
.toKK(Math.abs(iCurrentHam[index]))
/ iHamRegenerationKKMS[index],
lIncapacitationRemainingTimeMS);
updateIncapacitationTimer(lIncapacitationRemainingTimeMS);
iIncapTimer = (int) (lIncapacitationRemainingTimeMS / 1000);
} else {
removeState(Constants.STATE_COMBAT);
if (this instanceof NPC) {
setStance(null, Constants.STANCE_DEAD, true); // If I'm
// an
// NPC,
// I
// straight
// up
// die.
} else {
setStance(null, Constants.STANCE_INCAPACITATED, true); // If
// I'm
// a
// Player,
// I
// might
// incapacitate,
// or
// die,
// depending
// on
// how
// often
// I
// incapacitate.
}
// removeState(Constants.STATE_COMBAT);
if (lastUsedSurveyTool != null) {
lastUsedSurveyTool.stopSurveying();
bIsSampling = false;
}
// How long to regenerate?
if (thePlayer != null) {
if (!thePlayer.setPlayerJustIncapacitated()) {
lIncapacitationRemainingTimeMS = Math.max(
PacketUtils.toKK(Math
.abs(iCurrentHam[index]))
/ iHamRegenerationKKMS[index],
lIncapacitationRemainingTimeMS);
updateIncapacitationTimer(lIncapacitationRemainingTimeMS);
iIncapTimer = (int) (lIncapacitationRemainingTimeMS / 1000);
} else {
setStance(null, Constants.STANCE_DEAD, true);
bSeenCloneWindow = false;
}
}
}
}
}
return iDifference;
}
private transient boolean bSeenCloneWindow = false;
private long lIncapacitationRemainingTimeMS = 0;
private void updateIncapacitationTimer(long lTimerMS) {
int iPreviousIncapTimer = iIncapTimer;
iIncapTimer = (int) (lTimerMS / 1000);
if (iIncapTimer != iPreviousIncapTimer) {
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 3, (short) 1,
(short) 7, this, iIncapTimer));
} catch (Exception e) {
// D'oh!
}
}
}
/**
* This function updates the max HAM bar of index with the new value.
*
* @param index
* -- The sub HAM bar to update.
* @param newHam
* -- The new value of the given sub HAM bar.
*/
protected synchronized void updateMaxHam(int index, int newHam,
boolean bUpdateCurrentHam, boolean bFlyText) {
int iPreviousHam = iMaxHam[index];
iMaxHam[index] = newHam;
// System.out.println("Update current ham. Previous: " + iPreviousHam +
// ", current: " + iCurrentHam[index]);
if (iMaxHam[index] != iPreviousHam) {
if (index % 3 == 2) {
iHamRegenerationKKMS[index - 2] = PacketUtils
.toKK(iMaxHam[index])
/ TIME_DIVIDER_ON_REGENERATION_RATE_MS; // Regenerate
// rate -- if
// Action,
// regenerate
// your Stamina
// in action
// every 100
// seconds.
}
// Deltas message.
// System.out.println("New currentHam["+index+"] = " +
// iCurrentHam[index]);
try {
client.insertPacket(PacketFactory.buildHAMDelta(this, (byte) 1,
(short) 2, index, iMaxHam[index], bFlyText),
Constants.PACKET_RANGE_CHAT_RANGE);
if (bUpdateCurrentHam) {
updateCurrentHam(index, newHam);
}
} catch (Exception e) {
// D'oh!
DataLog.logEntry("Error building ham deltas message: "
+ e.toString(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Error building ham deltas message: " +
// e.toString());
e.printStackTrace();
}
}
}
/**
* This function updates the current HAM wounds bar of index with the new
* value.
*
* @param index
* -- The sub HAM wounds bar to update.
* @param newHam
* -- The amount to alter the HAM wound bar by.
*/
protected synchronized void updateHAMWounds(int index, int hamDelta,
boolean bFlyText) {
int iPreviousHam = iHamWounds[index];
iHamWounds[index] = Math.max((iHamWounds[index] + hamDelta), 0);
iHamWounds[index] = Math.min(iHamWounds[index], (iMaxHam[index] - 1));
// System.out.println("Update current ham. Previous: " + iPreviousHam +
// ", current: " + iCurrentHam[index]);
if (iHamWounds[index] != iPreviousHam) {
// Deltas message.
System.out.println("New HAMWounds[" + index + "] = "
+ iHamWounds[index]);
try {
if (client != null) {
client.insertPacket(PacketFactory.buildHAMDelta(this,
(byte) 3, (short) 0x11, index, iHamWounds[index],
bFlyText), Constants.PACKET_RANGE_CHAT_RANGE);
}
} catch (Exception e) {
// D'oh!
DataLog.logEntry("Error building ham deltas message: "
+ e.toString(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Error building ham deltas message: " +
// e.toString());
e.printStackTrace();
}
if (iCurrentHam[index] > ((iMaxHam[index] + iHamModifiers[index]) - iHamWounds[index])) {
int difference = ((iMaxHam[index] + iHamModifiers[index]) - iHamWounds[index])
- iCurrentHam[index];
System.out.println("HAM update needed. Altering ham down by "
+ (difference * -1));
updateCurrentHam(index, difference);
}
}
}
/**
* This function updates the max HAM bar of index with the new value.
*
* @param index
* -- The sub HAM bar to update.
* @param newHam
* -- The new value of the given sub HAM bar.
*/
protected synchronized void updateHamModifiers(int index, int newHam,
boolean bUpdateCurrentHam, boolean bFlyText) {
int iPreviousHam = iHamModifiers[index];
iHamModifiers[index] = newHam;
// System.out.println("Update current ham. Previous: " + iPreviousHam +
// ", current: " + iCurrentHam[index]);
if (iHamModifiers[index] != iPreviousHam) {
if (index % 3 == 2) {
iHamRegenerationKKMS[index - 2] = PacketUtils
.toKK(iMaxHam[index])
/ TIME_DIVIDER_ON_REGENERATION_RATE_MS; // Regenerate
// rate -- if
// Action,
// regenerate
// your Stamina
// in action
// every 100
// seconds.
}
// Deltas message.
// System.out.println("New currentHam["+index+"] = " +
// iCurrentHam[index]);
try {
client.insertPacket(PacketFactory.buildHAMDelta(this, (byte) 6,
(short) 0x0E, index, iHamModifiers[index]
+ iMaxHam[index], bFlyText),
Constants.PACKET_RANGE_CHAT_RANGE);
if (bUpdateCurrentHam) {
updateCurrentHam(index, iCurrentHam[index] + newHam);
}
} catch (Exception e) {
// D'oh!
DataLog.logEntry("Error building ham deltas message: "
+ e.toString(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Error building ham deltas message: " +
// e.toString());
e.printStackTrace();
}
}
}
/**
* Sets the ID of the Zone Server which this Player resides on.
*
* @param i
* -- The server ID.
*/
public void setServerID(int i) {
iServerID = i;
}
/**
* Gets the ID of the Zone Server which this Player resides on.
*
* @return The server ID.
*/
public int getServerID() {
return iServerID;
}
/**
* Sets the Object ID of the Guild this Player is a member of.
*
* @param l
* -- The Guild ID.
*/
public void setGuildID(long l) {
lGuildID = l;
}
/**
* Gets the Object ID of the Guild this Player is a member of.
*
* @return The Guild ID.
*/
public long getGuildID() {
return lGuildID;
}
/**
* Sets the Account ID this Player belongs to.
* @param l -- The Account ID.
*/
public void setAccountID(long l) {
lAccountID = l;
}
/**
* Gets the Account ID this Player belongs to.
*
* @return The Account ID
*/
public long getAccountID() {
return lAccountID;
}
private final static long lUpdateIntervalMS = 300000;
private long lDatabaseUpdateTimeMS = 0;
private transient Vector<POI> vPOIsThisPlanet;
private final static int DISTANCE_TO_TRIGGER_GRANT_POI = 20;
private long lHamUpdateTimerMS = 0; // TODO: This value must be fiddled /
// reset / ignored if we're in combat,
// as we need ham updates "instantly"
// when we're fighting.
private final static long MAX_TIME_MS_BETWEEN_HAM_UPDATE = 1000;
private final static long TIME_DIVIDER_ON_REGENERATION_RATE_MS = 100000;
private transient Vector<MapLocationData> vLastSeenCloneLocations = null;
protected Vector<MapLocationData> getLastSeenCloneLocations() {
return vLastSeenCloneLocations;
}
/**
* The main update loop for the Player.
*
* @param lDeltaTimeMS
* -- The elapsed time since the last update.
*/
public void update(long lDeltaTimeMS) {
// System.out.println("Player update -- elapsed time: " + lDeltaTimeMS);
if (bOnlineStatus) {
lTotalPlayerOnlineTime += lDeltaTimeMS;
}
if (vBuffEffects != null) {
for (int i = 0; i < vBuffEffects.length; i++) {
BuffEffect effect = vBuffEffects[i];
if (effect != null) {
effect.update(lDeltaTimeMS);
}
}
} else {
vBuffEffects = new BuffEffect[Constants.BUFF_EFFECTS.length];
lPoisonTimeMS = new long[iNumberOfHams];
lBleedTimeMS = new long[iNumberOfHams];
lDiseaseTimeMS = new long[iNumberOfHams];
lFireTimeMS = new long[iNumberOfHams];
lPoisonTickTimeMS = new long[iNumberOfHams];
lBleedTickTimeMS = new long[iNumberOfHams];
lDiseaseTickTimeMS = new long[iNumberOfHams];
lFireTickTimeMS = new long[iNumberOfHams];
iPoisonPotency = new int[iNumberOfHams];
iBleedPotency = new int[iNumberOfHams];
iDiseasePotency = new int[iNumberOfHams];
iFirePotency = new int[iNumberOfHams];
lStateTimer = new long[Constants.NUM_STATES];
vCommandQueue = new LinkedList<CommandQueueItem>();
}
if (iHamRegenerationKKMS == null) {
iHamRegenerationKKMS = new long[iMaxHam.length];
for (int i = 0; i < iMaxHam.length; i += 3) {
iHamRegenerationKKMS[i] = PacketUtils.toKK(iMaxHam[i + 2])
/ TIME_DIVIDER_ON_REGENERATION_RATE_MS; // Regenerate
// rate -- if
// Action,
// regenerate
// your Stamina
// in action
// every 100
// seconds.
}
}
if (bClearPerformedAnimation) {
sPerformedAnimation = null;
bClearPerformedAnimation = false;
}
if (thePlayer != null) {
thePlayer.update(lDeltaTimeMS);
}
if (lHealDelayMS > 0) {
lHealDelayMS -= lDeltaTimeMS;
if (lHealDelayMS <= 0) {
System.out.println("Able to heal again.");
try {
client.insertPacket(PacketFactory.buildChatSystemMessage(
"healing_response", "healing_response_58", 0l, "",
"", "", 0l, "", "", "", 0l, "", "", "", 0, 0f,
false));
} catch (Exception e) {
System.out
.println("Error inserting chat system message for healing response: "
+ e.toString());
e.printStackTrace();
}
}
}
if (lMaskScentDelayTime > 0) {
lMaskScentDelayTime -= lDeltaTimeMS;
}
// Note: For this code to work correctly with various other systems
// (riding vehicles, for example),
// their states must have the timers set to -1 when they are applied.
for (int i = 0; i < lStateTimer.length; i++) {
if (lStateTimer[i] > 0) {
lStateTimer[i] = Math.max(0, lStateTimer[i] - lDeltaTimeMS);
if (lStateTimer[i] == 0) {
if (i == Constants.STATE_BLEEDING) {
for (int j = 0; j < lBleedTimeMS.length; j++) {
lStateTimer[i] = Math.max(lStateTimer[i],
lBleedTimeMS[j]);
}
if (lStateTimer[i] == 0) {
removeState(i);
}
} else if (i == Constants.STATE_POISONED) {
for (int j = 0; j < lPoisonTimeMS.length; j++) {
lStateTimer[i] = Math.max(lStateTimer[i],
lPoisonTimeMS[j]);
}
if (lStateTimer[i] == 0) {
removeState(i);
}
} else if (i == Constants.STATE_DISEASED) {
for (int j = 0; j < lDiseaseTimeMS.length; j++) {
lStateTimer[i] = Math.max(lStateTimer[i],
lDiseaseTimeMS[j]);
}
if (lStateTimer[i] == 0) {
removeState(i);
}
} else if (i == Constants.STATE_BURNING) {
for (int j = 0; j < lFireTimeMS.length; j++) {
lStateTimer[i] = Math.max(lStateTimer[i],
lFireTimeMS[j]);
}
if (lStateTimer[i] == 0) {
removeState(i);
}
} else {
if (i == Constants.STATE_SCENT_MASKED) {
try {
client.insertPacket(PacketFactory
.buildChatSystemMessage("skl_use",
"sys_scentmask_stop"));
} catch (IOException e) {
// D'oh!
}
}
removeState(i);
}
}
}
}
// TODO: Put all of this into updateHam(lDeltaTimeMS);
updateCommandQueueEnqueues(lDeltaTimeMS);
updatePoisons(lDeltaTimeMS);
updateDiseases(lDeltaTimeMS);
updateBleeds(lDeltaTimeMS);
updateFires(lDeltaTimeMS);
lHamUpdateTimerMS += lDeltaTimeMS;
if (lHamUpdateTimerMS >= MAX_TIME_MS_BETWEEN_HAM_UPDATE) {
for (int i = 0; i < iCurrentHam.length; i++) {
if (iHamMigrationTarget[i] != iMaxHam[i]) {
if (lHamMigrationRateKKMS[i] == 0) {
lHamMigrationRateKKMS[i] = SWGGui.getRandomLong(
HAM_MIGRATION_TIME_MINIMUM_KK_MS,
HAM_MIGRATION_TIME_MAXIMUM_KK_MS);
} else {
boolean direction = (iHamMigrationTarget[i] > iMaxHam[i]);
long lGainedHamKK = lHamMigrationRateKKMS[i]
* lHamUpdateTimerMS;
lMaxHamKK[i] += lGainedHamKK;
iMaxHam[i] = (int) (PacketUtils.unKK(lMaxHamKK[i]));
if (direction) {
if (iMaxHam[i] >= iHamMigrationTarget[i]) {
iMaxHam[i] = iHamMigrationTarget[i];
}
} else {
if (iMaxHam[i] < iHamMigrationTarget[i]) {
iMaxHam[i] = iHamMigrationTarget[i];
}
}
}
}
if (iCurrentHam[i] < ((iMaxHam[i] + iHamModifiers[i]) - iHamWounds[i])) {
long lHamUpdateKK = (iHamRegenerationKKMS[i] * lHamUpdateTimerMS);
long lHamUpdateValue = PacketUtils.unKK(lHamUpdateKK);
// System.out.println("Player stance: " + iStance);
if (iStance == Constants.STANCE_SITTING) {
lHamUpdateValue = (lHamUpdateValue * 14) / 10;
} else if ((lState & Constants.STATE_COMBAT) != 0) {
lHamUpdateValue = (lHamUpdateValue * 4) / 10;
}
// System.out.println("Add " + lHamUpdateValue +
// " to index " + i);
updateCurrentHam(i, (int) lHamUpdateValue);
}
}
lHamUpdateTimerMS = 0;
}
if (lIncapacitationRemainingTimeMS > 0) {
lIncapacitationRemainingTimeMS -= lDeltaTimeMS;
updateIncapacitationTimer(lIncapacitationRemainingTimeMS);
if (lIncapacitationRemainingTimeMS <= 0) {
setStance(null, Constants.STANCE_STANDING, true);
}
}
// From there to here.
lDatabaseUpdateTimeMS -= lDeltaTimeMS;
if (lDatabaseUpdateTimeMS < 0) {
lDatabaseUpdateTimeMS = lUpdateIntervalMS;
server.getGUI().getDB().updatePlayer(this, false, false);
}
try {
// this updates the players position and checks to see if the player
// has a poi badge or not
// if the player does not have it and is within the range og the poi
// we give the player the badge.
// Ack! We're getting the POI list EVERY SINGLE LOOP?
vPOIsThisPlanet = DatabaseInterface.getPOIListForPlanetID(this
.getPlanetID());
if (!vPOIsThisPlanet.isEmpty()) {
for (int i = 0; i < vPOIsThisPlanet.size(); i++) {
POI T = vPOIsThisPlanet.get(i);
if (!thePlayer.hasBadge(T.getBadgeID())
&& client.getClientReadyStatus()) {
// We're declaring a new SOEObject multiple times each
// time through this loop?
float x2 = T.getX();
float y2 = T.getY();
float x1 = getX();
float y1 = getY();
float deltaXSqr = (x2 - x1) * (x2 - x1);
float deltaYSqr = (y2 - y1) * (y2 - y1);
float distance = (float) Math.sqrt(deltaXSqr
+ deltaYSqr); // TODO: Replace with square root
// lookup table.
if (distance <= DISTANCE_TO_TRIGGER_GRANT_POI) {
// System.out.println("Badge " + T.getBadgeID() +
// " value is: " +
// getPlayData().hasBadge(T.getBadgeID()));
thePlayer.addBadge(T.getBadgeID());
client.insertPacket(PacketFactory
.buildBadgeResponseMessage(this.getID(),
this.getPlayData().getBadges()));
client.insertPacket(PacketFactory
.buildPlaySoundFileMessage(0,
"sound/music_acq_miner.snd", 1,
(byte) 0));
// "You have gained a new badge! (%TO)
client.insertPacket(PacketFactory
.buildChatSystemMessage("badge_n",
"prose_grant", 0, "", "", "", 0,
"", "", "", 0, "badge_n",
Constants.BADGE_STF_STRINGS[T
.getBadgeID()], "", 0, 0f,
false));
// client.insertPacket(PacketFactory.buildFlyTextSTFMessage(this,
// "badge_n",
// Constants.BADGE_STF_STRINGS[T.getBadgeID()], "",
// "",0));
client.insertPacket(PacketFactory
.buildChatSystemMessage("badge_n",
Constants.BADGE_STF_STRINGS[T
.getBadgeID()], 0, null,
null, null, 0, null, null, null, 0,
null, null, null, 0, 0f, true));
// this.getClient().insertPacket(PacketFactory.buildPlayClientEffectObjectMessage(this,
// "@sound:music_acq_miner.snd"));
/**
* @todo - Send a music animation of mus_acq_miner
* when a badge is acquired.
*/
}
}
// System.out.println("Badge " + T.getBadgeID() +
// " value is: " + getPlayData().hasBadge(T.getBadgeID()));
}
}
if (bBurstRunning) {
lBurstRunexpiryTimer -= lDeltaTimeMS;
if (lBurstRunexpiryTimer <= 0) {
playerUnBurstRun();
}
}
if (lBurstRunRechargeTimer > 0) {
lBurstRunRechargeTimer = Math.max(0, lBurstRunRechargeTimer
- lDeltaTimeMS);
}
// update players intangibles.
Vector<IntangibleObject> vI = tDatapad.getIntangibleObjects();
for (int i = 0; i < vI.size(); i++) {
IntangibleObject iUpd = vI.get(i);
iUpd.update(lDeltaTimeMS);
}
for (int i = 0; i < vInventoryItemsList.size(); i++) {
if (vInventoryItemsList.elementAt(i) != null) {
vInventoryItemsList.elementAt(i).update(lDeltaTimeMS,
server, client, this);
}
}
/**
* TEMPORARY USE FOR DEV USE ONLY
*/
if (bHeightMapCollect) {
lNextHeightMapUpdate -= lDeltaTimeMS;
if (lNextHeightMapUpdate <= 0 && getZ() != -1000) {
heightMapNewCoord();
lNextHeightMapUpdate += (1000 * 2);
}
}
/**
* This allows us to queue stuff to be spawned to the player at a
* later time even while logging in.
*/
if (this.getDelayListCount() >= 1
&& this.getClient().getClientReadyStatus()) {
for (int i = 0; i < lNextDelayedSpawn.size(); i++) {
// had to do this cause 1 its not going to be done often
// 2 it was the only way to look at the value and not update
// it inside the vector.
if (lNextDelayedSpawn.get(i) <= System.currentTimeMillis()) {
// do this
lNextDelayedSpawn.removeElementAt(i);
SOEObject o = this.vDelayedSpawnObjects.get(i);
if (o != null) {
vDelayedSpawnObjects.removeElementAt(i);
switch (o.getDelayedSpawnAction()) {
case (byte) 0x01:// spawn
{
// System.out.println("Delayed Spawn Action: Object ID: "
// + o.getID() + " IFF:" + o.getIFFFileName() +
// " Cell ID:" + o.getCellID());
server.addObjectToAllObjects(o, true, false);
this.spawnItem(o);
break;
}
case (byte) 0x02:// despawn
{
// System.out.println("Delayed DeSpawn Action: Object ID: "
// + o.getID() + " IFF:" + o.getIFFFileName() +
// " Cell ID:" + o.getCellID());
this.despawnItem(o);
server.removeObjectFromAllObjects(o, true);
break;
}
case (byte) 0x03:// cycle
{
// server.removeObjectFromAllObjects(o, true);
// // This removes it from the list of all
// objects!
this.despawnItem(o);
o
.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
this.addDelayedSpawnObject(o, System
.currentTimeMillis() + 500);
break;
}
case (byte) 0x04: // DELAYED_SPAWN_ACTION_RAW_SPAWN
{
server.addObjectToAllObjects(o, true, false);
if (o != null) {
this.spawnItem(o);
}
}
}
}
}
}
}
if (bPlayerRequestedLogout
&& this.getStance() == Constants.STANCE_SITTING) {
if (this.lLogoutSpamTimer <= 0) {
client.insertPacket(PacketFactory.buildChatSystemMessage(
"logout", "time_left", 0l, "", "", "", 0l, "", "",
"", 0l, "", "", "", (int) (lLogoutTimer / 1000),
0f, false));
lLogoutSpamTimer = 1100 * 5;
} else {
// System.out.println("Logout in progress");
lLogoutSpamTimer -= lDeltaTimeMS;
if (lLogoutSpamTimer < 0) {
lLogoutSpamTimer = 0;
}
}
// --------------------------------------
if (lLogoutTimer <= 0) {
// System.out.println("Logging out Player " +
// this.getFullName());
bPlayerRequestedLogout = false;
if (this.myGroup != null) {
myGroup.removeMemberFromGroup(this,
Constants.GROUP_REMOVE_REASON_LEAVE);
}
server.removeObjectFromAllObjects(this.getID());
SOEObject m = server.getObjectFromAllObjects(this
.getCurrentMount());
if (m != null) {
server.removeFromTree(m);
}
server.removeFromTree(this);
Vector<PlayerFriends> vPlayerFriends = thePlayer
.getFriendsList();
for (int i = 0; i < vPlayerFriends.size(); i++) {
Player friend = server.getPlayer(vPlayerFriends
.elementAt(i).getName());
ZoneClient friendClient = friend.getClient();
if (friendClient != null) {
friendClient.insertPacket(PacketFactory
.buildFriendOfflineStatusUpdate(friend,
this));
}
}
server.forwardFriendChangedStatus(this, false);
client.insertPacket(PacketFactory.buildLogoutClient()); // This
// packet
// causes
// the
// SWG
// client
// to
// send
// a
// Disconnect
// packet.
return;
} else {
lLogoutTimer -= lDeltaTimeMS;
if (lLogoutTimer < 0) {
lLogoutTimer = 0;
}
}
} else if (bPlayerRequestedLogout
&& this.getStance() != Constants.STANCE_SITTING) {
bPlayerRequestedLogout = false;
this.getClient().insertPacket(
PacketFactory.buildChatSystemMessage("logout",
"aborted", 0l, "", "", "", 0l, "", "", "", 0l,
"", "", "", 0, 0f, false));
}
// System.out.println("Delta time" + lDeltaTimeMS);
if (this.currentTradeObject != null) {
currentTradeObject.update(lDeltaTimeMS);
}
if (this.myGroup != null && myGroup.getUpdateObject().equals(this)) {
myGroup.update(lDeltaTimeMS);
} else if (this.myGroup != null
&& !myGroup.getUpdateObject().equals(this)
&& !myGroup.getUpdateObject().getOnlineStatus()) {
// System.out.println("Alternate Player is updating the Group Object: "
// + this.getFullName());
myGroup.update(lDeltaTimeMS);
}
if (heartbeatTimer < 0) {
heartbeatTimer = 1000 * 60 * 5;
getClient().insertPacket(PacketFactory.buildHeartbeat());
} else {
heartbeatTimer -= lDeltaTimeMS;
if (heartbeatTimer < 0) {
heartbeatTimer = 0;
}
}
if (this.getTutorial() != null) {
this.getTutorial().update(lDeltaTimeMS);
}
if (currentCampObject != null) {
currentCampObject.update(lDeltaTimeMS, server);
}
if (this.isForaging) {
this.forageCooldown -= lDeltaTimeMS;
if (this.forageCooldown <= 0) {
this.forage();
}
}
if (playerBeingListened != null) {
if (!ZoneServer.isInRange(this, playerBeingListened, 10)) {
playerBeingListened.removePlayerListening(this);
client.insertPacket(PacketFactory.buildChatSystemMessage(
"performance", "music_listen_out_of_range",
playerBeingListened.getID(), playerBeingListened
.getSTFFileName(), playerBeingListened
.getSTFFileIdentifier(),
playerBeingListened.getFullName(), 0, null, null,
null, 0, null, null, null, 0, 0.0f, false));
playerBeingListened = null;
}
if (!playerBeingListened.isPlayingMusic()) {
client.insertPacket(PacketFactory.buildChatSystemMessage(
"performance", "music_stop_other",
playerBeingListened.getID(), playerBeingListened
.getSTFFileName(), playerBeingListened
.getSTFFileIdentifier(),
playerBeingListened.getFullName(), 0, null, null,
null, 0, null, null, null, 0, 0.0f, false));
}
}
if (playerBeingWatched != null) {
if (ZoneServer.isInRange(this, playerBeingWatched, 10)) {
if (lRandomWatchPlayerTick <= 0) {
lRandomWatchPlayerTick = Math.max(5000, SWGGui
.getRandomLong(5000, 30000));
this.setPerformanceString("entertained");
this.setStance(null, Constants.STANCE_ANIMATING_SKILL,
false);
/*
* int r = SWGGui.getRandomInt(1,10); String anim =
* "applaud"; switch(r) { case 3: { anim = "airguitar";
* break; } case 7: { anim = "clap"; break; } case 9: {
* anim = "kiss"; break; } }
*
* Vector<Player> vPL =
* server.getPlayersAroundObject(this, true); for(int i
* = 0; i < vPL.size(); i++) { Player p = vPL.get(i);
* p.getClient
* ().insertPacket(PacketFactory.buildPlayerAnimation
* (this, anim)); }
*/
} else {
lRandomWatchPlayerTick -= lDeltaTimeMS;
}
} else {
playerBeingWatched.removePlayerWatching(this);
client.insertPacket(PacketFactory.buildChatSystemMessage(
"performance", "dance_watch_out_of_range",
playerBeingWatched.getID(), playerBeingWatched
.getSTFFileName(), playerBeingWatched
.getSTFFileIdentifier(), playerBeingWatched
.getFullName(), 0, null, null, null, 0,
null, null, null, 0, 0.0f, false));
playerBeingWatched = null;
}
if (playerBeingWatched != null
&& !playerBeingWatched.isDancing()) {
client.insertPacket(PacketFactory.buildChatSystemMessage(
"performance", "dance_stop_other",
playerBeingWatched.getID(), playerBeingWatched
.getSTFFileName(), playerBeingWatched
.getSTFFileIdentifier(), playerBeingWatched
.getFullName(), 0, null, null, null, 0,
null, null, null, 0, 0.0f, false));
playerBeingWatched = null;
}
}
if (this.isPlayingMusic()) {
if (lMusicTick <= 0) {
lMusicTick = 9000;
Structure s = null;
if (this.getCellID() != 0) {
Cell c = (Cell) server.getObjectFromAllObjects(this
.getCellID());
if (c != null) {
s = (Structure) c.getBuilding();
}
}
int iXPModifier = 0;
int iSkillModifier = 0;
int iHealingWoundMod = 0;
if (this.hasSkill(11)) {
iXPModifier += 5;
iHealingWoundMod += 5;
iSkillModifier++;
}
if (this.hasSkill(12)) {
iXPModifier += 10;
iHealingWoundMod += 10;
iSkillModifier++;
}
if (this.hasSkill(17)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(18)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(19)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(20)) {
iXPModifier += 10;
iSkillModifier++;
}
if (this.hasSkill(25)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(26)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(27)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(28)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(281)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(287)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(288)) {
iHealingWoundMod += 10;
}
if (this.hasSkill(289)) {
iHealingWoundMod += 10;
}
if (this.hasSkill(290)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(282)) {
iHealingWoundMod += 15;
}
int iListenBonus = 0;
int iHealedWoundAmount = 0;
if (vPlayersListening != null) {
iListenBonus = vPlayersListening.size();
for (int h = 0; h < vPlayersListening.size(); h++) {
Player w = vPlayersListening.get(h);
int[] iWounds = w.getHamWounds();
// 6,7,8
for (int e = 6; e < iWounds.length; e++) {
if (iWounds[e] >= 1) {
if (this.isInCamp()
|| s != null
&& s.getIFFFileName().contains(
"cantina")) {
if (iWounds[e] != 0) {
w.updateHAMWounds(e,
-iHealingWoundMod, true);
}
iHealedWoundAmount += iHealingWoundMod;
}
}
}
}
}
if (this.getGroupID() != 0) {
Group g = (Group) server.getObjectFromAllObjects(this
.getGroupID());
int iGroupModifier = 0;
Vector<SOEObject> vGM = g.getGroupMembers();
for (int i = 0; i < vGM.size(); i++) {
SOEObject o = vGM.get(i);
if (o instanceof Player && !o.equals(this)) {
Player p = (Player) o;
if (p.hasSkill(11)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(12)) {
iXPModifier += 10;
iSkillModifier++;
}
if (p.hasSkill(21)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(22)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(23)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(24)) {
iXPModifier += 10;
iSkillModifier++;
}
iGroupModifier++;
}
}
iXPModifier /= iGroupModifier;
iSkillModifier /= iGroupModifier;
this.updateExperience(null, DatabaseInterface
.getExperienceIDFromName("music"),
((iXPModifier * iSkillModifier)
+ iFlourishBonus + iListenBonus));
iFlourishBonus = 0;
} else {
this.updateExperience(null, DatabaseInterface
.getExperienceIDFromName("music"),
((iXPModifier * iSkillModifier)
+ iFlourishBonus + iListenBonus));
iFlourishBonus = 0;
}
if (iListenBonus >= 1) {
if (iHealedWoundAmount >= 1) {
this
.updateExperience(
null,
DatabaseInterface
.getExperienceIDFromName("entertainer_healing"),
((iHealedWoundAmount * iSkillModifier) + iListenBonus));
}
}
} else {
lMusicTick -= lDeltaTimeMS;
}
}
if (this.isDancing()) {
if (lDancetick <= 0) {
lDancetick = 9000;
Structure s = null;
if (this.getCellID() != 0) {
Cell c = (Cell) server.getObjectFromAllObjects(this
.getCellID());
if (c != null) {
s = c.getBuilding();
}
}
int iXPModifier = 0;
int iSkillModifier = 0;
int iHealingWoundMod = 0;
if (this.hasSkill(11)) {
iXPModifier += 5;
iHealingWoundMod += 5;
iSkillModifier++;
}
if (this.hasSkill(12)) {
iXPModifier += 10;
iHealingWoundMod += 10;
iSkillModifier++;
}
if (this.hasSkill(21)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(22)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(23)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(24)) {
iXPModifier += 10;
iSkillModifier++;
}
if (this.hasSkill(25)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(26)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(27)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(28)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(262)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(263)) {
iHealingWoundMod += 15;
}
if (this.hasSkill(268)) {
iHealingWoundMod += 5;
}
if (this.hasSkill(269)) {
iHealingWoundMod += 10;
}
if (this.hasSkill(270)) {
iHealingWoundMod += 10;
}
if (this.hasSkill(271)) {
iHealingWoundMod += 15;
}
int iWatchBonus = 0;
int iHealedWoundAmount = 0;
if (vPlayersWatching != null) {
iWatchBonus = vPlayersWatching.size();
for (int h = 0; h < vPlayersWatching.size(); h++) {
Player w = vPlayersWatching.get(h);
int[] iWounds = w.getHamWounds();
// 6,7,8
for (int e = 6; e < iWounds.length; e++) {
if (iWounds[e] >= 1) {
if (this.isInCamp()
|| s != null
&& s.getIFFFileName().contains(
"cantina")) {
if (iWounds[e] != 0) {
w.updateHAMWounds(e,
-iHealingWoundMod, true);
}
iHealedWoundAmount += iHealingWoundMod;
}
}
}
}
}
if (this.getGroupID() != 0) {
Group g = (Group) server.getObjectFromAllObjects(this
.getGroupID());
int iGroupModifier = 0;
Vector<SOEObject> vGM = g.getGroupMembers();
for (int i = 0; i < vGM.size(); i++) {
SOEObject o = vGM.get(i);
if (o instanceof Player && !o.equals(this)) {
Player p = (Player) o;
if (p.hasSkill(11)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(12)) {
iXPModifier += 10;
iSkillModifier++;
}
if (p.hasSkill(21)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(22)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(23)) {
iXPModifier += 5;
iSkillModifier++;
}
if (p.hasSkill(24)) {
iXPModifier += 10;
iSkillModifier++;
}
iGroupModifier++;
}
}
iXPModifier /= iGroupModifier;
iSkillModifier /= iGroupModifier;
this.updateExperience(null, DatabaseInterface
.getExperienceIDFromName("dance"),
((iXPModifier * iSkillModifier)
+ iFlourishBonus + iWatchBonus));
iFlourishBonus = 0;
} else {
this.updateExperience(null, DatabaseInterface
.getExperienceIDFromName("dance"),
((iXPModifier * iSkillModifier)
+ iFlourishBonus + iWatchBonus));
iFlourishBonus = 0;
}
if (iWatchBonus >= 1) {
if (iHealedWoundAmount >= 1) {
this
.updateExperience(
null,
DatabaseInterface
.getExperienceIDFromName("entertainer_healing"),
((iHealedWoundAmount * iSkillModifier) + iWatchBonus));
}
}
} else {
lDancetick -= lDeltaTimeMS;
}
}
lFlourishTick -= lDeltaTimeMS;
lEffectTick -= lDeltaTimeMS;
if (iStance == Constants.STANCE_DEAD) {
if (bSeenCloneWindow == false) {
SUIWindow cloneWindow = new SUIWindow(this);
cloneWindow
.setWindowType(Constants.SUI_SELECT_LOCATION_TO_CLONE);
cloneWindow.setOriginatingObject(this);
String WindowTypeString = "handlePlayerRevive";
String DataListTitle = "@base_player:revive_title";
String DataListPrompt = "@base_player:clone_prompt_header";
Vector<String> vCloneNames = new Vector<String>();
Vector<MapLocationData> vCloneData = new Vector<MapLocationData>();
// TODO: Now, check to see if the Player has a specific
// Player City cloning center they are bound to, on this
// planet. For that, players must be able to bind to a
// specific player city cloner.
MapLocationData playerCloneBindLocation = thePlayer
.getCloneBindLocation();
// If it's on this planet, let him go there.
if (playerCloneBindLocation != null) {
vCloneNames.add(playerCloneBindLocation.getName());
vCloneData.add(playerCloneBindLocation);
}
// Now, go through all static cloners and check them as
// well.
Vector<MapLocationData> vStaticLocationsThisPlanet = server
.getStaticMapLocations(Constants.PlanetNames[getPlanetID()]);
for (int i = 0; i < vStaticLocationsThisPlanet.size(); i++) {
MapLocationData staticPoint = vStaticLocationsThisPlanet
.elementAt(i);
if (staticPoint.getObjectType() == Constants.MAP_LOCATION_ID.CLONING_FACILITY
.ordinal()
|| staticPoint.getObjectSubType() == Constants.MAP_LOCATION_ID.CLONING_FACILITY
.ordinal()) {
vCloneNames.add(staticPoint.getName());
vCloneData.add(staticPoint);
}
}
System.out.println("Found " + vCloneNames.size()
+ " cloning centers on "
+ Constants.PlanetNames[getPlanetID()]);
String[] vCloneNameArr = new String[vCloneNames.size()];
vCloneNames.toArray(vCloneNameArr); // (String[])vCloneNames.toArray();
client.insertPacket(cloneWindow.SUIScriptListBox(client,
WindowTypeString, DataListTitle, DataListPrompt,
vCloneNameArr, null, 0, getID()));
vLastSeenCloneLocations = vCloneData;
bSeenCloneWindow = true;
// Constants.MAP_LOCATION_ID.CLONING_FACILITY;
/*
* String sList[] = new String[3]; sList[0] =
* "@player_structure:owner_prompt " +
* this.getCampOwner().getFullName(); //owner sList[1] =
* "Time Left: " + (this.lTimeToLive / 1000 / 60) + " Mins";
* sList[2] = "Visitors: " + this.vCampVisitors.size();
* client.insertPacket(w.SUIScriptListBox(client,
* WindowTypeString, DataListTitle, DataListPrompt, sList,
* null, 0, 0));
* client.getPlayer().addPendingSUIWindow(w.copyWindow());
*/
}
}
} catch (Exception e) {
DataLog.logEntry("Exception caught while checking POI Badges "
+ e.toString(), "Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exception caught while checking POI Badges "
// + e);
e.printStackTrace();
}
}
protected boolean addFlourishBonus(int iBonus) {
try {
if (lFlourishTick <= 0) {
lFlourishTick = 1000;
iFlourishBonus += iBonus;
int iXPModifier = 0;
int iSkillModifier = 0;
if (this.hasSkill(11)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(12)) {
iXPModifier += 10;
iSkillModifier++;
}
if (this.hasSkill(21)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(22)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(23)) {
iXPModifier += 5;
iSkillModifier++;
}
if (this.hasSkill(24)) {
iXPModifier += 10;
iSkillModifier++;
}
this.updateCurrentHam(Constants.HAM_INDEX_ACTION, (Math.min(-20, (-75 + iXPModifier))));
this.getClient().insertPacket(
PacketFactory.buildChatSystemMessage("performance",
"flourish_perform", this.getID(), this
.getSTFFileName(), this
.getSTFFileIdentifier(), this
.getFullName(), 0, null, null, null, 0,
null, null, null, 0, 0.0f, false));
return true;
} else {
this.getClient().insertPacket(
PacketFactory.buildChatSystemMessage("performance",
"flourish_wait_self", this.getID(), this
.getSTFFileName(), this
.getSTFFileIdentifier(), this
.getFullName(), 0, null, null, null, 0,
null, null, null, 0, 0.0f, false));
}
return false;
} catch (Exception e) {
DataLog.logException("Exception while granting flourish bonus",
"Player", ZoneServer.ZoneRunOptions.bLogToConsole, true, e);
}
return false;
}
public boolean isBHeightMapCollect() {
return bHeightMapCollect;
}
public void setBHeightMapCollect(boolean bHeightMapCollect) {
this.bHeightMapCollect = bHeightMapCollect;
}
public long getLNextHeightMapUpdate() {
return lNextHeightMapUpdate;
}
public void setLNextHeightMapUpdate(long lNextHeightMapUpdate) {
this.lNextHeightMapUpdate = lNextHeightMapUpdate;
}
float currentX = 0;
public short tempx, tempy, tempplanetid, tempnobuildings;
public transient short[][][] myHeightMap;
public transient boolean bHeightMapActive = false;
private void heightMapNewCoord() {
try {
bHeightMapCollect = false;
short tempz = (short) getZ();
if (tempx <= 254 && tempy <= 254
&& myHeightMap[tempplanetid][tempx][tempy] == 32767) {
this.getClient().insertPacket(
PacketFactory.buildChatSystemMessage("Z For X:"
+ (float) (7680 - (tempx * 60.472441)) + " Y: "
+ (float) (7680 - (tempy * 60.472441))
+ " Set at: " + (short) getZ()));
System.out.println(this.getFullName() + " has set Z For X:"
+ (float) (7680 - (tempx * 60.472441)) + " Y: "
+ (float) (7680 - (tempy * 60.472441)) + " Set at: "
+ (short) getZ());
myHeightMap[tempplanetid][tempx][tempy] = tempz;
server.updateHeightMapZ(tempx, tempy, tempz, tempplanetid);
tempy++;
if (tempy == 255) {
tempy = 0;
if (tempy == 255) {
tempy = 0;
if (tempx < 255) {
tempx++;
if (tempx == 255) {
tempx = 0;
tempplanetid++;
if (tempplanetid == 10) {
bHeightMapCollect = false;
return;
}
}
}
}
}
}
if (myHeightMap[tempplanetid][tempx][tempy] != 32767
&& tempy != 255) {
System.out.println("Moving Coords forward they were not 32767");
while (myHeightMap[tempplanetid][tempx][tempy] != 32767
&& tempy != 255) {
tempy++;
if (tempy == 255) {
tempy = 0;
if (tempx < 255) {
tempx++;
if (tempx == 255) {
tempx = 0;
tempplanetid++;
if (tempplanetid == 10) {
bHeightMapCollect = false;
return;
}
}
}
}
}
}
if (myHeightMap[tempplanetid][tempx][tempy] == 32767) {
this.playerWarp((float) (7680 - (tempx * 60.472441)),
(float) (7680 - (tempy * 60.472441)), (float) -1000f,
getCellID(), tempplanetid);
}
bHeightMapCollect = true;
} catch (Exception e) {
System.out.println("Height Map Tool Exception Caught " + e);
e.printStackTrace();
}
}
/**
* Initializes the countdown timer for when this character will next be
* updated in the Database.
*/
protected void initializeStartupTime() {
lDatabaseUpdateTimeMS = lUpdateIntervalMS;
}
/**
* This function adds a Command to the Command Queue.
*
* @param commandCRC
* -- The CRC of the command.
* @param timer
* -- The period of time this command causes any following
* commands to be delayed by.
* @param unknown1
* -- An unknown variable.
* @param unknown2
* -- An unknown variable.
*/
protected void queueCommand(CommandQueueItem queueItem) {
// vCommandQueue.add(new CommandQueueItem(commandCRC, timer, unknown1,
// unknown2, server.getRequiredCommandSkill(commandCRC), this));
vCommandQueue.add(queueItem);
}
/**
* Sets if the Player knows a given skill.
*
* @param skillID
* -- The ID of the Skill we are modifying.
* @param bGainingSkill
* -- If the Player knows the skill or not.
*/
protected void setSkill(int skillID, boolean bGainingSkill,
boolean bUpdateZone) {
if (!bIsJedi) {
thePlayer.setSkill(skillID, bGainingSkill, bUpdateZone); // How can
// this
// possibly
// be a
// null
// pointer?
} else {
// Skill must be a Force Sensitive skill, Language, or Pilot skill
// to learn. No other skills are learnable.
// ******* IMPORTANT *******
// This code is for Hologrind.
// TODO: Update for compatibility with the Village system.
if ((skillID >= 641 && skillID <= 989) || skillID >= 1010) {
thePlayer.setSkill(skillID, bGainingSkill, bUpdateZone);
} else {
if (bUpdateZone) {
try {
client
.insertPacket(PacketFactory
.buildChatSystemMessage("As a Jedi, you are not allowed to learn this skill."));
} catch (Exception e) {
// D'oh!
}
}
}
}
}
/**
* Checks to see if the Player knows a given skill.
*
* @param skillID
* -- The Skill ID
* @return If the player knows the skill.
*/
protected boolean hasSkill(int skillID) {
return thePlayer.hasSkill(skillID);
}
/**
* Initializes this Player's position at server start-up.
*
* @param moveCounter
* -- The number of movements the Player has made. (Should always
* be 0 for this function.)
* @param newN
* -- The Player's North orientation.
* @param newS
* -- The Player's South Orientation.
* @param newE
* -- The Player's X-axis rotation.
* @param newW
* -- The Player's Y-axis rotation.
* @param newX
* -- The Player's X position.
* @param newZ
* -- The Player's Z position.
* @param newY
* -- The Player's Y position.
* @param fVelocity
* -- The Player's velocity.
*/
protected void initializePosition(int moveCounter, float newN, float newS,
float newE, float newW, float newX, float newZ, float newY,
float fVelocity, long cellID) {
setCellID(cellID);
setX(newX);
setY(newY);
setZ(newZ);
setOrientationN(newN);
setOrientationE(newE);
setOrientationS(newS);
setOrientationW(newW);
setVelocity(fVelocity);
Vector<IntangibleObject> vDatapadItems = tDatapad.getIntangibleObjects();
for (int i = 0; i < vDatapadItems.size(); i++) {
IntangibleObject o = vDatapadItems.elementAt(i);
NPC theCalledObject = o.getAssociatedCreature();
if (theCalledObject != null) {
o.setRadialCondition(Constants.RADIAL_CONDITION.INTANGIBLE_VEHICLE_SPAWNED.ordinal());
} else {
o.setRadialCondition(Constants.RADIAL_CONDITION.NORMAL.ordinal());
}
}
for (int i = 0; i < vInventoryItemsList.size(); i++) {
TangibleItem inventoryItem = vInventoryItemsList.elementAt(i);
inventoryItem.setRadialCondition(Constants.RADIAL_CONDITION.NORMAL.ordinal());
}
}
private float discardedX = 0;
private float discardedY = 0;
private float discardedZ = 0;
// private int iMovementCounter = 0;
// private int getMovementCounter() {
// return iMovementCounter;
// }
/**
* This function updates the positon of the Player in the world, and sends
* the update packets to all other Players in range of this Player.
*
* @param moveCounter
* -- The number of times the Player's position has been updated.
* @param newN
* -- The Player's North orientation
* @param newS
* -- The Player's South orientation
* @param newE
* -- The Player's X axis rotation.
* @param newW
* -- The Player's Y axis rotation.
* @param newX
* -- The Player's X coordinate.
* @param newZ
* -- The Player's Z coordinate.
* @param newY
* -- The Player's Y coordinate.
* @param fVelocity
* -- The Player's Velocity
* @throws IOException
* -- If an error occured building the movement update packets.
*/
protected void updatePosition(int moveCounter, float newN, float newS,
float newE, float newW, float newX, float newZ, float newY,
float fVelocity, long cellID) throws IOException {
float dX;
float dY;
float dZ;
dX = Math.abs(newX - discardedX);
dY = Math.abs(newY - discardedY);
dZ = Math.abs(newZ - discardedZ);
// iMovementCounter = moveCounter;
double displacement = Math.sqrt((dX * dX) + (dY * dY) + (dZ * dZ));
discardedX = newX;
discardedY = newY;
discardedZ = newZ;
if (this.getCellID() != 0 || displacement > 50.0) {
if (getCellID() != 0) {
Cell c = (Cell) server.getObjectFromAllObjects(this.getCellID());
Structure s = c.getBuilding();
s.despawnObjectsInBuildingCells(client);
c.removeCellObject(this);
}
this.setCellID(0);
// Get every object on the Player, set them to an appropriate value.
Vector<IntangibleObject> vDatapadItems = tDatapad.getIntangibleObjects();
for (int i = 0; i < vDatapadItems.size(); i++) {
IntangibleObject o = vDatapadItems.elementAt(i);
NPC theCalledObject = o.getAssociatedCreature();
if (theCalledObject != null) {
o.setRadialCondition(Constants.RADIAL_CONDITION.INTANGIBLE_VEHICLE_SPAWNED.ordinal());
} else {
o.setRadialCondition(Constants.RADIAL_CONDITION.NORMAL.ordinal());
}
}
for (int i = 0; i < vInventoryItemsList.size(); i++) {
TangibleItem inventoryItem = vInventoryItemsList.elementAt(i);
inventoryItem.setRadialCondition(Constants.RADIAL_CONDITION.NORMAL.ordinal());
}
return;
}
if (getX() == newX && getY() == newY && getZ() == newZ) {
return;
}
float MovAngle = 0;
if (((newN * newN) + (newS * newS) + (newE * newE)) > 0.0) {
if (newW > 0.0 && newE < 0.0) {
newW *= -1;
}
MovAngle = (float) (2.0 * Math.acos(newW));
} else {
MovAngle = 0.0f;
}
// These 3 vectors need to be reworked. They are already taken care of
// by the positional grid.
Vector<SOEObject> vObjectsBeforeMovement = server
.getWorldObjectsAroundObject(this);
setCellID(cellID);
setZ(newZ);
setOrientationN(newN);
setOrientationE(newE);
setOrientationS(newS);
setOrientationW(newW);
setVelocity(fVelocity);
setMovementAngle(MovAngle);
if (bIsMounted) {
Vehicle mountObject = (Vehicle) server
.getObjectFromAllObjects(lCurrentMount);
if (mountObject.getTemplateID() == 6213) {
mountObject.setZ(newZ + Constants.JETPACK_Z_AXIS_MODIFIER);
setZ(newZ + Constants.JETPACK_Z_AXIS_MODIFIER);
} else {
mountObject.setZ(newZ);
setZ(newZ);
}
mountObject.setOrientationE(newE);
mountObject.setOrientationN(newN);
mountObject.setOrientationS(newS);
mountObject.setOrientationW(newW);
mountObject.setVelocity(fVelocity);
mountObject.setMovementAngle(MovAngle);
server.moveObjectInTree(mountObject, newX, newY, mountObject
.getPlanetID(), mountObject.getPlanetID());
server.moveObjectInTree(this, newX, newY, getPlanetID(),
getPlanetID());
getClient().insertPacket(
PacketFactory.buildUpdateTransformMessage(mountObject),
Constants.PACKET_RANGE_CHAT_RANGE);
getClient().insertPacket(
PacketFactory.buildUpdateTransformMessage(this),
Constants.PACKET_RANGE_CHAT_RANGE);
} else {
server.moveObjectInTree(this, newX, newY, getPlanetID(),
getPlanetID());
getClient().insertPacket(
PacketFactory.buildUpdateTransformMessage(this),
Constants.PACKET_RANGE_CHAT_RANGE);
}
if (this.getPetsFollowingObject().size() >= 1) {
for (int i = 0; i < getPetsFollowingObject().size(); i++) {
CreaturePet pet = getPetsFollowingObject().get(i);
pet.setX(newX + pet.getFollowXOffset());
pet.setY(newY + pet.getFollowYOffset());
pet.setZ(newZ);
pet.setOrientationN(newN);
pet.setOrientationS(newS);
pet.setOrientationE(newE);
pet.setOrientationW(newW);
pet.setVelocity(fVelocity);
pet.setMovementAngle(MovAngle);
server.moveObjectInTree(pet, newX, newY, pet.getPlanetID(), pet
.getPlanetID());
getClient().insertPacket(
PacketFactory.buildUpdateTransformMessage(pet),
Constants.PACKET_RANGE_CHAT_RANGE);
}
}
if (this.bIsTraveling) {
return;
}
Vector<SOEObject> vObjectsAfterMovement = server
.getWorldObjectsAroundObject(this);
Vector<SOEObject> vStillSpawned = new Vector<SOEObject>();
for (int i = 0; i < vObjectsBeforeMovement.size(); i++) {
SOEObject p = vObjectsBeforeMovement.elementAt(i);
if (!vObjectsAfterMovement.contains(p)) {
// System.out.println("Player " + p.getFullName() +
// " no longer seen by " + getFullName());
if (p instanceof Player && !(p instanceof NPC)
&& !(p instanceof Terminal)) {
Player play = (Player) p;
play.despawnItem(this);
}
if (p.getID() == this.getCurrentMount() && bIsMounted) {
// System.out.println("Attempt to Despawn mount while mounted!!!!");
} else {
despawnItem(p);
}
}
}
for (int i = 0; i < vObjectsAfterMovement.size(); i++) {
SOEObject p = vObjectsAfterMovement.elementAt(i);
if (!vObjectsBeforeMovement.contains(p)) {
if (p instanceof Player && !(p instanceof NPC)
&& !(p instanceof Terminal)) {
Player play = (Player) p;
play.spawnItem(this);
}
if (p.getID() == this.getCurrentMount() && bIsMounted) {
// its our mount dont do nothin!
// System.out.println("Attempt to spawn our mount while mounted!!!");
} else {
spawnItem(p);
/*
* long pCellID = p.getCellID();
*
* if (pCellID == 0) {client.insertPacket(PacketFactory.
* buildNPCUpdateTransformMessage(p)); } else {
* client.insertPacket
* (PacketFactory.buildNPCUpdateCellTransformMessage(p,
* server.getObjectFromAllObjects(pCellID))); }
*/
}
} else {
vStillSpawned.add(p);
}
}
Cell c = null;
// System.out.println("Objects still spawned: " + vStillSpawned.size());
/*
* for (int i = 0; i < vStillSpawned.size(); i++) { SOEObject o =
* vStillSpawned.elementAt(i); if (o instanceof Player && !(o instanceof
* NPC) && !(o instanceof Terminal)) { Player p = (Player) o; if
* (o.getID() != getID()) { //if(!this.isDancing ||
* !this.isPlayingMusic) { if (this.getCellID() != 0) {
* p.getClient().insertPacket
* (PacketFactory.buildUpdateContainmentMessage(this, c, -1)); }
* p.getClient
* ().insertPacket(PacketFactory.buildUpdateTransformMessage(this)); } }
* } }
*/
if (!this.isDancing && !this.isPlayingMusic) {
if (this.getCellID() != 0) {
getClient().insertPacket(
PacketFactory
.buildUpdateContainmentMessage(this, c, -1),
Constants.PACKET_RANGE_CHAT_RANGE);
}
getClient().insertPacket(
PacketFactory.buildUpdateTransformMessage(this),
Constants.PACKET_RANGE_CHAT_RANGE);
}
}
protected void initializeInteriorPosition(int moveCounter, float newN,
float newS, float newE, float newW, float newX, float newZ,
float newY, float fVelocity, long cellID) {
setCellID(cellID);
setCellX(newX);
setCellY(newY);
setCellZ(newZ);
setOrientationN(newN);
setOrientationE(newE);
setOrientationS(newS);
setOrientationW(newW);
setVelocity(fVelocity);
Vector<IntangibleObject> vDatapadItems = tDatapad.getIntangibleObjects();
for (int i = 0; i < vDatapadItems.size(); i++) {
IntangibleObject o = vDatapadItems.elementAt(i);
NPC theCalledObject = o.getAssociatedCreature();
if (theCalledObject != null) {
o.setRadialCondition(Constants.RADIAL_CONDITION.INTANGIBLE_VEHICLE_SPAWNED.ordinal());
} else {
o.setRadialCondition(Constants.RADIAL_CONDITION.TANGIBLE_ITEM_INDOORS.ordinal());
}
}
for (int i = 0; i < vInventoryItemsList.size(); i++) {
TangibleItem inventoryItem = vInventoryItemsList.elementAt(i);
inventoryItem.setRadialCondition(Constants.RADIAL_CONDITION.TANGIBLE_ITEM_INDOORS.ordinal());
}
}
/**
* This function updates the position of the Player when the Player is
* inside of a Structure / Cell object.
*
* @param moveCounter
* -- The number of times the Player's position has been updated.
* @param newN
* -- The Player's North orientation.
* @param newS
* -- The Player's South orientation.
* @param newE
* -- The Player's X axis rotation.
* @param newW
* -- The Player's Y axis rotation.
* @param newX
* -- The Player's X coordinate.
* @param newZ
* -- The Player's Z coordinate.
* @param newY
* -- The Player's Y coordinate.
* @param fVelocity
* -- The Player's velocity.
* @param cellID
* -- The Cell the Player is currently occupying.
* @throws IOException
* If an error occured building the position update packet.
*/
protected void updateInteriorPosition(int moveCounter, float newN,
float newS, float newE, float newW, float newX, float newZ,
float newY, float fVelocity, long cellID) throws IOException {
// float dX;
// float dY;
// float dZ;
// dX = Math.abs(newX - discardedX);
// dY = Math.abs(newY - discardedY);
// dZ = Math.abs(newZ - discardedZ);
// double displacement = Math.sqrt(
// (dX * dX) +
// (dY * dY) +
// (dZ * dZ));
discardedX = newX;
discardedY = newY;
discardedZ = newZ;
// this was causing invalid cell id to be saved.
/*
* if (lCellID == 0 || displacement > 50) { if (lCellID == 0) { lCellID
* = (cellID / 2) + 1; } return; }
*/
long oldCellID = getCellID();
Cell c = (Cell) server.getObjectFromAllObjects(cellID);
Structure s = c.getBuilding();
float MovAngle = 0;
if (((newN * newN) + (newS * newS) + (newE * newE)) > 0.0) {
if (newW > 0.0 && newE < 0.0) {
newW *= -1;
}
MovAngle = (float) (2.0 * Math.acos(newW));
} else {
MovAngle = 0.0f;
}
// server.getWorldObjectsAroundObject(this);
Vector<SOEObject> vObjectsBeforeMovement = server
.getWorldObjectsAroundObject(this);
c.addCellObject(this);
if (oldCellID == 0) {
Vector<IntangibleObject> vDatapadItems = tDatapad.getIntangibleObjects();
for (int i = 0; i < vDatapadItems.size(); i++) {
IntangibleObject o = vDatapadItems.elementAt(i);
NPC theCalledObject = o.getAssociatedCreature();
if (theCalledObject != null) {
o.setRadialCondition(Constants.RADIAL_CONDITION.INTANGIBLE_VEHICLE_SPAWNED.ordinal());
} else {
o.setRadialCondition(Constants.RADIAL_CONDITION.TANGIBLE_ITEM_INDOORS.ordinal());
}
}
for (int i = 0; i < vInventoryItemsList.size(); i++) {
TangibleItem inventoryItem = vInventoryItemsList.elementAt(i);
inventoryItem.setRadialCondition(Constants.RADIAL_CONDITION.TANGIBLE_ITEM_INDOORS.ordinal());
}
s.spawnObjectsInBuildingCells(client);
} else if (oldCellID != cellID) {
Cell oldCell = (Cell)server.getObjectFromAllObjects(oldCellID);
oldCell.removeCellObject(this);
}
synchronized(this) {
setCellID(cellID);
}
setCellX(newX);
setCellY(newY);
setCellZ(newZ);
// ------------------------------------
// The way we add or remove Cell X from or to x and Cell y from or to y
// depends on building Direction.
if (s != null && s.getIsStaticObject()) {
setX(s.getX() + newX);
setY(s.getY() + newY);
setZ(s.getZ() + newZ);
} else if (s != null) {
switch (s.getIFacingDirection()) {
case 0: {
setX(s.getX() + newX);
setY(s.getY() + newY);
setZ(s.getZ() + newZ);
break;
}
case 1: {
setX(s.getX() + newY);
setY(s.getY() - newX);
setZ(s.getZ() + newZ);
break;
}
case 2: {
setX(s.getX() - newX);
setY(s.getY() - newY);
setZ(s.getZ() + newZ);
break;
}
case 3: {
setX(s.getX() - newY);
setY(s.getY() + newX);
setZ(s.getZ() + newZ);
break;
}
}
}
// -----------------------------
setOrientationN(newN);
setOrientationE(newE);
setOrientationS(newS);
setOrientationW(newW);
setVelocity(fVelocity);
setMovementAngle(MovAngle);
if (this.bIsTraveling) {
return;
}
Vector<SOEObject> vObjectsAfterMovement = server
.getWorldObjectsAroundObject(this);
Vector<SOEObject> vStillSpawned = new Vector<SOEObject>();
for (int i = 0; i < vObjectsBeforeMovement.size(); i++) {
SOEObject p = vObjectsBeforeMovement.elementAt(i);
if (!vObjectsAfterMovement.contains(p)) {
// System.out.println("Player " + p.getFullName() +
// " no longer seen by " + getFullName());
if (p instanceof Player && !(p instanceof NPC)
&& !(p instanceof Terminal)) {
Player play = (Player) p;
play.despawnItem(this);
}
despawnItem(p);
}
}
for (int i = 0; i < vObjectsAfterMovement.size(); i++) {
SOEObject p = vObjectsAfterMovement.elementAt(i);
if (!vObjectsBeforeMovement.contains(p)) {
if (p instanceof Player && !(p instanceof NPC)
&& !(p instanceof Terminal)) {
Player play = (Player) p;
play.spawnItem(this);
}
spawnItem(p);
/*
* if (p instanceof Shuttle) { Shuttle shuttle = (Shuttle)p; if
* (!shuttle.getIsSpawned()) { shuttle.flyOut(client); } }
*/
} else {
vStillSpawned.add(p);
}
}
// System.out.println("Objects still spawned: " + vStillSpawned.size());
/*
* for (int i = 0; i < vStillSpawned.size(); i++) { SOEObject o =
* vStillSpawned.elementAt(i); if (o instanceof Player && !(o instanceof
* NPC) && !(o instanceof Terminal)) { Player p = (Player) o; if
* (o.getID() != getID()) { //if(!this.isDancing &&
* !this.isPlayingMusic) { if (this.getCellID() != cellID) {
* //p.getClient
* ().insertPacket(PacketFactory.buildUpdateContainmentMessage(this, //
* server.getObjectFromAllObjects(lCellID), // false));
* p.getClient().insertPacket
* (PacketFactory.buildUpdateContainmentMessage(this, c, -1)); }
* p.getClient
* ().insertPacket(PacketFactory.buildUpdateCellTransformMessage(this,
* c)); } } } }
*/
if (!this.isDancing && !this.isPlayingMusic) {
if (this.getCellID() != cellID) {
getClient().insertPacket(
PacketFactory
.buildUpdateContainmentMessage(this, c, -1),
Constants.PACKET_RANGE_CHAT_RANGE);
}
getClient().insertPacket(
PacketFactory.buildUpdateCellTransformMessage(this, c),
Constants.PACKET_RANGE_CHAT_RANGE);
}
if ((this.getCellID() != 0)) {
if (this.getCellID() != cellID) {
Cell oldCell = (Cell) server.getObjectFromAllObjects(this
.getCellID());
if (oldCell != null) {
this.setCellID(cellID);
oldCell.removeCellObject(this);
c.addCellObject(this);
}
}
} else {
this.setCellID(cellID);
c.addCellObject(this);
}
}
/**
* Gets the full name of the Player, in the format Firstname Lastname
*
* @return The Player's full name.
*/
protected String getFullName() {
if (sLastName == null || sLastName.length() < 1) {
return sFirstName;
} else {
StringBuffer buff = new StringBuffer().append(sFirstName).append(
" ").append(sLastName);
return buff.toString();
}
}
/**
* Gets the Player's first name.
*
* @return The Player's first name.
*/
protected String getFirstName() {
return sFirstName;
}
/**
* Get the Player's last name.
*
* @returns The player's last name.
*/
protected String getLastName() {
return sLastName;
}
/**
* Sets the player's Active status. If the player becomes inactive, saves
* him to the database.
*
* @param status
* -- The player's active status.
*/
protected void setActive(boolean status) {
if (!status) {
// Save me to the database!!!
}
bActive = status;
}
/**
* Gets the player's active status.
*
* @return The active status.
*/
protected boolean getStatus() {
return bActive;
}
/**
* Convenience function -- returns the ID of the Player's "PlayItem".
*
* @return The PlayItem Object ID.
*/
public long getPlayObjectID() {
return thePlayer.getID();
}
public long getFriendsListID() {
return thePlayer.getID() + 11;
}
private transient Waypoint wSurveyWaypoint; // This is simply a pointer to
// the given waypoint.
protected Waypoint getSurveyWaypoint() {
return wSurveyWaypoint;
}
public void addSurveyWaypoint(Waypoint w) {
if (w != null) {
if (wSurveyWaypoint == null) {
wSurveyWaypoint = w;
wSurveyWaypoint.setID(server.getNextObjectID());
addWaypoint(wSurveyWaypoint, true);
server.addObjectToAllObjects(wSurveyWaypoint, false, false);
} else {
wSurveyWaypoint.setName("Survey location");
wSurveyWaypoint.setPlanetID(getPlanetID());
wSurveyWaypoint
.setPlanetCRC(Constants.PlanetCRCForWaypoints[getPlanetID()]);
wSurveyWaypoint.setX(w.getX());
wSurveyWaypoint.setY(w.getY());
wSurveyWaypoint.setZ(w.getZ());
w.setIsActivated(true);
w.setWaypointType(Constants.WAYPOINT_TYPE_PLAYER_CREATED);
client.insertPacket(PacketFactory.buildWaypointDelta(this, w,
Constants.DELTA_UPDATING_ITEM));
}
} else {
wSurveyWaypoint = null;
}
}
/**
* Adds a new Waypoint the PlayItem's list of waypoints. Sends a packet back
* to the Player containing the new waypoint.
*
* @param w
* -- The waypoint to be added.
*/
public void addWaypoint(Waypoint w, boolean bUpdate) {
// System.out.println("Adding waypoint " + w.getName() + " to player " +
// getFullName());
thePlayer.addWaypoint(w);
// client.insertPacket(PacketFactory.buildBaselinePLAY8(getPlayData()));
// System.out.println("Calling buildWaypointDelta");
if (bUpdate) {
client.insertPacket(PacketFactory.buildWaypointDelta(this, w,
Constants.DELTA_CREATING_ITEM));
}
}
public void deleteWaypoint(Waypoint w, boolean bUpdate) {
if (thePlayer.deleteWaypoint(w)) {
if (bUpdate) {
try {
// this.despawnItem(w);
client.insertPacket(PacketFactory.buildWaypointDelta(this,
w, Constants.DELTA_DELETING_ITEM));
} catch (Exception e) {
DataLog.logEntry("Exception in Player.deleteWaypoint "
+ e.toString(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exception in player.deleteWaypoint "
// + e );
e.printStackTrace();
}
}
}
}
public int getLastWaypointIndex() {
return (thePlayer.getWaypointListSize() - 1);
}
/**
* Indicates if this Player is currently riding a vehicle.
*
* @return If the player is on/in a vehicle.
*/
public boolean isMounted() {
return bIsMounted;
}
/**
* Sets the player to be mounted on "something"
*
* @param bIsVehicle
* -- Indicates if the player is mounting a vehicle or a
* creature. True for vehicle, false for creature.
*/
public void setPlayerIsMounted(boolean bIsVehicle) {
bIsMounted = true;
if (bIsVehicle) {
addState(Constants.STATE_MOUNTED_VEHICLE, -1l);
// setStance(Constants.STANCE_DRIVING, false);
} else {
addState(Constants.STATE_MOUNTED_CREATURE, -1l);
// setStance(Constants.STANCE_MOUNTED, false);
}
// setStance(Constants.STANCE_MOUNTED, false);
}
public void setPlayerIsNotMounted() {
if (setStance(null, Constants.STANCE_STANDING, false)) { // Forcibly
// stand the
// player
// when they
// dismount,
// unless
// they
// dismounted
// because
// they
// became
// incapacitated.
bIsMounted = false;
removeState(Constants.STATE_MOUNTED_CREATURE);
removeState(Constants.STATE_MOUNTED_VEHICLE);
}
}
public long getCurrentMount() {
return lCurrentMount;
}
public void setCurrentMount(long MountID) {
lCurrentMount = MountID;
}
/**
* Get the player's current mood ID for spatial chat functions.
*
* @return The mood ID.
*/
public int getMoodID() {
return moodID;
}
public void setMoodID(int id) {
if (id < 0 || id > Constants.vMoodStrings.length) {
} else {
moodID = id;
setMoodString(Constants.vMoodStrings[moodID]);
}
}
/**
* Get the Emote ID for spatial chat functions.
*
* @return The Emote ID
*/
public int getPerformedEmoteID() {
return emoteID;
}
/**
* Sets the current Emote ID for spatial chat functions.
*
* @param id
* -- The Emote ID
*/
public void setPerformedEmoteID(int id) {
emoteID = id;
}
/**
* Gets a list of all of this Player's friends.
*
* @return The friends list.
*/
public Vector<PlayerFriends> getFriendsList() {
return thePlayer.getFriendsList();
}
/**
* Gets a list of all the Players which this Player is ignoring.
*
* @return The ignore list.
*/
public Vector<PlayerFriends> getIgnoreList() {
return thePlayer.getIgnoreList();
}
// TODO: Add in a function that detects whether the travel terminal the
// player is using is a starport terminal.
/**
* Returns whether the Player is currently using a Starport terminal instead
* of a Shuttleport terminal.
*/
public boolean isAtStarport() {
return true;
}
/**
* Returns the ID of the Terminal this Player is currently using.
*
* @return The terminal ID.
*/
public int getTerminalID() {
return iCurrentTerminalID;
}
/**
* Return the Flourish ID this Player is currently performing, if any.
*
* @return The Flourish ID.
*/
public int getFlourishID() {
return iFlourishID;
}
/**
* Sets the Flourish ID that this Player is currently performing, if any.
*
* @param id
* -- The Flourish ID.
*/
public void setFlourishID(int id) {
iFlourishID = id;
}
/**
* Returns the pointer to the Zone Server this Player is currently residing
* on.
*
* @return The Zone Server.
*/
public ZoneServer getServer() {
return server;
}
/**
* Sets the Zone Server this Player is active on.
*
* @param server
* -- The Zone Server.
*/
protected void setServer(ZoneServer server) {
this.server = server;
}
/**
* Gets the number of "tells" this user has received / sent.
*
* @return The tell count.
*/
protected int getTellCount() {
return iTellCount;
}
/**
* Sets the tell count.
*
* @param iTellCount
* -- The number of tells the client states it's sent.
*/
protected void setTellCount(int iTellCount) {
this.iTellCount = iTellCount;
}
/**
* Gets the skill animation the player is currently performing.
*
* @return The skill animation.
*/
public String getPerformedAnimation() {
bClearPerformedAnimation = false;
return sPerformedAnimation;
}
public void setPerformedAnimation(String sPerformedAnimation) {
bClearPerformedAnimation = false;
this.sPerformedAnimation = sPerformedAnimation;
}
public void setBClearPerformedAnimation(boolean bClearPerformedAnimation) {
this.bClearPerformedAnimation = bClearPerformedAnimation;
}
/**
* Unknown function.
*
* @return
*/
public String getCurrentEffectOnOtherObjects() {
return sClientEffectString;
}
/**
* Returns the Player's currently equipped weapon. Should never return null,
* as the Player always has a weapon equipped (even if it's just his
* "fists").
*
* @return The currently equipped weapon
*/
public Weapon getWeapon() {
return equippedWeapon;
}
/**
* Equips the given weapon.
*
* @param w
* -- The weapon.
*/
public void equipWeapon(Weapon w, boolean updateZone) {
try {
if (w != null) {
equippedWeapon = w;
if (equippedWeapon.isDefaultWeapon()) {
defaultWeapon = equippedWeapon;
}
// Calculate and set the challenge rating.
float weaponDamagePerSecond = equippedWeapon
.getAverageDamageRound()
/ equippedWeapon.getRefireDelay();
setConLevel((short) weaponDamagePerSecond, updateZone);
if (updateZone) {
if (!vAllSpawnedObjectIDs.contains(equippedWeapon.getID())) {
spawnItem(equippedWeapon);
}
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(equippedWeapon,
this, 4));
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 6, (short) 1,
(short) 5, this, equippedWeapon.getID()),
Constants.PACKET_RANGE_CHAT_RANGE);
client.insertPacket(PacketFactory
.buildDeltasMessage_EquippedItem(this,
equippedWeapon, (byte) 1,
Constants.SLOT_ID_WEAPON),
Constants.PACKET_RANGE_CHAT_RANGE);
int skillRequired = equippedWeapon.getSkillRequirement();
System.out.println("Required skill ID for weapon "
+ equippedWeapon.getName() + ": " + skillRequired);
if (skillRequired != -1) {
if (!hasSkill(skillRequired)) {
client.insertPacket(PacketFactory
.buildChatSystemMessage("combat_effects",
"no_proficiency", 0l, "", "", "",
0l, "", "", "", 0l, "", "", "", 0,
0f, false));
setConLevel((short) 0, true);
} else {
System.out.println("Player has requisite skill.");
}
}
}
}
} catch (Exception e) {
// D'oh!
}
}
public void updateEquippedWeapon(Weapon newWeapon, boolean updateZone) {
try {
if (equippedWeapon != null) {
equippedWeapon.setEquipped(getInventory(), -1);
}
if (newWeapon != null) {
equipWeapon(newWeapon, updateZone);
} else {
equipWeapon(defaultWeapon, updateZone);
}
if (newWeapon instanceof Instrument) {
this.equippedInstrument = (Instrument) newWeapon;
}
} catch (Exception e) {
DataLog.logException(
"Error building deltas messages for equipped item status: "
+ e.toString(), "Player.updateEquippedWeapon()",
true, true, e);
}
}
/**
* Returns the Player's current Stance.
*
* @return The stance.
*/
public byte getStance() {
return iStance;
}
/**
* Updates the Player's current stance.
*
* @param newStance
* -- The new Stance.
*/
public boolean setStance(CommandQueueItem action, byte newStance,
boolean bForceNewStance) {
if (lastUsedSurveyTool != null) {
if (iStance == Constants.STANCE_KNEELING
&& newStance != Constants.STANCE_KNEELING) {
lastUsedSurveyTool.stopSurveying();
bIsSampling = false;
try {
client.insertPacket(PacketFactory.buildChatSystemMessage(
"survey", "sample_cancel", 0l, "", "", "", 0l, "",
"", "", 0l, "", "", "", 0, 0f, false));
} catch (Exception e) {
// D'oh!
}
}
}
if (newStance != iStance) {
// If we're dead, we can't just stand back up. We need to be stood
// back up by something else.
if (bForceNewStance
|| (iStance != Constants.STANCE_DEAD && iStance != Constants.STANCE_INCAPACITATED)) {
iStance = newStance;
setCommandQueueErrorStance(iStance);
try {
if (client != null) {
boolean bCanChangePosture = true;
if (hasState(Constants.STATE_DIZZY)) {
int iChanceToChangePosture = SWGGui
.getRandomInt(10);
if (iChanceToChangePosture != 0) {
bCanChangePosture = false;
}
if (!bCanChangePosture) {
// Knock me down and make me flop around.
iStance = Constants.STANCE_KNOCKED_DOWN;
setCommandQueueErrorStance(iStance);
client
.insertPacket(
PacketFactory
.buildObjectControllerMessage_UpdatePosture(this),
Constants.PACKET_RANGE_CHAT_RANGE);
client.insertPacket(PacketFactory
.buildDeltasMessage(
Constants.BASELINES_CREO,
(byte) 3, (short) 1,
(short) 0x0B, this, iStance),
Constants.PACKET_RANGE_CHAT_RANGE);
client.insertPacket(PacketFactory
.buildChatSystemMessage("cbt_spam",
"dizzy_fall_down_single"));
}
}
if (bCanChangePosture) {
client
.insertPacket(
PacketFactory
.buildObjectControllerMessage_UpdatePosture(this),
Constants.PACKET_RANGE_CHAT_RANGE);
client.insertPacket(PacketFactory
.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 3,
(short) 1, (short) 0x0B, this,
iStance),
Constants.PACKET_RANGE_CHAT_RANGE);
if (this.isDancing()) {
System.out
.println("Player Was Dancing Resetting to not Dancing.");
this.setIsDancing(false);
// this.setSongID(0);// the ones set here to be
// commented out cannot be reset ot 0 or false.
// this.setPerformanceID(0);//seems the client
// does that automatically when we move or
// change posture if messed with the client will
// stop sending updates to other players
this.setPerformanceString("");
// this.setC60X11(false);//
client.insertPacket(PacketFactory
.buildChatSystemMessage("performance",
"dance_stop_self",
this.getID(), this
.getSTFFileName(),
this.getSTFFileIdentifier(),
this.getFullName(), 0, null,
null, null, 0, null, null,
null, 0, 0.0f, false));
} else if (this.isPlayingMusic()) {
this.setIsPlayingMusic(false);
this.setListeningToID(0);
this.setSongID(0);
// @todo remove the playing musig info from the
// player.
}
}
}
} catch (Exception e) {
// Oh well.
}
return true;
} else {
action
.setErrorMessageID(Constants.COMMAND_QUEUE_ERROR_TYPE_CANNOT_EXECUTE_IN_STANCE);
action.setStateInvoked(getCommandQueueErrorStance());
return false;
}
}
return true;
}
/**
* Adds a state to the player.
*
* @param iState
* -- The state to add.
*/
public void addState(int iStateToSet, long lTimeToApply) {
long lPreviousState = lState;
lState = lState | (0x01 << iStateToSet);
if (lPreviousState != lState) {
if (client != null) {
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 3, (short) 1,
(short) 0x10, this, getStateBitmask()),
Constants.PACKET_RANGE_CHAT_RANGE);
} catch (IOException e) {
// D'oh!
}
}
}
if (lStateTimer == null) {
lStateTimer = new long[Constants.NUM_STATES];
}
lStateTimer[iStateToSet] = lTimeToApply;
if (iStateToSet == Constants.STATE_COMBAT && lTimeInCombat == 0) {
lTimeInCombat = System.currentTimeMillis();
}
}
private transient long lTimeInCombat = 0;
/**
* Removes a state from the player.
*
* @param iState
* -- The state to remove.
*/
public void removeState(int iStateToSet) {
long lPreviousState = lState;
lState = lState & ~(0x01 << iStateToSet);
if (lPreviousState != lState) {
if (client != null) {
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 3, (short) 1,
(short) 0x10, this, getStateBitmask()),
Constants.PACKET_RANGE_CHAT_RANGE);
} catch (IOException e) {
// D'oh!
}
}
}
if (lStateTimer[iStateToSet] > 0) {
lStateTimer[iStateToSet] = 0;
}
}
public boolean hasState(int iStateToSet) {
return (lState & (1 << iStateToSet)) != 0;
}
/**
* Gets the Race ID of the Player.
*
* @return The Player's Race ID.
*/
public int getRaceID() {
return iRaceID;
}
/**
* Sets the CRC which is used to spawn this Player when other clients see
* him.
*
* @param iCRC
* -- The shared race CRC.
*/
public void setSharedCRC(int iCRC) {
spawnCRC = iCRC;
}
/**
* Gets the CRC used to spawn this Player when other clients see him.
*
* @return The shared CRC.
*/
public int getSharedCRC() {
return spawnCRC;
}
/**
* Gets the number of updates performed on the Skill List since it was last
* reset.
*
* @return The skill list update counter.
*/
public synchronized int getSkillListUpdateCount(boolean bIncrement) {
if (bIncrement) {
iSkillListUpdateCount++;
}
return iSkillListUpdateCount;
}
/**
* Gets the number of credits the Player currently has banked.
*
* @return The bank credits.
*/
public int getBankCredits() {
return iBankCredits;
}
public void transferBankCreditsToInventory() {
iInventoryCredits += iBankCredits;
iBankCredits = 0;
updateCredits();
}
/**
* Gets the number of credits the Player currently has in inventory.
*
* @return The inventory credits.
*/
public int getInventoryCredits() {
return iInventoryCredits;
}
public void transferInventoryCreditsToBank() {
iBankCredits += iInventoryCredits;
iInventoryCredits = 0;
updateCredits();
}
public boolean hasEnoughCredits(int amount) {
boolean retval = false;
int comp = iBankCredits + iInventoryCredits;
if (comp >= amount) {
retval = true;
}
return retval;
}
public boolean hasEnoughInventoryCredits(int amount) {
boolean retval = false;
if (iInventoryCredits >= amount) {
retval = true;
}
return retval;
}
/**
* Returns the list of HAM modifiers applying to the Player.
*
* @return The Ham Modifiers list.
*/
public int[] getHamModifiers() {
return iHamModifiers;
}
public void setHamModifiers(int[] mods) {
iHamModifiers = mods;
}
/**
* Increments the Ham Modifiers list update counter, then gets it.
*
* @return The Ham Modifiers update counter.
*/
public synchronized int getHamModifiersUpdateCount(boolean bIncrement) {
if (bIncrement) {
iHamModifiersUpdateCount++;
}
return iHamModifiersUpdateCount;
}
/**
* Gets the period of time remaining in which the Player is incapacitated
* and unable to perform actions.
*
* @return The incap timer.
*/
public int getIncapTimer() {
return iIncapTimer;
}
/**
* Gets the Player's Scale.
*
* @return The Scale factor of the Player.
*/
public float getScale() {
return fScale;
}
/**
* Gets the Player's current Battle Fatigue level.
*
* @return The Battle Fatigue of the Player.
*/
public int getBattleFatigue() {
return iBattleFatigue;
}
public void updateBattleFatigue(int iFatigueToAdd, boolean updateZone) {
int iPreviousBattleFatigue = iBattleFatigue;
iBattleFatigue += iFatigueToAdd;
iBattleFatigue = Math.max(iBattleFatigue, 0);
iBattleFatigue = Math.min(iBattleFatigue, 1000);
if (updateZone && (iBattleFatigue != iPreviousBattleFatigue)) {
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 3, (short) 1,
(short) 15, this, iBattleFatigue));
} catch (Exception e) {
// D'oh!
}
}
}
/**
* Builds the actual state bitmask number, from the State bitset, then
* returns it.
*
* @return The state bitmask.
*/
public long getStateBitmask() {
return lState;
}
/**
* Gets the list of wounds to the Player's maximum ham.
*
* @return The ham wounds list.
*/
public int[] getHamWounds() {
return iHamWounds;
}
/**
* Increments the update counter on the Ham Wounds variable, then returns
* it.
*
* @return The ham wounds update counter.
*/
public synchronized int getHamWoundsUpdateCount(boolean bIncrement) {
if (bIncrement) {
iHamWoundsUpdateCount++;
}
return iHamWoundsUpdateCount;
}
/**
* Gets the list of skill modifiers applicable for this Player.
*
* @return The skill mods list.
*/
public Vector<SkillMods> getSkillModsList() {
return vSkillModsList;
}
/**
* Searches for a particular skill mod by name, in the Player's list of
* skill mods, and returns it.
*
* @param skillModName
* -- The skill mod being searched for.
* @return The skill mod, or null if the Player does not have the skill mod.
*/
public SkillMods getSkillMod(String skillModName) {
try {
for (int i = 0; i < vSkillModsList.size(); i++) {
SkillMods mod = vSkillModsList.elementAt(i);
if (mod.getName().equalsIgnoreCase(skillModName)) {
return mod;
}
}
} catch (Exception e) {
// Most likely a null pointer -- return null anyway.
return null;
}
return null;
}
/**
* Increases the modifier value of a skill mod, by name. If the Player does
* not have the skill mod, adds the skill mod.
*
* @param sModName
* -- The skill modifier name.
* @param iDeltaValue
* -- The value to increase the modifier by.
*/
public void increaseSkillModValue(String sModName, int iDeltaValue,
boolean bUpdateZone) {
System.out.println("Player " + sFirstName + " increasing skill mod "
+ sModName + " by " + iDeltaValue);
try {
for (int i = 0; i < vSkillModsList.size(); i++) {
SkillMods existMod = vSkillModsList.elementAt(i);
if (existMod.getName().equals(sModName)) {
int iSkillModValue = existMod.getSkillModModdedValue();
iSkillModValue += iDeltaValue;
System.out.println("New skillmod value: " + iSkillModValue);
if (iSkillModValue == 0) {
vSkillModsList.remove(existMod);
if (bUpdateZone) {
client.insertPacket(PacketFactory
.buildSkillModsDelta(this, existMod,
Constants.DELTA_DELETING_ITEM),
Constants.PACKET_RANGE_CHAT_RANGE);
// client.insertPacket(PacketFactory.buildSkillModsDelta(this,
// existMod, Constants.DELTA_DELETING_ITEM));
}
} else {
existMod.setSkillModModdedValue(iSkillModValue);
if (bUpdateZone) {
client.insertPacket(PacketFactory
.buildSkillModsDelta(this, existMod,
Constants.DELTA_UPDATING_ITEM),
Constants.PACKET_RANGE_CHAT_RANGE);
// client.insertPacket(PacketFactory.buildSkillModsDelta(this,
// existMod, Constants.DELTA_UPDATING_ITEM));
}
}
return;
}
}
SkillMods mod = new SkillMods();
mod.setName(sModName);
mod.setSkillModModdedValue(iDeltaValue);
addSkillMod(mod, bUpdateZone);
} catch (Exception e) {
DataLog.logEntry("Error updating skill mod: " + e.toString(),
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Error updating skill mod: " + e.toString());
e.printStackTrace();
}
}
/**
* Add a new Skill Mod to the list of Skill Mods.
*
* @param mod
* -- The skill mod to add.
*/
public void addSkillMod(SkillMods mod, boolean bUpdateZone) {
vSkillModsList.add(mod);
if (bUpdateZone) {
try {
client.insertPacket(PacketFactory.buildSkillModsDelta(this,
mod, Constants.DELTA_CREATING_ITEM),
Constants.PACKET_RANGE_CHAT_RANGE);
// client.insertPacket(PacketFactory.buildSkillModsDelta(this,
// mod, Constants.DELTA_CREATING_ITEM));
} catch (Exception e) {
DataLog.logEntry("Error adding skill mod: " + e.toString(),
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Error adding skill mod: " +
// e.toString());
e.printStackTrace();
}
}
}
/**
* Adds a set of Skill Mods to the list of Skill Mods.
*
* @param mods
* -- The list of skill mods to add.
*/
public void addSkillMods(Vector<SkillMods> mods) {
vSkillModsList.addAll(mods);
}
/**
* Gets the list of encumberances currently active on the Player's HAM
* values.
*
* @return The HAM encumberances.
*/
public int[] getHamEncumberances() {
return iHamEncumberance;
}
public void addEncumberance(int[] enc) {
for (int i = 0; i < iHamEncumberance.length; i++) {
iHamEncumberance[i] += enc[i];
}
}
public void removeEncumberance(int[] enc) {
for (int i = 0; i < iHamEncumberance.length; i++) {
iHamEncumberance[i] -= enc[i];
}
}
/**
* Gets the update count of the HAM encumberances active on the Player.
*
* @return The Ham Encumberances update counter.
*/
public synchronized int getHamEncumberanceUpdateCount(boolean bIncrement) {
if (bIncrement) {
iHamEncumberanceUpdateCount++;
}
return iHamEncumberanceUpdateCount;
}
/**
* Gets the Player's current velocity.
*
* @return The velocity.
*/
public float getVelocity() {
return fCurrentVelocity;
}
/**
* Sets the Player's current velocity.
*
* @param v
* -- The velocity.
*/
public void setVelocity(float v) {
fCurrentVelocity = Math.min(v, getMaxVelocity());
}
/**
* Gets the Maximum velocity the Player can travel at.
*
* @return The max velocity.
*/
public float getMaxVelocity() {
return fMaxVelocity;
}
/**
* Sets the Maximum velocity the Player can travel at.
*
* @param fVelocity
* -- The velocity.
*/
public void setMaxVelocity(float fVelocity) {
if (fMaxVelocity != fVelocity) {
fMaxVelocity = fVelocity;
// Deltas message
try {
byte[] velocityDelta = PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 4, (short) 1,
(short) 7, this, fMaxVelocity);
client.insertPacket(velocityDelta,
Constants.PACKET_RANGE_CHAT_RANGE);
} catch (Exception e) {
// D'oh!
}
}
}
/**
* Gets the Player's current acceleration value.
*
* @return The acceleration value.
*/
public float getAcceleration() {
return fCurrentAcceleration;
}
public void setAcceleration(float f) {
if (fCurrentAcceleration != f) {
// Deltas message
fCurrentAcceleration = f;
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 4, (short) 1,
(short) 0x0B, this, fCurrentAcceleration),
Constants.PACKET_RANGE_CHAT_RANGE);
} catch (Exception e) {
// D'oh!
}
}
}
/**
* Gets the Player's current target ID.
*
* @return the Target ID.
*/
public long getTargetID() {
return lTargetID;
}
/**
* Sets the Player's current target ID.
*
* @param objID
* -- The Player's Target ID.
*/
public void setTargetID(long objID) {
lTargetID = objID;
if (objID != 0) {
SOEObject t = this.server.getObjectFromAllObjects(objID);
if (t == null) {
System.out.println("Unknown object targeted with ID " + objID);
return;
} else {
if (this.getInventoryItems().contains(t)
|| this.getDatapad().getIntangibleObjects().contains(t)) {
// we dont need to inform of a target in our inventory.
return;
} else if (t.getParentID() == this.getInventory().getID()) {
return;
}
}
try {
// this.getClient().insertPacket(PacketFactory.buildCreo6ChangeTarget(this,
// t), Constants.PACKET_RANGE_CHAT_RANGE);
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 6, (short) 1,
(short) Constants.DELTAS_CREO6.TARGET_ID.ordinal(),
this, objID), Constants.PACKET_RANGE_CHAT_RANGE);
} catch (Exception e) {
DataLog.logEntry(
"Exception Caught while sending target update to players "
+ e.toString(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exception Caught while sending target update to players "
// + e);
e.printStackTrace();
}
}
}
/**
* Gets the Player's current turning radius.
*
* @return The turn radius.
*/
public float getTurnRadius() {
return fTurnRadius;
}
/**
* Gets the list of all items in the Player's inventory / equipped by the
* Player.
*
* @return The Inventory list.
*/
public Vector<TangibleItem> getInventoryItems() {
return vInventoryItemsList;
}
/**
* Gets the Player's current mood name.
*
* @return The mood name.
*/
public String getMoodString() {
return sMoodString;
}
/**
* Sets the Player's current mood name.
*
* @param sMood
* -- The mood name.
*/
public void setMoodString(String sMood) {
sMoodString = sMood;
}
/**
* Gets the Player's current song/dance performance string.
*
* @return The Player's performance string.
*/
public String getPerformanceString() {
return sPerformanceString;
}
public void setPerformanceString(String sPerformanceString)
throws IOException {
this.sPerformanceString = sPerformanceString;
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 6, (short) 1, (short) 0x03,
this, this.sPerformanceString, false),
Constants.PACKET_RANGE_CHAT_RANGE);
}
/**
* Gets a list of all Players currently defending themselves from this
* Player.
*
* @return The defender list.
*/
public Vector<Long> getDefenderList() {
return vDefenderList;
}
/**
* Increments and then gets the Defender List update counter.
*
* @return The defender list update counter.
*/
public synchronized int getDefenderListUpdateCounter(boolean bIncrement) {
if (bIncrement) {
iDefenderListUpdateCounter++;
}
return iDefenderListUpdateCounter;
}
/**
* Gets the "consider" level of this Player.
*
* @return The Player's con level.
*/
public short getConLevel() {
return iConLevel;
}
public void setConLevel(short con, boolean updateZone) {
iConLevel = con;
if (updateZone) {
try {
// Yes, a different level for me to see than for everyone else
// to see -- that's how pvp consider works.
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 6, (short) 1,
(short) 2, this, iConLevel));
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 6, (short) 1,
(short) 2, this, (short) 1),
Constants.PACKET_RANGE_CHAT_RANGE_EXCLUDE_SENDER);
} catch (Exception e) {
// D'oh!
}
}
}
/**
* Gets the Object ID of the Player's current group, or 0 if the Player is
* not currently part of a group.
*
* @return The group ID.
*/
public long getGroupID() {
if (myGroup != null) {
return myGroup.getID();
} else {
return 0;
}
}
public void setGroupObject(Group g) {
myGroup = g;
}
/**
* Gets the current Dance the Player is dancing, by ID.
*
* @return The Dance ID.
*/
public int getDanceID() {
return iDanceID;
}
/**
* Gets the current Song the Player is singing, by ID.
*
* @return The Song ID.
*/
public int getSongID() {
return iSongID;
}
public void setSongID(int iSongID) throws IOException {
this.iSongID = iSongID;
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 6, (short) 1, (short) 0x0C,
this, this.iSongID), Constants.PACKET_RANGE_CHAT_RANGE);
}
/**
* Gets the Player's current Maximum HAM values.
*
* @return The Max Ham.
*/
public int[] getMaxHam() {
return iMaxHam;
}
/**
* Gets the Player's current HAM values.
*
* @return The current ham.
*/
public int[] getCurrentHam() {
return iCurrentHam;
}
/**
* Increments and then gets the update counter for the Max HAMs.
*
* @return The Max Ham update counter.
*/
public synchronized int getMaxHamUpdateCounter(boolean bIncrement) {
if (bIncrement) {
iMaxHamUpdateCount++;
}
return iMaxHamUpdateCount;
}
/**
* Increments and then gets the update counter for the Current HAMS.
*
* @return The Current Ham update counter.
*/
public synchronized int getCurrentHamUpdateCounter(boolean bIncrement) {
if (bIncrement) {
iCurrentHamUpdateCount++;
}
return iCurrentHamUpdateCount;
}
/**
* Increments and then gets the update counter for the Equipped Item list.
*
* @return The Equippped Item update counter.
*/
public synchronized int getEquippedItemUpdateCount(boolean bIncrement) {
if (bIncrement) {
iEquippedItemUpdateCount++;
}
return iEquippedItemUpdateCount;
}
/**
* Returns if this Player has GM privileges.
*
* @return If this Player's Client's Account is a GM.
*/
protected boolean isGM() {
return server.getAccountDataFromLoginServer(client.getAccountID())
.getIsGM();
}
protected boolean isDev() {
return server.getAccountDataFromLoginServer(client.getAccountID())
.getIsDeveloper();
}
/**
* Attaches this Player to a specific Zone Client.
*
* @param c
* -- The Zone Client.
*/
public void setClient(ZoneClient c) {
client = c;
}
/**
* Gets the pointer to this Player's Zone Client.
*
* @return The Zone Client.
*/
public ZoneClient getClient() {
return client;
}
/**
* Spawns the Player, including his PlayItem, his inventory, and his
* personal appearance effects (hair, etc.)
*/
protected synchronized void spawnPlayer() {
// Force the player's speed back to proper whenever he is spawned.
if (iStance == Constants.STANCE_PRONE) {
fMaxVelocity = Constants.MAX_CRAWL_SPEED_METERS_SEC;
} else {
fMaxVelocity = Constants.MAX_PLAYER_RUN_SPEED_METERS_SEC;
}
fCurrentAcceleration = 1.0f;
defaultWeapon.setWeaponType(Constants.WEAPON_TYPE_UNARMED);
try {
// this saved player object will be used to place the player in the
// same position he was in when he saved.
// this will eliminate the problem with always spawning north.
/*
* Player savedCoords = new Player(server);
* savedCoords.setX(this.getX()); savedCoords.setY(this.getY());
* savedCoords.setZ(this.getZ());
* savedCoords.setOrientationN(this.getOrientationN());
* savedCoords.setOrientationS(this.getOrientationS());
* savedCoords.setOrientationE(this.getOrientationE());
* savedCoords.setOrientationW(this.getOrientationW());
* savedCoords.setPlanetID(this.getPlanetID());
* savedCoords.setCellID(this.getCellID());
* savedCoords.setCellX(this.getCellX());
* savedCoords.setCellY(this.getCellY());
* savedCoords.setCellZ(this.getCellZ());
*/
client.setClientNotReady();
initializeState();
if (iStance != Constants.STANCE_STANDING
&& iStance != Constants.STANCE_KNEELING
&& iStance != Constants.STANCE_PRONE
&& iStance != Constants.STANCE_SITTING) {
iStance = Constants.STANCE_SITTING;
}
// isLoading = true;
client.insertPacket(PacketFactory.buildChatServerStatus());
client.insertPacket(PacketFactory.buildParametersMessage());
client.insertPacket(PacketFactory
.buildConnectPlayerResponseMessage());
client.insertPacket(PacketFactory.buildCmdStartScene(this, 1));
client.insertPacket(PacketFactory.buildServerTimeMessage());
// System.out.println("SpawnPlayer Cell id " + this.getCellID());
if (getCellID() != 0) {
System.out.println("Player Loaded in Cell ID:" + this.getCellID());
Cell Loc = (Cell) server.getObjectFromAllObjects(
this.getCellID());
if (Loc == null) {
DataLog.logEntry("Null Cell In Spawn Player ID:"
+ this.getCellID(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Null Cell In Spawn Player ID:" +
// lCellID);
// lCellID = getCellID();
}
SOEObject so = Loc.getBuilding();
if (so instanceof TutorialObject) {
TutorialObject to = (TutorialObject) so;
if (!to.hasCompleted()) {
System.out.println("Spawning tutorial building.");
spawnItem(to);
} else {
this.setCellID(0);
}
} else if (so instanceof Structure) {
Structure s = (Structure) so;
if (s != null && !s.getIsStaticObject()) {
spawnItem(s);
} else if (s == null) {
DataLog.logEntry("Null Structure In Spawn Player ID:"
+ this.getCellID(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(),
true);
// System.out.println("Null Structure in SpawnPlayer" );
if (Loc != null) {
s = Loc.getBuilding();
if (s != null) {
spawnItem(s);
} else {
System.out
.println("Bad Structure cannot find.");
}
}
}
}
}
// System.out.println("SpawnPlayer Cell id " + this.getCellID());
if (tutorial != null && getCellID() == 0
&& !tutorial.hasCompleted()) {
// System.out.println("Player detected in tutorial. Spawning tutorial 1");
spawnItem(tutorial);
Enumeration<Cell> cEnum = tutorial.getCellsInBuilding()
.elements();
while (cEnum.hasMoreElements()) {
Cell c = cEnum.nextElement();
if (c.getCellObjects().containsKey(this.getID())) {
setCellID(c.getID());
}
}
} else if (tutorial != null && getCellID() != 0
&& !tutorial.hasCompleted()) {
// System.out.println("Player detected in tutorial. Spawning tutorial 2");
spawnItem(tutorial);
} else if (tutorial != null && getCellID() != 0
&& tutorial.hasCompleted()) {
this.setCellID(0);
}
if (iHamModifiers == null) {
iHamModifiers = new int[iNumberOfHams];
}
spawnItem(this);
if (this.getCellID() != 0) {
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(this, server
.getObjectFromAllObjects(this.getCellID()), 4));
}
// System.out.println("Spawn the Player Item.");
spawnItem(thePlayer);
server.addObjectToAllObjects(thePlayer, false, false);
if (tHairObject != null) {
spawnItem(tHairObject);
server.addObjectToAllObjects(tHairObject, false,
false);
}
spawnItem(tDatapad);
server.addObjectToAllObjects(tDatapad, false, false);
// ----------------------------------------------------------
// Mission Related Spawning
// System.out.println("Spawn the MissionBag Item.");
spawnItem(tMissionBag);
server.addObjectToAllObjects(tMissionBag, false, false);
Vector<MissionObject> vML = tMissionBag.getVMissionList();
for (int i = 0; i < vML.size(); i++) {
MissionObject m = vML.elementAt(i);
// tMissionBag.addIntangibleObject(m);
// System.out.println("Spawn the MissionObject Item.");
spawnItem(m);
server.addObjectToAllObjects(m, false, false);
}
// ------------------------------------------------------------
// System.out.println("Spawn the Player Inventory.");
spawnItem(tPlayerInventory);
server.addObjectToAllObjects(tPlayerInventory, false,
false);
// System.out.println("Spawn the Player Bank.");
spawnItem(tBank);
server.addObjectToAllObjects(tBank, false, false);
for (int i = 0; i < vInventoryItemsList.size() /* && i < 1 */; i++) {
TangibleItem e = vInventoryItemsList.elementAt(i);
if (e instanceof Deed) {
Deed d = (Deed) e;
d.setServer(server);
if (!d.isPlaced()) {
// this prevents a placed house deed to spawn to the
// inventory.
// System.out.println("Spawn a Deed.");
spawnItem(d);
server.addObjectToAllObjects(d, false,
false);
}
} else {
// System.out.println("Spawn an Item.");
spawnItem(e); // Null pointer exception -- TANO3.
server.addObjectToAllObjects(e, false, false);
// if this item is a backpack or something that contains
// objects then we need to spawn its contents too or it will
// appear empty
if (e.getLinkedObjects().size() >= 1) {
// System.out.println("Spawning Container With Items in it: "
// + e.getIFFFileName());
Vector<TangibleItem> vContainedItems = e
.getLinkedObjects();
for (int c = 0; c < vContainedItems.size(); c++) {
TangibleItem contained = vContainedItems.get(c);
// System.out.println("Spawning Item in Container: "
// + contained.getIFFFileName());
if (contained.getContainer().equals(e)) {
// System.out.println("Spawn Contained Item.");
spawnItem(contained);
}
server.addObjectToAllObjects(contained,
false, false);
}
}
}
}
// This doesn't necessarially have to happen until/unless the Player
// opens their bank.
Vector<TangibleItem> vBankItems = tBank.getLinkedObjects();
for (int i = 0; i < vBankItems.size(); i++) {
TangibleItem t = vBankItems.get(i);
// System.out.println("Spawn Bank Item.");
spawnItem(t);
server.addObjectToAllObjects(t, false, false);
if (t.getLinkedObjects().size() >= 1) {
// System.out.println("Spawning Container In Bank With Items in it: "
// + t.getIFFFileName());
Vector<TangibleItem> vContainedItems = t.getLinkedObjects();
for (int c = 0; c < vContainedItems.size(); c++) {
TangibleItem contained = vContainedItems.get(c);
// System.out.println("Spawning Item in Container: " +
// contained.getIFFFileName());
if (contained.getContainer().equals(t)) {
// System.out.println("Spawn Contained Item.");
spawnItem(contained);
}
server.addObjectToAllObjects(contained,
false, false);
}
}
}
Vector<IntangibleObject> datapadItems = tDatapad
.getIntangibleObjects();
for (int i = 0; i < datapadItems.size(); i++) {
IntangibleObject itno = datapadItems.elementAt(i);
//System.out.println("Spawn Datapad Item with iff name "
// + itno.getIFFFileName());
// if (itno instanceof ManufacturingSchematic) {
// tDatapad.removeIntangibleObject(itno);
// server.removeObjectFromAllObjects(itno, false);
// ManufacturingSchematic schematic =
// (ManufacturingSchematic)itno;
// CraftingSchematic cSchem = schematic.getCraftingSchematic();
// String sCraftedItemIFFFilename =
// cSchem.getCraftedItemIFFFilename();
// System.out.println("Crafted item name: " +
// sCraftedItemIFFFilename);
// ItemTemplate template =
// DatabaseInterface.getTemplateDataByFilename(sCraftedItemIFFFilename);
// System.out.println("Template data retrieved. IFF filename: "
// + template.getIFFFileName());
// String stfFileName = template.getSTFFileName();
// String stfFileIdentifier = template.getSTFFileIdentifier();
// System.out.println("Setting filename " + stfFileName +
// ", identifier " + stfFileIdentifier +
// " for datapad manufacturing schematic.");
// schematic.setSTFFileNameForMFGSchematic(template.getSTFFileName());
// schematic.setSTFFileIdentifierForMFGSchematic(template.getSTFFileIdentifier());
// schematic.setCraftedName(template.getIFFFileName());
// } else {
spawnItem(itno);
// }
server.addObjectToAllObjects(itno, false, false);
SOEObject ac = itno.getAssociatedCreature();
if (ac != null) {
server.addObjectToAllObjects(ac, false, false);
}
}
// System.out.println("CMD Scene Ready.");
client.insertPacket(PacketFactory.buildCmdSceneReady());
// This is to be moved to "handleClientReady".
// System.out.println("Sending Weather Message.");
client.insertPacket(PacketFactory.buildServerWeatherMessage(server.getCurrentWeather(getPlanetID())));
// if (true) return;
// Can't do this.
/*
* SOEObject theCell = server.getObjectFromAllObjects(getCellID());
* if (theCell == null) {
* client.insertPacket(PacketFactory.buildUpdateTransformMessage
* (this)); } else {
* client.insertPacket(PacketFactory.buildUpdateCellTransformMessage
* (this, theCell)); }
*/
// isLoading = false;
/*
* this.setX(savedCoords.getX()); this.setY(savedCoords.getY());
* this.setZ(savedCoords.getZ());
* this.setOrientationN(savedCoords.getOrientationN());
* this.setOrientationS(savedCoords.getOrientationS());
* this.setOrientationE(savedCoords.getOrientationE());
* this.setOrientationW(savedCoords.getOrientationW());
* this.setPlanetID(savedCoords.getPlanetID());
* this.setCellID(savedCoords.getCellID());
* this.setCellX(savedCoords.getCellX());
* this.setCellY(savedCoords.getCellY());
* this.setCellZ(savedCoords.getCellZ());
*
* if(savedCoords.getCellID() == 0) {
* client.insertPacket(PacketFactory
* .buildObjectControllerPlayerDataTransformToClient(this,
* 0x1B),Constants.PACKET_RANGE_CHAT_RANGE); } else {
* client.insertPacket(PacketFactory.
* buildObjectControllerDataTransformWithParentObjectToClient(this,
* 0x1B),Constants.PACKET_RANGE_CHAT_RANGE); }
*/
} catch (Exception e) {
DataLog.logEntry("Exploded spawning the player: " + e.toString(),
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exploded spawning the player: " +
// e.toString());
e.printStackTrace();
}
}
protected void despawnItem(SOEObject i) throws IOException {
if (i == null) {
return;
}
if (i.equals(this)) {
// System.out.println("Despawn Our Selves in despawnitem");
// why should we despawn us to our us?
/*
* StackTraceElement[] elements =
* Thread.currentThread().getStackTrace(); for (int s = 0; s <
* elements.length; s++) { System.out.println(elements[s]); }
*/
return;
}
if (i instanceof CreaturePet) {
CreaturePet pet = (CreaturePet) i;
if (pet.isFollowing()) {
if (pet.objectBeingFollowed() != null
&& pet.objectBeingFollowed().equals(this)) {
return;
}
}
}
if (i.getIsStaticObject()) {
// System.out.println("Attempting to despawn a static item -- no need.");
return;
}
long itemID = i.getID();
boolean bFound = false;
for (int I = 0; I < vAllSpawnedObjectIDs.size() && !bFound; I++) {
long lCompareID = vAllSpawnedObjectIDs.elementAt(I);
if (lCompareID == itemID) {
bFound = true;
client.insertPacket(PacketFactory.buildSceneDestroyObject(i));
vAllSpawnedObjectIDs.removeElementAt(I);
return;
}
}
if (!bFound) {
// System.out.println("Player.despawnItem: object with IFF " +
// i.getIFFFileName() + ", ID " + itemID + " is not spawned!");
// StackTraceElement[] trace =
// Thread.currentThread().getStackTrace();
// for (int j = 0; j < trace.length; j++) {
// System.out.println(trace[j].toString());
// }
}
}
/**
* Spawns an Item.
*
* @param i
* -- The Item to spawn.
* @throws IOException
* If an error occured building the packets.
*/
protected void spawnItem(SOEObject i) throws IOException {
if (vAllSpawnedObjectIDs == null) {
// System.out.println("Player::spawnItem -- vector of IDs is null. Instantiating...");
vAllSpawnedObjectIDs = new Vector<Long>();
}
// If an object is in a cell, and the Player is not in the same building, do not spawn it.
if (i == null) {
return;
}
long lObjectCellID = i.getCellID();
Cell c = null;
Structure s = null;
if (lObjectCellID != 0) {
System.out.println("Spawning object in cell.");
c = (Cell)server.getObjectFromAllObjects(lObjectCellID);
s = c.getBuilding();
System.out.println("Found building: " + s.getStructureName());
if (s.contains(this) || i.equals(this)) {
System.out.println("Player in building -- spawn the item.");
} else {
System.out.println("Player outside, do NOT spawn the item.");
return;
}
}
c = null;
s = null;
boolean sceneEndBaseLinesSent = false;
long itemID = i.getID();
try {
if (i.equals(this)) {
// System.out.println("OUR Player in Spawn Item Detected.");
if (this.isMounted()) {
return;
}
}
if (i.getIsStaticObject() && !(i instanceof Structure)) {
// System.out.println("Attempting to spawn a static item -- client already knows about this item.");
return;
}
// System.out.println("Spawning object with ID " + itemID + " IFF: "
// + i.getIFFFileName() + " , " + i.getClass()+ ".");
// System.out.println("Searching list for if spawned.");
for (int I = 0; I < vAllSpawnedObjectIDs.size(); I++) {
long lCompareID = vAllSpawnedObjectIDs.elementAt(I);
// System.out.println("ID: " + itemID + ", comparator: " +
// lCompareID + ", equal? " + (lCompareID == itemID));
if (lCompareID == itemID) {
// System.out.println("Player.spawnItem: object with IFF " +
// i.getIFFFileName() + " is already spawned!");
// StackTraceElement[] trace =
// Thread.currentThread().getStackTrace();
// for (int j = 0; j < trace.length; j++) {
// System.out.println(trace.toString());
// }
return;
}
}
boolean bShared = false;
if ((i instanceof Player)
&& !((i instanceof Terminal) || (i instanceof NPC))) {
bShared = true;
}
if (i.getID() == this.getCurrentMount() && this.isMounted()) {
// cant touch this while mounted !!!! Hammer Time!!!
// System.out.println("Spawn Vehicle Packet While Mounted.");
sceneEndBaseLinesSent = true;
} else if (i.getIsStaticObject()) {
// do nothing we dont need a crc spawn,
// this means its a building in the world but we do need
// permissions to be sent.
// these are taken care of by the spawn building section in this
// method, look further down.VVV
// System.out.println("Static Object Not Sending SpawnByCRC");
} else {
client.insertPacket(PacketFactory.buildSceneCreateObjectByCRC(
i, bShared));
}
// i.resetTransientVariables();
c = null;
long ltCellID = 0;
if (i instanceof Terminal) {
if (i.getIsStaticObject()) {
return;
}
Terminal t = (Terminal) i;
ltCellID = t.getCellID();
if (ltCellID > 0) {
//System.out.println("Spawning terminal ID " + t.getID() + ", name " + t.getFullName() + " in cell ID " + ltCellID);
c = (Cell) server.getObjectFromAllObjects(ltCellID);
c.addCellObject(t); // Cell is null, so the terminal's cell ID is incorrect.
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(t, c, -1));
s = c.getBuilding();
//System.out.println("Building name: " + s.getStructureName());
} else {
//System.out.println("Spawning terminal ID " + t.getID() + ", name " + t.getFullName() + " in the world.");
}
client.insertPacket(PacketFactory.buildBaselineCREO3(t));
client.insertPacket(PacketFactory.buildBaselineCREO6(t));
//System.out.println("Writing PVP status bitmask " + Integer.toBinaryString(t.getPVPStatus()));
client.insertPacket(PacketFactory.buildUpdatePvPStatusMessage(t));
// client.insertPacket(PacketFactory.buildSceneEndBaselines(t));
client.insertPacket(PacketFactory
.buildObjectControllerDataTransformObjectToClient(t,
0x21));
} else if (i instanceof Vehicle) {
if (i.getIsStaticObject()) {
return;
}
Vehicle v = (Vehicle) i;
if (v.getID() == this.getCurrentMount() && this.isMounted()) {
// System.out.println("Spawn Vehicle Packet While Mounted.");
} else {
client.insertPacket(PacketFactory.buildBaselineCREO1(v));
client.insertPacket(PacketFactory.buildBaselineCREO3(v));
client.insertPacket(PacketFactory.buildBaselineCREO4(v));
client.insertPacket(PacketFactory.buildBaselineCREO6(v));
client
.insertPacket(PacketFactory
.buildSceneEndBaselines(v));
}
} else if (i instanceof NPC) {
if (i.getIsStaticObject()) {
return;
}
NPC n = (NPC) i;
if (n.getCellID() > 0) {
c = (Cell) server.getObjectFromAllObjects(n.getCellID());
c.addCellObject(n);
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(n, c, -1));
}
client.insertPacket(PacketFactory.buildBaselineCREO3(n));
client.insertPacket(PacketFactory.buildBaselineCREO6(n));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(n));
sceneEndBaseLinesSent = true;
client.insertPacket(PacketFactory.buildSceneEndBaselines(n));
client.insertPacket(PacketFactory
.buildObjectControllerDataTransformObjectToClient(n,
0x21));
} else if (i instanceof Player) {
if (i.getIsStaticObject()) {
return;
}
Player n = (Player) i;
if (n.getCellID() > 0) {
c = (Cell) server.getObjectFromAllObjects(n.getCellID());
c.addCellObject(n);
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(n, c, 4));
}
if (n.isMounted()) {
SOEObject m = server.getObjectFromAllObjects(n
.getCurrentMount());
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(n, m, 4));
}
client.insertPacket(PacketFactory.buildBaselineCREO1(n));
client.insertPacket(PacketFactory.buildBaselineCREO3(n));
client.insertPacket(PacketFactory.buildBaselineCREO4(n));
client.insertPacket(PacketFactory.buildBaselineCREO6(n));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(n));
} else if (i instanceof Camp) {
if (i.getIsStaticObject()) {
return;
}
Camp t = (Camp) i;
// some items do not send the equipped state packet. Mission Bag
// is one of them.
if (t.bSendsEquipedState()) {
client.insertPacket(PacketFactory.buildUpdateContainmentMessage(t, t.getContainer(),t.getEquippedStatus()));
}
client.insertPacket(PacketFactory.buildBaselineTANO3(t));
client.insertPacket(PacketFactory.buildBaselineTANO6(t));
client.insertPacket(PacketFactory.buildBaselineTANO8(t));
client.insertPacket(PacketFactory.buildBaselineTANO9(t));
//client.insertPacket(PacketFactory.buildUpdatePvPStatusMessage(t));
client.insertPacket(PacketFactory.buildObjectControllerDataTransformObjectToClient(t,0x21));
// if(t.getAdminTerminal()!=null)
// {
// Terminal aT = t.getAdminTerminal();
// aT.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
// this.addDelayedSpawnObject(aT,(System.currentTimeMillis() +
// (1000 * 10)));
// }
} else if (i instanceof Factory) {
Factory f = (Factory) i;
client.insertPacket(PacketFactory.buildBaselineINSO3(f));
client.insertPacket(PacketFactory.buildBaselineINSO6(f));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(f));
sceneEndBaseLinesSent = true;
client.insertPacket(PacketFactory.buildSceneEndBaselines(f));
spawnItem(f.getInputHopper());
spawnItem(f.getOutputHopper());
} else if (i instanceof Structure) {
s = (Structure) i;
System.out.println("Spawning Structure name: " + s.getStructureName() + " to player " + getFirstName());
System.out.println("Structure ID: " + Long.toHexString(s.getID()));
if (s.getIsStaticObject()) {
// if its a static object building we only send permissions
// for the cells.
// System.out.println("Sending Permissions Message for a Static Structure");
// int cellcnt = s.getCellsInBuilding().size();
// System.out.println("Cell Count " + cellcnt);
Enumeration<Cell> cEnum = s.getCellsInBuilding().elements();
while (cEnum.hasMoreElements()) {
Cell cell = cEnum.nextElement();
if (cell == null) {
// System.out.println("NULL CELL IN STATIC BUILDING!!!!");
DataLog.logEntry("Null Cell In static Building SID:"+ s.getID(), "Player",Constants.LOG_SEVERITY_CRITICAL,ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
} else {
if (client.getClientReadyStatus()) {
if (DatabaseInterface.isRestricted(cell.getID())) {
client.insertPacket(PacketFactory.buildUpdateCellPermissionMessage(cell, s, this));
}
} else {
return;
}
}
}
} else {
// if its a player structure we give it the whole spa
// treatment
if (s.getStructureType() == Constants.STRUCTURE_TYPE_BUILDING) {
client.insertPacket(PacketFactory.buildBaselineBUIO3(s));
client.insertPacket(PacketFactory.buildBaselineBUIO6(s));
int cellcnt = s.getCellsInBuilding().size();
for (int cid = 0; cid < cellcnt; cid++) {
Cell cell = s.getCellByIndex(cid);
if (cell == null) {
DataLog.logEntry(
"Null Cell In Player Building SID:"
+ s.getID(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions
.isBLogToConsole(), true);
// System.out.println("NULL CELL IN BUILDING!!!!");
} else {
spawnItem(cell);
}
// System.out.println("Spawning Cell ID:" +
// cell.getID() + " Parent ID:" +
// cell.getBuildingID()+ " Index:" +
// cell.getCellNum());
/*
client.insertPacket(PacketFactory
.buildSceneCreateObjectByCRC(cell, false));
client
.insertPacket(PacketFactory
.buildUpdateContainmentMessage(
cell, s, -1));
client.insertPacket(PacketFactory
.buildBaselineSCLT3(cell));
client.insertPacket(PacketFactory
.buildBaselineSCLT6(cell));
client.insertPacket(PacketFactory
.buildUpdateCellPermissionMessage(cell, s,
this));
client.insertPacket(PacketFactory
.buildSceneEndBaselines(cell));*/
//System.out.println("Add cell with ID " + cell.getID() + ", parent building name " + cell.getBuilding().getName() + " to list of all objects.");
//server.addObjectToAllObjects(cell, false,
// false);
}
sceneEndBaseLinesSent = true;
client.insertPacket(PacketFactory
.buildSceneEndBaselines(s));
Terminal guildTerminal = s.getGuildTerminal();
TangibleItem structureBase = s.getStructureBase();
Terminal structureSign = s.getStructureSign();
Terminal adminTerminal = s.getAdminTerminal();
Vector<Terminal> vElevatorTerminal = s.getVElevatorTerminals();
spawnItem(structureBase);
spawnItem(guildTerminal);
spawnItem(structureSign);
spawnItem(adminTerminal);
if (!vElevatorTerminal.isEmpty()) {
for (int j = 0; j < vElevatorTerminal.size(); j++) {
spawnItem(vElevatorTerminal.elementAt(j));
}
}
/*
if (s.getGuildTerminal() != null) {
Terminal gT = s.getGuildTerminal();
gT
.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
this.addDelayedSpawnObject(gT, (System
.currentTimeMillis() + (1000 * 10)));
}
if (s.getStructureBase() != null) {
TangibleItem bB = s.getStructureBase();
bB
.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
this.addDelayedSpawnObject(bB, 1000 * 1);
}
if (s.getStructureSign() != null) {
Terminal sT = s.getStructureSign();
sT
.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
this.addDelayedSpawnObject(sT, (System
.currentTimeMillis() + (1000 * 10)));
}
// System.out.println("Sign Spawned, Spawning terminal");
if (s.getAdminTerminal() != null) {
Terminal aT = s.getAdminTerminal();
aT
.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
this.addDelayedSpawnObject(aT, (System
.currentTimeMillis() + (1000 * 10)));
}
if (s.getVElevatorTerminals().size() >= 1) {
Vector<Terminal> vE = s.getVElevatorTerminals();
for (int e = 0; e < vE.size(); e++) {
Terminal eT = vE.get(e);
eT
.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
this.addDelayedSpawnObject(eT, (System
.currentTimeMillis() + (1000 * 10)));
}
}
*/
} else if (s.getStructureType() == Constants.STRUCTURE_TYPE_INSTALLATION) {
client
.insertPacket(PacketFactory
.buildBaselineINSO3(s));
client
.insertPacket(PacketFactory
.buildBaselineINSO6(s));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(s));
sceneEndBaseLinesSent = true;
client.insertPacket(PacketFactory
.buildSceneEndBaselines(s));
} else if (s instanceof Harvester) {
Harvester h = (Harvester) s;
client
.insertPacket(PacketFactory
.buildBaselineHINO3(h));
client
.insertPacket(PacketFactory
.buildBaselineHINO6(h));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(h));
sceneEndBaseLinesSent = true;
client.insertPacket(PacketFactory
.buildSceneEndBaselines(s));
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_HINO, (byte) 3, (short) 1,
(short) 0x06, s, s.getIAnimationBitmask()));
} else if (s.getStructureType() == Constants.STRUCTURE_TYPE_TUTORIAL) {
System.out.println("Spawning Tutorial Building.");
client.insertPacket(PacketFactory.buildBaselineBUIO3(s));
client.insertPacket(PacketFactory.buildBaselineBUIO6(s));
TutorialObject to = (TutorialObject) s;
Enumeration<Cell> vCellsInBuilding = to.getCellsInBuilding().elements();
while (vCellsInBuilding.hasMoreElements()) {
Cell cell = vCellsInBuilding.nextElement();
if (cell == null) {
DataLog.logEntry(
"Null Cell In Tutorial Building SID:"
+ s.getID(), "Player",
Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions
.isBLogToConsole(), true);
// System.out.println("NULL CELL IN BUILDING!!!!");
} else {
System.out.println("Spawn building cell index " + cell.getCellNum());
spawnItem(cell);
}
// System.out.println("Spawning Cell ID:" +
// cell.getID() + " Parent ID:" +
// cell.getBuildingID()+ " Index:" +
// cell.getCellNum());
/*
client.insertPacket(PacketFactory
.buildSceneCreateObjectByCRC(cell, false));
client
.insertPacket(PacketFactory
.buildUpdateContainmentMessage(
cell, s, -1));
client.insertPacket(PacketFactory
.buildBaselineSCLT3(cell));
client.insertPacket(PacketFactory
.buildBaselineSCLT6(cell));
client.insertPacket(PacketFactory
.buildUpdateCellPermissionMessage(cell, s,
this));
client.insertPacket(PacketFactory
.buildSceneEndBaselines(cell));*/
//server.addObjectToAllObjects(cell, false,
//false);
}
sceneEndBaseLinesSent = true;
client.insertPacket(PacketFactory
.buildSceneEndBaselines(s));
//System.out.println("BYPASS spawn tutorial objects.");
to.spawnTutorialObjects(this);
// Terminal tt = to.getTutorialTravelTerminal();
// tt.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_RAW_SPAWN);
// this.addDelayedSpawnObject(tt,
// System.currentTimeMillis() + 1000);
}
client.insertPacket(PacketFactory
.buildObjectControllerDataTransformObjectToClient(
s, 0x21));
}
} else if (i instanceof PlayerItem) {
if (i.getIsStaticObject()) {
return;
}
PlayerItem p = (PlayerItem) i;
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(p, this, 4));
client.insertPacket(PacketFactory.buildBaselinePLAY3(p));
client.insertPacket(PacketFactory.buildBaselinePLAY6(p));
client.insertPacket(PacketFactory.buildBaselinePLAY8(p));
client.insertPacket(PacketFactory.buildBaselinePLAY9(p));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(p));
} else if (i instanceof ResourceContainer) {
if (i.getIsStaticObject()) {
return;
}
ResourceContainer r = (ResourceContainer) i;
// Resources cannot be equipped on a Player... and in fact, it'd
// look rather silly if they were.
// However, they are contained by whatever cell (or inventory)
// they are in.
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(r, r.getContainer(), r
.getEquippedStatus()));
client.insertPacket(PacketFactory.buildBaselineRCNO3(r));
client.insertPacket(PacketFactory.buildBaselineRCNO6(r));
// client.insertPacket(PacketFactory.buildBaselineRCNO8(r));
// client.insertPacket(PacketFactory.buildBaselineRCNO9(r));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(r));
} else if (i instanceof Deed) {
if (i.getIsStaticObject()) {
return;
}
Deed d = (Deed) i; // some items do not send the equipped state
// packet. Mission Bag is one of them.
if (d.bSendsEquipedState()) {
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(d, d.getContainer(),
-1));
}
client.insertPacket(PacketFactory.buildBaselineTANO3(d));
client.insertPacket(PacketFactory.buildBaselineTANO6(d));
client.insertPacket(PacketFactory.buildBaselineTANO8(d));
client.insertPacket(PacketFactory.buildBaselineTANO9(d));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(d));
} else if (i instanceof Instrument) {
if (i.getIsStaticObject()) {
return;
}
TangibleItem t = (TangibleItem) i;
// some items do not send the equipped state packet. Mission Bag
// is one of them.
if (t.bSendsEquipedState()) {
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(t, t.getContainer(),
t.getEquippedStatus()));
}
client.insertPacket(PacketFactory.buildBaselineTANO3(t));
client.insertPacket(PacketFactory.buildBaselineTANO6(t));
client.insertPacket(PacketFactory.buildBaselineTANO8(t));
client.insertPacket(PacketFactory.buildBaselineTANO9(t));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(t));
} else if (i instanceof Weapon) {
if (i.getIsStaticObject()) {
return;
}
Weapon w = (Weapon) i;
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(w, w.getContainer(), w
.getEquippedStatus()));
/*
* if (equippedWeapon != null) { if (w.equals(equippedWeapon)) {
* client
* .insertPacket(PacketFactory.buildUpdateContainmentMessage(w,
* this, 4)); } else {
* client.insertPacket(PacketFactory.buildUpdateContainmentMessage
* (w, tPlayerInventory, -1)); } } else {
* client.insertPacket(PacketFactory
* .buildUpdateContainmentMessage(w, tPlayerInventory, -1)); }
*/
client.insertPacket(PacketFactory.buildBaselineWEAO3(w));
client.insertPacket(PacketFactory.buildBaselineWEAO6(w));
client.insertPacket(PacketFactory.buildBaselineWEAO8(w));
client.insertPacket(PacketFactory.buildBaselineWEAO9(w));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(w));
} else if (i instanceof StaticItem) {
// System.out.println("Spawning Static Item");
if (i.getIsStaticObject()) {
return;
}
StaticItem si = (StaticItem) i;
client.insertPacket(PacketFactory.buildBaselineSTAO3(si));
client.insertPacket(PacketFactory.buildBaselineSTAO6(si));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(si));
client.insertPacket(PacketFactory
.buildObjectControllerDataTransformObjectToClient(si,
0x21));
} else if (i instanceof TangibleItem) {
if (i.getIsStaticObject()) {
return;
}
TangibleItem t = (TangibleItem) i;
// int templateID = t.getTemplateID();
if (t.bSendsEquipedState()) {
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(t, t.getContainer(),
t.getEquippedStatus()));
}
client.insertPacket(PacketFactory.buildBaselineTANO3(t));
client.insertPacket(PacketFactory.buildBaselineTANO6(t));
client.insertPacket(PacketFactory.buildBaselineTANO8(t));
client.insertPacket(PacketFactory.buildBaselineTANO9(t));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(t));
} else if (i instanceof MissionObject) {
if (i.getIsStaticObject()) {
return;
}
MissionObject m = (MissionObject) i;
// System.out.println("Sending Mission Object Baselines " +
// m.getID());
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(m, tMissionBag, -1));
client.insertPacket(PacketFactory.buildBaselineMISO3(m));
client.insertPacket(PacketFactory.buildBaselineMISO6(m));
client.insertPacket(PacketFactory.buildBaselineMISO8(m));
client.insertPacket(PacketFactory.buildBaselineMISO9(m));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(m));
} else if (i instanceof ManufacturingSchematic) {
ManufacturingSchematic schematic = (ManufacturingSchematic) i;
// Works!
client
.insertPacket(PacketFactory
.buildUpdateContainmentMessage(schematic,
schematic.getContainer(), schematic
.getEquippedStatus()));
client.insertPacket(PacketFactory.buildBaselineMSCO3(schematic,
this));
client
.insertPacket(PacketFactory
.buildBaselineMSCO6(schematic));
client
.insertPacket(PacketFactory
.buildBaselineMSCO8(schematic));
client
.insertPacket(PacketFactory
.buildBaselineMSCO9(schematic));
} else if (i instanceof IntangibleObject) {
if (i.getIsStaticObject()) {
return;
}
// We can't carry intangible items.
IntangibleObject o = (IntangibleObject) i;
client.insertPacket(PacketFactory
.buildUpdateContainmentMessage(o, tDatapad, -1));
client.insertPacket(PacketFactory.buildBaselineITNO3(o));
client.insertPacket(PacketFactory.buildBaselineITNO6(o));
client.insertPacket(PacketFactory.buildBaselineITNO8(o));
client.insertPacket(PacketFactory.buildBaselineITNO9(o));
client.insertPacket(PacketFactory
.buildUpdatePvPStatusMessage(o));
} else if (i instanceof Cell) {
if (i.getIsStaticObject()) {
return;
}
Cell cell = (Cell) i;
// System.out.println("Spawning Cell: " + cell.getID() +
// " Index:" + cell.getCellNum());
s = (Structure) cell.getBuilding();
client.insertPacket(PacketFactory.buildUpdateContainmentMessage(cell, s, -1));
client.insertPacket(PacketFactory.buildBaselineSCLT3(cell));
client.insertPacket(PacketFactory.buildBaselineSCLT6(cell));
client.insertPacket(PacketFactory.buildUpdateCellPermissionMessage(cell, s, this));
} else if (i instanceof Group) {
if (i.getIsStaticObject()) {
return;
}
// System.out.println("Spawning a Group Object to: " +
// this.getFullName());
Group g = (Group) i;
client.insertPacket(PacketFactory.buildBaselineGRUP3(g));
client.insertPacket(PacketFactory.buildBaselineGRUP6(g, this));
}
} catch (Exception e) {
System.out.println("Error spawning item with ID " + i.getID() + ": " + e.toString());
e.printStackTrace();
}
if (!sceneEndBaseLinesSent) {
if (i.getIsStaticObject()) {
return;
}
client.insertPacket(PacketFactory.buildSceneEndBaselines(i));
}
vAllSpawnedObjectIDs.add(itemID);
}
/**
* Sets the Player's biography data.
*
* @param bio
* -- The new Biography data.
*/
protected void setBiography(String bio) {
sBiography = bio;
}
/**
* Gets the Players biography data.
*
* @return The biography.
*/
protected String getBiography() {
return sBiography;
}
/**
* Sets the Player's First Name.
*
* @param name
* -- The new First Name.
*/
protected void setFirstName(String name) {
sFirstName = name;
}
/**
* Sets the Player's Last Name.
*
* @param name
* -- The new Last Name.
*/
protected void setLastName(String name) {
sLastName = name;
}
/**
* Sets the Player's Race ID.
*
* @param i
* -- The Race ID.
*/
protected void setRace(int i) {
iRaceID = i;
}
/**
* Add a single item to this Player's Inventory.
*
* @param t
* -- The item to add to Inventory.
*/
protected void addItemToInventory(TangibleItem t) {
vInventoryItemsList.add(t);
// tPlayerInventory.addLinkedObject(t);
}
protected void removeItemFromInventory(TangibleItem t) {
vInventoryItemsList.remove(t);
// tPlayerInventory.removeLinkedObject(t);
}
/**
* Adds a list of items to this Player's Inventory.
*
* @param v
* -- THe items to add to Inventory.
*/
protected void addInventoryItem(Vector<TangibleItem> v) {
vInventoryItemsList.addAll(v);
}
/**
* Gets a list of all items currently equipped by the Player.
*
* @return The list of equipped items.
*/
protected Vector<TangibleItem> getEquippedItems() {
Vector<TangibleItem> toReturn = new Vector<TangibleItem>();
for (int i = 0; i < vInventoryItemsList.size(); i++) {
TangibleItem t = vInventoryItemsList.elementAt(i);
if (t.getContainerID() == getID()) {
toReturn.add(t);
}
}
toReturn.add(tHairObject);
return toReturn;
}
/**
* Sets the Player's scale.
*
* @param f
* -- The new scale.
* @param bUpdateZone
* -- Indicates if a DeltasMessage is to be returned or not.
* @return -- The DeltasMessage, or null if bUpdateZone is false.
* @throws IOException if an error occured building the packet
* @throws IndexOutOfBoundsException if the scale is outside the range.
*/
protected byte[] setScale(float f, boolean bUpdateZone, boolean bOverride) throws IOException, IndexOutOfBoundsException {
if (Constants.getIsValidScale(this, f) || bOverride) {
float oldScale = fScale;
fScale = f;
if (fScale != oldScale) {
if (bUpdateZone) {
return PacketFactory.buildDeltasMessage(Constants.BASELINES_CREO, (byte)3, (short)1, (short)14, this, fScale);
} else {
return null;
}
}
return null;
} else {
throw new IndexOutOfBoundsException("Error: Invalid scale factor " + f + " for species " + Constants.SpeciesNames[getRaceID()]);
}
}
protected void setIsAFK(boolean status) {
if (status) {
thePlayer.addBitToStatusBitmask(Constants.PLAYER_STATUS_AFK);
} else {
thePlayer.removeBitFromStatusBitmask(Constants.PLAYER_STATUS_AFK);
}
}
protected boolean getIsAFK() {
return ((thePlayer.getStatusBitmask() & Constants.PLAYER_STATUS_AFK) != 0);
}
/**
* Set the total number of Lots this Player has.
*
* @param i
* -- The number of lots.
*/
protected void setTotalLots(int i) {
iTotalLots = i;
}
/**
* Gets the total number of Lots this Player has.
*
* @return -- The number of lots
*/
protected int getTotalLots() {
return iTotalLots;
}
/**
* Gets the number of empty Lots this Player has.
*
* @return -- The number of free lots.
*/
protected int getFreeLots() {
if (vPlayerStructures == null) {
vPlayerStructures = new ConcurrentHashMap<Long, Structure>();
}
iUsedLots = 0;
Enumeration<Structure> sEnum = vPlayerStructures.elements();
while (sEnum.hasMoreElements()) {
Structure s = sEnum.nextElement();
iUsedLots += s.getLotsize();
}
return iTotalLots - iUsedLots;
}
/**
* Sets the HAM wounds array for this Player.
*
* @param i
* -- the new Ham Wounds.
*/
protected void setHamWounds(int[] i) {
iHamWounds = i;
}
/**
* Sets the current credits in the Player's Inventory.
*
* @param iCredits
* -- The new credits value in the Player's Inventory.
*/
protected void setInventoryCredits(int iCredits) {
iInventoryCredits = iCredits;
}
/**
* Sets the current credits in the Player's Bank.
*
* @param iCredits
* -- The new credits value in the Player's Bank.
*/
protected void setBankCredits(int iCredits) {
iBankCredits = iCredits;
}
/**
* Attaches a TangibleItem as a Hair object to this Player.
*
* @param hair
* -- The Hair.
*/
protected void addHair(TangibleItem hair) {
tHairObject = hair;
// addTangibleItem(hair);
}
/**
* Returns the Player's Hair object.
*
* @return The hair object.
*/
protected TangibleItem getHair() {
return tHairObject;
}
/**
* Sets the Player's original starting profession, by name.
*
* @param s
* -- The starting profession.
*/
protected void setStartingProfession(String s) {
sStartingProfession = s;
}
/**
* Returns the name of the Player's original starting profession.
*
* @return The starting profession.
*/
protected String getStartingProfession() {
return sStartingProfession;
}
/**
* Gets a Waypoint by ID.
*
* @param ID
* -- The Object ID of the Waypoint.
* @return The Waypoint associated with the given ID, or null if no such
* waypoint exists.
*/
protected Waypoint getWaypoint(long ID) {
return thePlayer.getWaypoint(ID);
}
/**
* Gets all of the Player's waypoints.
*
* @return The list of waypoints.
*/
protected Vector<Waypoint> getWaypoints() {
return thePlayer.getWaypoints();
}
/**
* Increments and then gets the update counter for the Player's skill
* modifications list.
*
* @return
*/
public int getSkillModsUpdateCounter(boolean bIncrement) {
if (bIncrement) {
iSkillModsUpdateCount++;
}
return iSkillModsUpdateCount;
}
public void setSkillModsUpdateCounter(int counter) {
iSkillModsUpdateCount = counter;
}
/**
* Sets the Player's Friends list.
*
* @param vFriendsList
* -- The friends list.
*/
public void setFriendsList(Vector<PlayerFriends> vFriendsList) {
thePlayer.setFriendsList(vFriendsList);
}
/**
* Returns the PlayerItem associated with this Player. The PlayerItem
* contains information on Waypoint data, Experience, Skills, Skill Mods,
* Quests, Jedi settings, etc.
*
* @return -- The PlayerItem.
*/
protected PlayerItem getPlayData() {
return thePlayer;
}
/**
* Sets the PlayerItem associated with this Player. The PlayerItem contains
* information on Waypoint data, Experience, Skills, Skill Mods, Quests,
* Jedi settings, etc.
*
* @param p
* -- The new PlayerItem.
*/
protected void setPlayData(PlayerItem p) {
thePlayer = p;
}
/**
* Sets the Inventory Container for this Player.
*
* @param t
* -- The Inventory.
*/
protected void setInventoryItem(TangibleItem t) {
tPlayerInventory = t;
}
/**
* Gets the Inventory Container for this Player.
*
* @return The Inventory.
*/
protected TangibleItem getInventory() {
return tPlayerInventory;
}
/**
* Sets the Datapad item for this Player.
*
* @param t
* -- The Datapad.
*/
protected void setDatapad(TangibleItem t) {
tDatapad = t;
}
/**
* Gets the Datapad item for this Player.
*
* @return The Datapad.
*/
protected TangibleItem getDatapad() {
return tDatapad;
}
/**
* Sets the Bank item for this Player.
*
* @param t
* -- The Bank.
*/
protected void setBank(TangibleItem t) {
tBank = t;
}
/**
* Gets the Bank item for this Player.
*
* @return The Bank.
*/
protected TangibleItem getBank() {
return tBank;
}
/**
* Sets the Mission Container for this Player.
*
* @param t
* -- The Mission Container.
*/
protected void setMissionBag(TangibleItem t) {
tMissionBag = t;
}
/**
* Gets the Mission Container for this Player.
*
* @return -- The Mission Container.
*/
protected TangibleItem getMissionBag() {
return tMissionBag;
}
protected void resetCreo1UpdateVars() {
}
protected void resetCreo3UpdateVars() {
}
protected void resetCreo4UpdateVars() {
}
protected void resetCreo6UpdateVars() {
}
protected void resetPlay3UpdateVars() {
}
protected void resetPlay6UpdateVars() {
}
protected void resetPlay8UpdateVars() {
}
protected void resetPlay9UpdateVars() {
}
protected void useItem(ZoneClient client) {
try {
// client.insertPacket(PacketFactory.buildChatSystemMessage("You can't use another player!"));
} catch (Exception e) {
System.out.println("Error building packet: " + e.toString());
e.printStackTrace();
}
}
protected float[] getStartingCoordinates() {
return fStartingCoordinates;
}
protected void setStartingCoordinates(float x, float y) {
fStartingCoordinates[0] = x;
fStartingCoordinates[2] = y;
}
protected float[] getHouseCoordinates() {
return fHouseCoordinates;
}
protected void setHouseCoordinates(float x, float z, float y) {
fHouseCoordinates[0] = x;
fHouseCoordinates[1] = z;
fHouseCoordinates[2] = y;
}
protected float[] getBankCoordinates() {
return fBankCoordinates;
}
protected void setBankCoordinates(float x, float y) {
fBankCoordinates[0] = x;
fBankCoordinates[2] = y;
}
protected void setBankPlanetID(int i) {
if (i >= 0 && i < Constants.PlanetNames.length) {
iBankPlanetID = i;
} else {
iBankPlanetID = -1;
}
}
protected int getBankPlanetID() {
return iBankPlanetID;
}
protected void setHousePlanetID(int i) {
if (i >= 0 && i < Constants.PlanetNames.length) {
iHomePlanetID = i;
} else {
iHomePlanetID = -1;
}
}
protected int getHousePlanetID() {
return iHomePlanetID;
}
protected void setHamMigrationTarget(int index, int value) {
iHamMigrationTarget[index] = value;
}
protected int[] getHamMigrationTargets() {
return iHamMigrationTarget;
}
protected void setHamMigrationPointsAvailable(int iPoints) {
iHamMigrationPoints = iPoints;
}
protected int getHamMigrationPointsAvailable() {
return iHamMigrationPoints;
}
protected void setRebelFactionPoints(int iFaction) {
iRebelFactionPoints = iFaction;
}
protected int getRebelFactionPoints() {
return iRebelFactionPoints;
}
protected void setImperialFactionPoints(int iFaction) {
iImperialFactionPoints = iFaction;
}
protected int getImperialFactionPoints() {
return iImperialFactionPoints;
}
protected void addFactionToFactionList(String sFaction) {
vFactionList.add(new PlayerFactions(sFaction, 0));
}
protected void addFactionToFactionList(String sFaction, float newValue) {
vFactionList.add(new PlayerFactions(sFaction, newValue));
}
protected void updateFaction(String sFactionName, float newValue) {
for (int i = 0; i < vFactionList.size(); i++) {
PlayerFactions faction = vFactionList.elementAt(i);
if (faction.getFactionName().equals(sFactionName)) {
faction.setFactionValue(newValue);
return;
}
}
addFactionToFactionList(sFactionName, newValue);
}
protected Vector<PlayerFactions> getFactionList() {
return vFactionList;
}
protected byte[] clearAllStates(boolean bUpdateZone) {
lState = 0;
if (bUpdateZone) {
try {
return (PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 3, (short) 1,
(short) 0x10, this, lState));
} catch (Exception e) {
// D'oh!
return null;
}
} else {
return null;
}
}
protected void setCREO3Bitmask(int value) {
iUnknownCREO3Bitmask = value;
}
protected int getCREO3Bitmask() {
return iUnknownCREO3Bitmask;
}
/**
* Sets the last used travel terminal.
*
* @param t
* - Terminal
*/
protected void setLastUsedTravelTerminal(Terminal t) {
LastUsedTravelTerminal = t;
}
/**
* Returns the last used travel terminal.
*
* @return Terminal
*/
protected Terminal getLastUsedTravelTerminal() {
return LastUsedTravelTerminal;
}
/**
* Returns all cash on hand by player a sum of Inventory + Bank
*
* @return int
*/
protected int getCashOnHand() {
int retval = iInventoryCredits + iBankCredits;
// System.out.println("Inventory: " + iInventoryCredits);
// System.out.println("Bank: " + iBankCredits);
// System.out.println("CashOnHand: " + retval);
return retval;
}
/**
* debitCredits() Debits the amount of credits from player. Will try to
* debit from bank first. Returns True if success. If not enough in bank it
* will try inventory. Returns True if success. If inventory is not enough
* it will add bank + inventory. Returns True if success. If Still not
* enough it will return false.
*
* @param amount
* int
* @return boolean - true = success false = failure not enough cash.
*/
protected boolean debitCredits(int amount) {
int TotalCredits = iInventoryCredits + iBankCredits;
boolean retval = false;
if (iBankCredits >= amount) {
iBankCredits = iBankCredits - amount;
retval = true;
} else if (iInventoryCredits >= amount) {
iInventoryCredits = iInventoryCredits - amount;
retval = true;
} else if (TotalCredits >= amount) {
TotalCredits = TotalCredits - amount;
iBankCredits = 0;
iInventoryCredits = TotalCredits;
retval = true;
}
if (retval) {
// update client on credits left.
updateCredits();
}
return retval;
}
protected boolean debitInventoryCredits(int amount) {
boolean retval = false;
if (iInventoryCredits >= amount) {
iInventoryCredits -= amount;
retval = true;
updateCredits();
}
return retval;
}
protected boolean debitBankCredits(int ammount) {
boolean retval = false;
if (iInventoryCredits >= ammount) {
iInventoryCredits -= ammount;
retval = true;
updateCredits();
}
return retval;
}
/**
* Add indicated amount to bank
*
* @param amount
* int
*/
protected void creditBankCredits(int amount) {
iBankCredits = iBankCredits + amount;
updateCredits();
}
/**
* Add indicated amount to inventory
*
* @param amount
* int
*/
protected void creditInventoryCredits(int amount) {
iInventoryCredits = iInventoryCredits + amount;
updateCredits();
}
protected void updateCredits() {
try {
if (this.getOnlineStatus()) {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 1, (short) 1,
(short) 0, this, iBankCredits));
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 1, (short) 1,
(short) 1, this, iInventoryCredits));
}
} catch (Exception e) {
DataLog.logEntry("Eception Caught in Player.updateCredits() " + e,
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Eception Caught in Player.updateCredits() " +
// e);
e.printStackTrace();
}
}
public int getLastSUIBox() {
// System.out.println("Returning Last SUI Box Value: " +
// this.LastSUIBox);
incrementLastSUIBox();
return this.LastSUIBox;
}
public int getCurrentSUIBoxID() {
return LastSUIBox;
}
private void incrementLastSUIBox() {
// System.out.println("LastSUIBox Incrementing Value Before: " +
// this.LastSUIBox);
if (this.LastSUIBox == -1) {
this.LastSUIBox = 0;
}
this.LastSUIBox = this.LastSUIBox + 1;
// System.out.println("LastSUIBox Incrementing Value After: " +
// this.LastSUIBox);
}
protected void clearSpawnedItems() {
if (vAllSpawnedObjectIDs != null) {
vAllSpawnedObjectIDs.removeAllElements();
}
}
protected void setLastSuiWindowTypeString(String Type) {
sLastSuiWindowType = Type;
}
protected String getLastSuiWindowTypeString() {
return sLastSuiWindowType;
}
protected void setLastSuiWindowTypeInt(int t) {
iLastSuiWindowType = t;
}
protected int getLastSuiWindowTypeInt() {
return iLastSuiWindowType;
}
/**
* Adds one object that can be selected when using an SUI Window with a list
* of objects to select from.
*
* @param i
* @param o
*/
protected void addSUIListWindowObjectList(int i, SOEObject o) {
if (SUIListWindowObjectList != null) {
SUIListWindowObjectList.put(i, o);
} else {
SUIListWindowObjectList = new Hashtable<Integer, SOEObject>();
SUIListWindowObjectList.put(i, o);
}
}
/**
* clears the sui list window selection contents and variables
*/
protected void clearSUIListWindowObjectList() {
if (SUIListWindowObjectList != null) {
SUIListWindowObjectList.clear();
}
this.iLastSuiWindowType = -1;
this.sLastSuiWindowType = "";
}
/**
* Returns one item from the sui list window objects list.
*
* @param item
* @return
*/
protected SOEObject getSUIListWindowObjectListItem(int item) {
return SUIListWindowObjectList.get(item);
}
protected void playerTravel(float x, float y, float z, int planetID) {
// here is where we make the player travel and delete the ticket from
// the players inventory.
// We will ALWAYS be exiting a cell when this occurs.
setCellID(0);
try {
// TravelDestination ArrivalDestination = T.getArrivalInformation();
int oldPlanetID = getPlanetID();
int newPlanetID = planetID;
if (oldPlanetID == newPlanetID) {
float newX = x;
float newY = y;
this.setZ(z);
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
} else {
// for now travel is only to the current server.
// if travel is to be between planets we need to save the
// player, serialize it and send it to the new
// planet server for processing and spawn the player there.
float newX = (x);
float newY = (y);
this.setZ(z);
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
}
} catch (Exception e) {
DataLog.logEntry("Eception Caught in playerTravel " + e, "Player",
Constants.LOG_SEVERITY_CRITICAL, ZoneServer.ZoneRunOptions
.isBLogToConsole(), true);
// System.out.println("Eception Caught in playerTravel " + e);
e.printStackTrace();
}
}
protected void playerTravel(TravelTicket T) {
// here is where we make the player travel and delete the ticket from
// the players inventory.
try {
// We will always travel to the out of doors. No matter what.
setCellID(0);
TravelDestination ArrivalDestination = T.getArrivalInformation();
int oldPlanetID = getPlanetID();
int newPlanetID = ArrivalDestination.getDestinationPlanet();
if (this.getPlanetID() == ArrivalDestination.getDestinationPlanet()) {
this.despawnItem(T);
this.getInventoryItems().remove(T);
// this.setPlanetID(ArrivalDestination.getDestinationPlanet());
// -- Done by the moveObjectInTree function call.
float newX = (ArrivalDestination.getX());
float newY = (ArrivalDestination.getY());
this.setZ(ArrivalDestination.getZ());
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
} else {
// for now travel is only to the current server.
// if travel is to be between planets we need to save the
// player, serialize it and send it to the new
// planet server for processing and spawn the player there.
this.despawnItem(T);
this.getInventoryItems().remove(T);
// this.setPlanetID(ArrivalDestination.getDestinationPlanet());
// // Done by the move object in tree function call.
float newX = (ArrivalDestination.getX());
float newY = (ArrivalDestination.getY());
this.setZ(ArrivalDestination.getZ());
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
}
} catch (Exception e) {
DataLog.logEntry("Eception Caught in playerTravel " + e, "Player",
Constants.LOG_SEVERITY_CRITICAL, ZoneServer.ZoneRunOptions
.isBLogToConsole(), true);
// System.out.println("Eception Caught in playerTravel " + e);
e.printStackTrace();
}
}
protected void playerTravel(TravelDestination T) {
try {
int oldPlanetID = getPlanetID();
int newPlanetID = T.getDestinationPlanet();
if (this.getPlanetID() == T.getDestinationPlanet()) {
// this.setPlanetID(ArrivalDestination.getDestinationPlanet());
// -- Done by the moveObjectInTree function call.
float newX = (T.getX());
float newY = (T.getY());
this.setZ(T.getZ());
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
} else {
/**
* @todo for now travel is only to the current server. if travel
* is to be between planets we need to save the player,
* serialize it and send it to the new planet server for
* processing and spawn the player there.
* */
float newX = (T.getX());
float newY = (T.getY());
this.setZ(T.getZ());
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
}
} catch (Exception e) {
DataLog.logEntry("Eception Caught in playerTravel " + e, "Player",
Constants.LOG_SEVERITY_CRITICAL, ZoneServer.ZoneRunOptions
.isBLogToConsole(), true);
// System.out.println("Eception Caught in playerTravel " + e);
e.printStackTrace();
}
}
protected void playerTravelToCell(TravelDestination T) {
try {
int oldPlanetID = getPlanetID();
int newPlanetID = T.getDestinationPlanet();
if (this.getPlanetID() == T.getDestinationPlanet()) {
this.setPlanetID(T.getDestinationPlanet());
float newX = T.getX();
float newY = T.getY();
this.setZ(T.getZ());
this.setCellID(T.getCellID());
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
} else {
// for now travel is only to the current planet.
// if travel is to be between planets we need to save the
// player, serialize it and send it to the new
// planet server for processing and spawn the player there.
this.setPlanetID(T.getDestinationPlanet());
float newX = T.getX();
float newY = T.getY();
this.setZ(T.getZ());
server.moveObjectInTree(this, newX, newY,
oldPlanetID, newPlanetID);
this.setCellID(T.getCellID());
this.clearSpawnedItems();
bIsTraveling = true;
this.spawnPlayer();
}
} catch (Exception e) {
DataLog.logEntry("Eception Caught in playerTravel " + e, "Player",
Constants.LOG_SEVERITY_CRITICAL, ZoneServer.ZoneRunOptions
.isBLogToConsole(), true);
// System.out.println("Eception Caught in playerTravel " + e);
e.printStackTrace();
}
}
protected void playerWarp(float x, float y, float z, long cellid,
int planetid) {
// here is where we make the player warp
// this.isWarping = true;
try {
Vector<Player> vPL = server.getPlayersAroundObject(this, false);
for (int i = 0; i < vPL.size(); i++) {
Player p = vPL.get(i);
p.despawnItem(this);
}
if (this.getPlanetID() == planetid) {
this.setPlanetID(planetid);
this.setX(x);
this.setY(y);
this.setZ(z);
this.setCellID(cellid);
this.clearSpawnedItems();
// bIsTraveling = true;
// this.spawnPlayer();
// spawnItem(this);
if (cellid == 0) {
this
.getClient()
.insertPacket(
PacketFactory
.buildObjectControllerPlayerDataTransformToClient(
this, 0x0B));
} else {
this
.getClient()
.insertPacket(
PacketFactory
.buildObjectControllerPlayerDataTransformWithParentToClient(
this, 0x0B));
}
} else {
// for now travel is only to the current planet.
// if travel is to be between planets we need to save the
// player, serialize it and send it to the new
// planet server for processing and spawn the player there.
this.setPlanetID(planetid);
this.setX(x);
this.setY(y);
this.setZ(z);
this.setCellID(cellid);
this.clearSpawnedItems();
// bIsTraveling = true;
// this.spawnPlayer();
// 'spawnItem(this);
if (cellid == 0) {
this
.getClient()
.insertPacket(
PacketFactory
.buildObjectControllerPlayerDataTransformToClient(
this, 0x0B));
} else {
this
.getClient()
.insertPacket(
PacketFactory
.buildObjectControllerPlayerDataTransformWithParentToClient(
this, 0x0B));
}
}
// this.isWarping = false;
} catch (Exception e) {
DataLog.logEntry("Eception Caught in playerWarp " + e, "Player",
Constants.LOG_SEVERITY_CRITICAL, ZoneServer.ZoneRunOptions
.isBLogToConsole(), true);
// System.out.println("Eception Caught in playerWarp " + e);
e.printStackTrace();
}
}
protected boolean IsPlayerTraveling() {
return bIsTraveling;
}
protected void setPlayerIsNotTraveling() {
bIsTraveling = false;
}
protected void addPendingSUIWindow(SUIWindow W) {
// System.out.println("Add pending SUI window, ID " + W.getWindowID());
if (PendingSUIWindowList == null) {
PendingSUIWindowList = new ConcurrentHashMap<Integer, SUIWindow>();
}
if (W != null) {
// System.out.println("Adding SUIWindow ID" + W.getWindowID());
PendingSUIWindowList.putIfAbsent(W.getWindowID(), W);
}
}
protected void removePendingSUIWindow(SUIWindow W) {
PendingSUIWindowList.remove(W.getWindowID());
}
protected void removePendingSUIWindow(int W) {
try {
PendingSUIWindowList.remove(W);
} catch (Exception e) {
// who cares.
}
}
protected SUIWindow getPendingSUIWindow(int W) {
return PendingSUIWindowList.get(W);
}
protected void setLastConversationNPC(long NPCId) {
lLastConversationNPC = NPCId;
}
protected long getLastConversationNPC() {
return lLastConversationNPC;
}
protected void clearLastConversationMenu() {
sLastConversationMenu = null;
}
protected void setLastConversationMenu(String[] M) {
if (sLastConversationMenu == null) {
sLastConversationMenu = new String[7];
}
sLastConversationMenu[0] = M[0];
sLastConversationMenu[1] = M[1];
sLastConversationMenu[2] = M[2];
sLastConversationMenu[3] = M[3];
sLastConversationMenu[4] = M[4];
sLastConversationMenu[5] = M[5];
sLastConversationMenu[6] = M[6];
}
protected String[] getLastConversationMenu() {
return sLastConversationMenu;
}
protected void clearLastConversationMenuOptions() {
vLastConversationMenuOptions.clear();
}
protected void setLastConversationMenuOptions(Vector<DialogOption> L) {
if (vLastConversationMenuOptions == null) {
vLastConversationMenuOptions = new Vector<DialogOption>();
}
vLastConversationMenuOptions.clear();
vLastConversationMenuOptions = L;
}
protected Vector<DialogOption> getLastConversationMenuOptions() {
return vLastConversationMenuOptions;
}
protected void setSkillBeingPurchased(int index) {
iSkillBeingPurchasedIndex = index;
}
protected int getSkillBeingPurchased() {
return iSkillBeingPurchasedIndex;
}
protected void playerBurstRun(CommandQueueItem action) {
if (!bBurstRunning && lBurstRunRechargeTimer <= 0 && !this.isMounted()
&& this.getStance() == Constants.STANCE_STANDING) {
lBurstRunexpiryTimer = (1000 * 60);
lBurstRunRechargeTimer = (1000 * 60 * 6);
bBurstRunning = true;
short[] updateOperand = new short[2];
float[] newValue = new float[2];
short updateCount = 2;
updateOperand[0] = 7;
updateOperand[1] = 11;
newValue[0] = (float) (5.375 * 2.5);
newValue[1] = ((float) 3.5);
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 0x04, updateCount,
updateOperand, this, newValue));
client.insertPacket(PacketFactory.buildChatSystemMessage(
"cbt_spam", "burstrun_start_single", 0l, "", "", "",
0l, "", "", "", 0l, "", "", "", 0, 0f, false));
} catch (Exception e) {
DataLog.logEntry("Exception while trying to Burst Run " + e,
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exception while trying to Burst Run " +
// e);
e.printStackTrace();
}
} else if (lBurstRunexpiryTimer > 0) {
action
.setErrorMessageID(Constants.COMMAND_QUEUE_ERROR_TYPE_CANNOT_EXECUTE_WITH_STATE);
action
.setStateInvoked(Constants.COMMAND_QUEUE_ERROR_STANCE_RUNNING); // Why
// not...
} else if (lBurstRunRechargeTimer > 0) {
try {
long b = lBurstRunRechargeTimer;
if (lBurstRunRechargeTimer >= (1000 * 60 * 6)) {
lBurstRunRechargeTimer = 0;
playerBurstRun(action);
return;
}
b /= 1000;
b /= 60;
if (b >= 2) {
client
.insertPacket(PacketFactory
.buildChatSystemMessage("You cannot burst run again for "
+ b + " Minutes"));
} else if (b >= 1) {
client
.insertPacket(PacketFactory
.buildChatSystemMessage("You cannot burst run again for "
+ b + " Minute"));
} else {
client
.insertPacket(PacketFactory
.buildChatSystemMessage("You cannot burst run again for "
+ b + " Seconds"));
}
} catch (Exception e) {
DataLog.logEntry("Exception while trying to Burst Run " + e,
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exception while trying to Burst Run " +
// e);
e.printStackTrace();
}
} else if (isMounted()) {
action
.setErrorMessageID(Constants.COMMAND_QUEUE_ERROR_TYPE_CANNOT_EXECUTE_IN_STANCE);
action
.setStateInvoked(Constants.COMMAND_QUEUE_ERROR_STANCE_MOUNTED_VEHICLE);
} else if (this.getStance() != Constants.STANCE_STANDING) {
action
.setErrorMessageID(Constants.COMMAND_QUEUE_ERROR_TYPE_CANNOT_EXECUTE_IN_STANCE);
action.setStateInvoked(getCommandQueueErrorStance());
}
}
protected void playerUnBurstRun() {
if (bBurstRunning) {
bBurstRunning = false;
short[] updateOperand = new short[2];
float[] newValue = new float[2];
short updateCount = 2;
updateOperand[0] = 7;
updateOperand[1] = 11;
newValue[0] = (float) (5.375);
newValue[1] = ((float) 2.5);
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 0x04, updateCount,
updateOperand, this, newValue));
client.insertPacket(PacketFactory.buildChatSystemMessage(
"cbt_spam", "burstrun_stop_single", 0l, "", "", "", 0l,
"", "", "", 0l, "", "", "", 0, 0f, false));
client.insertPacket(PacketFactory
.buildChatSystemMessage("You are tired"));
} catch (Exception e) {
DataLog.logEntry("Exception while trying to Burst Run " + e,
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exception while trying to Burst Run " +
// e);
e.printStackTrace();
}
}
}
protected void setLastUsedSurveyTool(TangibleItem t) {
lastUsedSurveyTool = t;
}
protected TangibleItem getLastUsedSurveyTool() {
return lastUsedSurveyTool;
}
protected void updateExperience(Skills skill, int iExperienceType,
int iExperienceGained) {
if (iExperienceGained != 0) {
thePlayer.updateExperience(skill, iExperienceType,
iExperienceGained);
}
}
protected void resetTimedEvents() {
/*
* for (int i = 0; i < vInventoryItemsList.size(); i++) { TangibleItem
* item = vInventoryItemsList.elementAt(i); item.stopSurveying(); }
*/
if (lastUsedSurveyTool != null) {
lastUsedSurveyTool.stopSurveying();
bIsSampling = false;
}
}
protected boolean addPlayerStructure(Structure s) {
if (vPlayerStructures == null) {
vPlayerStructures = new ConcurrentHashMap<Long, Structure>();
}
if (!vPlayerStructures.containsKey(s.getID())) {
vPlayerStructures.put(s.getID(), s);
}
return vPlayerStructures.containsKey(s.getID());
}
protected void removePlayerStructure(Structure s) {
if (vPlayerStructures == null) {
vPlayerStructures = new ConcurrentHashMap<Long, Structure>();
}
if (vPlayerStructures.containsKey(s.getID())) {
vPlayerStructures.remove(s.getID());
}
}
protected ConcurrentHashMap<Long, Structure> getAllPlayerStructures() {
if (vPlayerStructures == null) {
vPlayerStructures = new ConcurrentHashMap<Long, Structure>();
}
return vPlayerStructures;
}
public long getLCurrentDeedInPlacementMode() {
return lCurrentDeedInPlacementMode;
}
public void setLCurrentDeedInPlacementMode(long lCurrentDeedInPlacementMode) {
this.lCurrentDeedInPlacementMode = lCurrentDeedInPlacementMode;
}
protected void addDelayedSpawnObject(SOEObject o, long lDelayTime) {
if (vDelayedSpawnObjects == null) {
vDelayedSpawnObjects = new Vector<SOEObject>();
}
vDelayedSpawnObjects.add(o);
if (lNextDelayedSpawn == null) {
lNextDelayedSpawn = new Vector<Long>();
}
lNextDelayedSpawn.add(lDelayTime);
}
protected SOEObject getNextDelayedSpawnObject() {
if (vDelayedSpawnObjects == null) {
vDelayedSpawnObjects = new Vector<SOEObject>();
}
return vDelayedSpawnObjects.get(0);
}
protected long getNextDelayTime(int item) {
if (lNextDelayedSpawn == null) {
lNextDelayedSpawn = new Vector<Long>();
}
return lNextDelayedSpawn.get(item);
}
protected int getDelayListCount() {
if (lNextDelayedSpawn == null) {
lNextDelayedSpawn = new Vector<Long>();
}
return lNextDelayedSpawn.size();
}
protected void removeDelayedSpawn(SOEObject o, long lDelayTime) {
if (lNextDelayedSpawn.contains(lDelayTime)) {
lNextDelayedSpawn.remove(lDelayTime);
}
if (vDelayedSpawnObjects.contains(o)) {
vDelayedSpawnObjects.remove(o);
}
}
protected BitSet getSkillList() {
return thePlayer.getSkillBits();
}
protected void removeSpawnedObject(SOEObject o) {
if (vAllSpawnedObjectIDs.contains(o)) {
vAllSpawnedObjectIDs.remove(o);
}
}
public boolean isDeleted() {
return bIsDeleted;
}
public void setIsDeleted(boolean bIsDeleted) {
this.bIsDeleted = bIsDeleted;
}
protected void playerLogout(CommandQueueItem action) {
if ((getStateBitmask() & Constants.STATE_COMBAT) != 0) {
action
.setErrorMessageID(Constants.COMMAND_QUEUE_ERROR_TYPE_CANNOT_EXECUTE_WITH_STATE);
action.setStateInvoked(Constants.STATE_COMBAT);
return;
}
try {
this.lLogoutTimer = 1000 * 30;
this.bPlayerRequestedLogout = true;
this.lLogoutSpamTimer = 1000 * 5;
client.insertPacket(PacketFactory.buildChatSystemMessage("logout",
"time_left", 0l, "", "", "", 0l, "", "", "", 0l, "", "",
"", (int) (lLogoutTimer / 1000), 0f, false));
} catch (Exception e) {
DataLog.logEntry("Exception caught in player.playerlogout " + e,
"Player", Constants.LOG_SEVERITY_CRITICAL,
ZoneServer.ZoneRunOptions.isBLogToConsole(), true);
// System.out.println("Exception caught in Player.playerLogout " +
// e);
e.printStackTrace();
}
}
protected void resetPlayerLogout() {
this.bPlayerRequestedLogout = false;
}
protected int getTradeRequestCounter() {
return iTradeRequestCounter;
}
protected void setTradeRequestCounter(int iTradeRequestCounter) {
this.iTradeRequestCounter = iTradeRequestCounter;
}
protected boolean addTradeRequest(TradeObject t) {
if (vTradeRequests == null) {
vTradeRequests = new Vector<TradeObject>();
}
return vTradeRequests.add(t);
}
// vTradeRequests;
protected boolean removeTradeRequest(TradeObject t) {
if (vTradeRequests == null) {
vTradeRequests = new Vector<TradeObject>();
}
return vTradeRequests.remove(t);
}
protected TradeObject getTradeObjectByRequestID(int iRequest) {
TradeObject retval = null;
for (int i = 0; i < vTradeRequests.size(); i++) {
TradeObject t = vTradeRequests.get(i);
if (t.getITradeRequestID() == iRequest) {
return t;
}
}
return retval;
}
protected TradeObject getTradeObjectByRecipientID(long lRecipient) {
TradeObject retval = null;
for (int i = 0; i < vTradeRequests.size(); i++) {
TradeObject t = vTradeRequests.get(i);
if (t.getRecipient().getID() == lRecipient) {
return t;
}
}
return retval;
}
protected long getIncomingTradeRequesterID() {
if (vIncomingTradeRequest == null) {
return 0;
}
return vIncomingTradeRequest.get(0); // <<get the top requester
}
protected void addIncomingTradeRequest(long lRequesterID) {
if (vIncomingTradeRequest == null) {
vIncomingTradeRequest = new Vector<Long>();
}
if (!vIncomingTradeRequest.contains(lRequesterID)) {
vIncomingTradeRequest.add(0, lRequesterID); // <<always add to 0
}
}
protected void removeIncomingtradeRequest(long lRequesterID) {
if (vIncomingTradeRequest == null) {
vIncomingTradeRequest = new Vector<Long>();
}
if (!vIncomingTradeRequest.contains(lRequesterID)) {
vIncomingTradeRequest.remove(lRequesterID);
}
}
protected void setCurrentTradeObject(TradeObject currentTradeObject) {
this.currentTradeObject = currentTradeObject;
}
protected TradeObject getCurrentTradeObject() {
return currentTradeObject;
}
protected void removeCurrentTradeObject() {
currentTradeObject = null;
}
public long getLPlayerCreationDate() {
return lPlayerCreationDate;
}
/**
* returns the next number of the group invite value this increments the
* counter for every call
*
* @return
*/
public int getGroupInviteCounter(boolean bIncrement) {
if (bIncrement) {
iGroupInviteCounter++;
}
return iGroupInviteCounter;
}
public long getGroupHost() {
return lGroupHost;
}
public void setGroupHost(long lGroupHost) {
this.lGroupHost = lGroupHost;
}
public void resetGroupTime() {
lGroupTime = 0;
}
public void updateGroupTime(long lDeltaMS) {
lGroupTime += lDeltaMS;
}
public long getGroupTime() {
return lGroupTime;
}
public int getGroupUpdateCounter(boolean bIncrement) {
if (bIncrement) {
iGroupUpdateCounter++;
}
return iGroupUpdateCounter;
}
protected ResourceContainer getLastUpdatedResourceContainer() {
return thePlayer.getLastUpdatedResourceContainer();
}
protected void setLastUpdatedResourceContainer(ResourceContainer container) {
thePlayer.setLastUpdatedResourceContainer(container);
}
protected void setNextHealDelay(int iSkillModValue) {
lHealDelayMS = (Constants.BASE_HEALING_ACTION_COOLDOWN_MS - (Constants.HEALING_ACTION_DECAY_PER_SKILLMOD_POINT * iSkillModValue));
}
protected long getNextHealDelay() {
return lHealDelayMS;
}
public void setHasOutstandingTeachingOffer(
boolean bHasOutstandingTeachingOffer) {
this.bHasOutstandingTeachingOffer = bHasOutstandingTeachingOffer;
}
public boolean getHasOutstandingTeachingOffer() {
return bHasOutstandingTeachingOffer;
}
public void setDisconnectIgnore(boolean bDisconnectIgnore) {
this.bDisconnectIgnore = bDisconnectIgnore;
}
public boolean isDisconnectIgnore() {
return bDisconnectIgnore;
}
public void setStudent(Player student) {
this.teachingStudent = student;
}
public Player getStudent() {
return teachingStudent;
}
public Player getTeacher() {
return teacher;
}
public void setTeacher(Player player) {
teacher = player;
}
public void setSkillOfferedByTeacher(Skills skill) {
skillOfferedByTeacher = skill;
if (skill == null) {
setHasOutstandingTeachingOffer(false);
} else {
setHasOutstandingTeachingOffer(true);
}
}
public Skills getSkillOfferedByTeacher() {
return skillOfferedByTeacher;
}
public int getIPlaySoundUpdateCounter() {
iPlaySoundUpdateCounter++;
return iPlaySoundUpdateCounter;
}
public long getListeningToID() {
return lListeningToID;
}
public void setListeningToID(long lListeningToID) {
this.lListeningToID = lListeningToID;
try {
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 4, (short) 1, (short) 6,
this, lListeningToID));
} catch (Exception e) {
DataLog.logException("Exception while updating listening to ID",
"Player.setListeningToID",
ZoneServer.ZoneRunOptions.bLogToConsole, true, e);
}
}
/**
* Return the amount of space left on a players inventory. If any items such
* as deeds are not to be counted towards space used because they are in a
* state that should not be counted, it has to be accounted for here. In the
* case of deeds, when placed the deed is not counted towards inventory
* space since its not spawned to the players inventory yet its still there
* so the deed can be returned. This routine will count the amount of items
* in the players inventory and return 80 - the count of items.
*
* @return
*/
protected int getInventorySlotsLeft() {
int invCount = 0;
for (int i = 0; i < getInventoryItems().size(); i++) {
TangibleItem t = getInventoryItems().get(i);
if (t instanceof Deed) {
Deed d = (Deed) t;
if (!d.isPlaced()) {
invCount++;
} else {
invCount++;
}
}
}
return 80 - invCount;
}
public void setSynchronizedListenObject(SOEObject synchronizedObject) {
this.synchronizedObject = synchronizedObject;
}
public SOEObject getSynchronizedListenObject() {
return synchronizedObject;
}
public void setLastSentCraftingSchematicList(
Vector<CraftingSchematic> vLastCreatedCraftingSchematicList) {
this.vLastCreatedCraftingSchematicList = vLastCreatedCraftingSchematicList;
}
public Vector<CraftingSchematic> getLastSentCraftingSchematicList() {
return vLastCreatedCraftingSchematicList;
}
public Camp getCurrentCampObject() {
return currentCampObject;
}
public void setCurrentCampObject(Camp currentCampObject) {
this.currentCampObject = currentCampObject;
}
public boolean isInCamp() {
return bIsInCamp;
}
public void setIsInCamp(boolean bIsInCamp) {
this.bIsInCamp = bIsInCamp;
}
protected void addCalledPet(CreaturePet pet) {
if (vCalledPets == null) {
vCalledPets = new Vector<CreaturePet>();
}
if (!vCalledPets.contains(pet)) {
vCalledPets.add(pet);
}
}
public void setCurrentManufacturingSchematic(
ManufacturingSchematic currentManufacturingSchematic) {
this.currentManufacturingSchematic = currentManufacturingSchematic;
}
protected void removeCalledPet(CreaturePet pet) {
if (vCalledPets == null) {
vCalledPets = new Vector<CreaturePet>();
}
if (vCalledPets.contains(pet)) {
vCalledPets.remove(pet);
}
}
public ManufacturingSchematic getCurrentManufacturingSchematic() {
return currentManufacturingSchematic;
}
protected Vector<CreaturePet> getCalledPets() {
if (vCalledPets == null) {
vCalledPets = new Vector<CreaturePet>();
}
return vCalledPets;
}
protected void addFriendPet(CreaturePet pet) {
if (vFriendPets == null) {
vFriendPets = new Vector<CreaturePet>();
}
if (!vFriendPets.contains(pet)) {
vFriendPets.add(pet);
}
}
protected void removeFriendPet(CreaturePet pet) {
if (vFriendPets == null) {
vFriendPets = new Vector<CreaturePet>();
}
if (vFriendPets.contains(pet)) {
vFriendPets.remove(pet);
}
}
protected Vector<CreaturePet> getFriendPets() {
if (vFriendPets == null) {
vFriendPets = new Vector<CreaturePet>();
}
return vFriendPets;
}
/*------------------------------------------------------*/
/**
* 338, 'outdoors_creaturehandler_novice',
* 'pet_follow,pet_release,pet_attack,tame',
* 'stored_pets=4,keep_creature=1,tame_non_aggro=5,tame_level=12' 339,
* 'outdoors_creaturehandler_master', 'pet_transfer,pet_rangedattack',
* 'keep_creature=1,tame_non_aggro=5,tame_aggro=15,private_creature_empathy=10
* , private_creature_training=10,private_creature_management=10,tame_level=
* 10, stored_pets=4' 340, 'outdoors_creaturehandler_taming_01', ' ',
* 'tame_non_aggro=5,tame_level=2' 341,
* 'outdoors_creaturehandler_taming_02', ' ',
* 'tame_non_aggro=5,tame_aggro=10,tame_level=2' 342,
* 'outdoors_creaturehandler_taming_03', 'pet_specialattack1',
* 'tame_non_aggro=5,tame_aggro=10,tame_level=3' 343,
* 'outdoors_creaturehandler_taming_04', 'pet_specialattack2',
* 'tame_non_aggro=5,tame_aggro=15,tame_level=5' 344,
* 'outdoors_creaturehandler_training_01', 'pet_stay',
* 'private_creature_training=10,tame_level=2,stored_pets=2,tame_non_aggro=5
* ' 345, 'outdoors_creaturehandler_training_02', 'pet_guard',
* 'stored_pets=3,private_creature_training=10,tame_level=2,tame_non_aggro=5
* ' 346, 'outdoors_creaturehandler_training_03', 'pet_patrol',
* 'private_creature_training=10,tame_level=3,stored_pets=3,tame_non_aggro=5
* ' 347, 'outdoors_creaturehandler_training_04', 'pet_formation',
* 'stored_pets=4,private_creature_training=10,tame_level=5,tame_non_aggro=5
* ' 348, 'outdoors_creaturehandler_healing_01', 'trick1',
* 'private_creature_empathy=10,tame_level=2,tame_non_aggro=5' 349,
* 'outdoors_creaturehandler_healing_02', 'emboldenpets',
* 'private_creature_empathy=10,tame_level=2,tame_non_aggro=5' 350,
* 'outdoors_creaturehandler_healing_03', 'trick2',
* 'private_creature_empathy=10,tame_level=3,tame_non_aggro=5' 351,
* 'outdoors_creaturehandler_healing_04', 'enragepets',
* 'private_creature_empathy=10,tame_level=5,tame_non_aggro=5' 352,
* 'outdoors_creaturehandler_support_01', 'pet_group',
* 'private_creature_management=10,tame_level=2,tame_non_aggro=5' 353,
* 'outdoors_creaturehandler_support_02', 'pet_followother',
* 'private_creature_management=10,tame_level=2,tame_non_aggro=5' 354,
* 'outdoors_creaturehandler_support_03', 'pet_friend',
* 'keep_creature=1,private_creature_management=10,tame_level=3,tame_non_aggro=5
* ' 355, 'outdoors_creaturehandler_support_04', 'train_mount',
* 'private_creature_management=10,tame_level=5,tame_non_aggro=5'
*
* private int iMaxCalledDroids; // def 2 private int iMaxCalledAnimalPets;
* //def 1 private int iMaxCalledFactionPets; //def 2
*
* private int iMaxDataPadDroids; //def 4 private int iMaxDataPadAnimalPets;
* //def 3 private int iMaxDataPadFactionPets; //def 2
*
* private int iMaxCalledPets; //def 2 private int iMaxDataPadPets; //def 9
*/
public int getIMaxCalledAnimalPets() {
iMaxCalledAnimalPets = 1;
if (this.hasSkill(338)) {
iMaxCalledAnimalPets++;
}
if (this.hasSkill(354)) {
iMaxCalledAnimalPets++;
}
return iMaxCalledAnimalPets;
}
public void setIMaxCalledAnimalPets(int iMaxCalledAnimalPets) {
this.iMaxCalledAnimalPets = iMaxCalledAnimalPets;
}
public int getIMaxCalledDroids() {
iMaxCalledDroids = 2;
if (this.hasSkill(479)) {
iMaxCalledDroids += 2;
}
return iMaxCalledDroids;
}
public void setIMaxCalledDroids(int iMaxCalledDroids) {
this.iMaxCalledDroids = iMaxCalledDroids;
}
public int getIMaxCalledFactionPets() {
iMaxCalledFactionPets = 2;
return iMaxCalledFactionPets;
}
public void setIMaxCalledFactionPets(int iMaxCalledFactionPets) {
this.iMaxCalledFactionPets = iMaxCalledFactionPets;
}
public int getIMaxCalledPets() {
iMaxCalledPets = 2;
if (this.hasSkill(338)) {
iMaxCalledPets++;
}
if (this.hasSkill(354)) {
iMaxCalledPets++;
}
if (this.hasSkill(339)) {
iMaxCalledPets++;
}
if (this.hasSkill(479)) {
iMaxCalledPets += 2;
}
return iMaxCalledPets;
}
public void setIMaxCalledPets(int iMaxCalledPets) {
this.iMaxCalledPets = iMaxCalledPets;
}
public int getIMaxDataPadAnimalPets() {
iMaxDataPadAnimalPets = 3;
if (this.hasSkill(338)) {
iMaxDataPadAnimalPets += 4;
}
if (this.hasSkill(339)) {
iMaxDataPadAnimalPets += 4;
}
if (this.hasSkill(344)) {
iMaxDataPadAnimalPets += 2;
}
if (this.hasSkill(345)) {
iMaxDataPadAnimalPets += 3;
}
if (this.hasSkill(346)) {
iMaxDataPadAnimalPets += 3;
}
if (this.hasSkill(347)) {
iMaxDataPadAnimalPets += 4;
}
return iMaxDataPadAnimalPets;
}
public void setIMaxDataPadAnimalPets(int iMaxDataPadAnimalPets) {
this.iMaxDataPadAnimalPets = iMaxDataPadAnimalPets;
}
public int getIMaxDataPadDroids() {
iMaxDataPadDroids = 4;
if (this.hasSkill(472)) {
iMaxDataPadDroids += 4;
}
return iMaxDataPadDroids;
}
public void setIMaxDataPadDroids(int iMaxDataPadDroids) {
this.iMaxDataPadDroids = iMaxDataPadDroids;
}
public int getIMaxDataPadFactionPets() {
iMaxDataPadFactionPets = 2;
return iMaxDataPadFactionPets;
}
public void setIMaxDataPadFactionPets(int iMaxDataPadFactionPets) {
this.iMaxDataPadFactionPets = iMaxDataPadFactionPets;
}
public int getIMaxDataPadPets() {
iMaxDataPadPets = 9;
if (this.hasSkill(338)) {
iMaxDataPadPets += 4;
}
if (this.hasSkill(339)) {
iMaxDataPadPets += 4;
}
if (this.hasSkill(344)) {
iMaxDataPadPets += 2;
}
if (this.hasSkill(345)) {
iMaxDataPadPets += 3;
}
if (this.hasSkill(346)) {
iMaxDataPadPets += 3;
}
if (this.hasSkill(347)) {
iMaxDataPadPets += 4;
}
if (this.hasSkill(472)) {
iMaxDataPadPets += 4;
}
return iMaxDataPadPets;
}
public void setIMaxDataPadPets(int iMaxDataPadPets) {
this.iMaxDataPadPets = iMaxDataPadPets;
}
public Waypoint getLastForageArea() {
return lastForageArea;
}
public void setLastForageArea(Waypoint lastForageArea) {
this.lastForageArea = lastForageArea;
}
public long getForageCooldown() {
return forageCooldown;
}
public void setForageCooldown(long forageCooldown) {
this.forageCooldown = forageCooldown;
}
public byte getForageType() {
return forageType;
}
public void setForageType(byte forageType) {
this.forageType = forageType;
}
public boolean isForaging() {
return isForaging;
}
public void setIsForaging(boolean isForaging) {
this.isForaging = isForaging;
}
private void forage() {
try {
this.isForaging = false;
if (this.getForageType() == Constants.FORAGE_TYPE_GENERAL) {
boolean bFound = false;
TangibleItem foraged = null;
if (SWGGui.getRandomInt(1, 1000) >= 500) {
int iRandomForagedItem = SWGGui.getRandomInt(0,
Constants.FORAGED_ITEMS.length);
foraged = new FoodItem();
foraged.setID(server.getNextObjectID());
foraged
.setTemplateID(Constants.FORAGED_ITEMS[iRandomForagedItem]);
foraged.setConditionDamage(0, false);
foraged.setMaxCondition(1000, false);
foraged.setPVPStatus(Constants.PVP_STATUS_IS_ITEM);
int iRandomSkillModCount = SWGGui.getRandomInt(0, 2);
if (iRandomSkillModCount >= 1) {
int[] iRandomSkillMod = new int[iRandomSkillModCount];
int[] iRandomSkillModValue = new int[iRandomSkillModCount];
for (int i = 0; i < iRandomSkillModCount; i++) {
iRandomSkillMod[i] = SWGGui.getRandomInt(0,
Constants.FORAGED_SKILL_MODIFIERS.length);
iRandomSkillModValue[i] = Math.max(2, SWGGui
.getRandomInt(2, 8));
SkillModifier s = new SkillModifier();
s.setCharges(1);
long lDuration = Math.max(5000, SWGGui
.getRandomLong(5000, 15000));
s.setDuration(lDuration);
s
.setSkillModifierID(Constants.FORAGED_SKILL_MODIFIERS[iRandomSkillMod[i]]);
s.setSkillModifierValue(iRandomSkillModValue[i]);
foraged.addSkillModifier(s);
}
}
bFound = true;
}
if (bFound && this.getInventorySlotsLeft() >= 1) {
foraged
.setDelayedSpawnAction(Constants.DELAYED_SPAWN_ACTION_SPAWN);
server.addObjectToAllObjects(foraged, false, false);
foraged.setEquipped(this.getInventory(),
Constants.EQUIPPED_STATE_UNEQUIPPED);
this.addItemToInventory(foraged);
this.getInventory().addLinkedObject(foraged);
this.addDelayedSpawnObject(foraged, System
.currentTimeMillis() + 500);
this.getClient().insertPacket(
PacketFactory.buildChatSystemMessage("skl_use",
"sys_forage_success"));
this.updateExperience(null, DatabaseInterface
.getExperienceIDFromName("camp"), 15);
} else if (this.getInventorySlotsLeft() == 0) {
this.getClient().insertPacket(
PacketFactory.buildChatSystemMessage("skl_use",
"sys_forage_noroom"));
} else {
this.getClient().insertPacket(
PacketFactory.buildChatSystemMessage("skl_use",
"sys_forage_fail"));
}
}
} catch (Exception e) {
DataLog.logException("Exception in forage", "Player",
ZoneServer.ZoneRunOptions.bLogToConsole, true, e);
}
}
public Instrument getEquippedInstrument() {
return equippedInstrument;
}
public void unequipInstrument() {
equippedInstrument = null;
}
public Player getPlayerBeingListened() {
return playerBeingListened;
}
public void setPlayerBeingListened(Player playerBeingListened) {
try {
getClient().insertPacket(
PacketFactory.buildChatSystemMessage("performance",
"music_stop_other", this.playerBeingListened
.getID(), this.playerBeingListened
.getSTFFileName(), this.playerBeingListened
.getSTFFileIdentifier(),
this.playerBeingListened.getFullName(), 0, null,
null, null, 0, null, null, null, 0, 0.0f, false));
if (playerBeingListened != null) {
this.setListeningToID(playerBeingListened.getID());
} else {
this.setListeningToID(0);
}
this.playerBeingListened = playerBeingListened;
} catch (Exception e) {
DataLog.logException("Exception while setting listening target",
"Player", ZoneServer.ZoneRunOptions.bLogToConsole, true, e);
}
}
public Player getPlayerBeingWatched() {
return playerBeingWatched;
}
public void setPlayerBeingWatched(Player playerBeingWatched) {
if (this.playerBeingWatched != null) {
this.playerBeingWatched.removePlayerWatching(this);
}
if (playerBeingWatched != null) {
this.playerBeingWatched = playerBeingWatched;
try {
client.insertPacket(PacketFactory.buildChatSystemMessage(
"performance", "dance_watch_self", this.getID(), this
.getSTFFileName(), this.getSTFFileIdentifier(),
this.getFullName(), playerBeingWatched.getID(),
playerBeingWatched.getSTFFileName(), playerBeingWatched
.getSTFFileIdentifier(), playerBeingWatched
.getFullName(), 0, null, null, null, 0, 0.0f,
false));
this.setListeningToID(playerBeingWatched.getID());
lRandomWatchPlayerTick = Math.max(5000, SWGGui.getRandomLong(
5000, 30000));
/**
* @todo send player listening to ID delta
*/
// client.insertPacket(PacketFactory);
} catch (Exception e) {
DataLog.logException(
"Exception while setting listening target", "Player",
ZoneServer.ZoneRunOptions.bLogToConsole, true, e);
}
}
}
protected void addPlayerWatching(Player p) {
if (vPlayersWatching == null) {
vPlayersWatching = new Vector<Player>();
}
if (!vPlayersWatching.contains(p)) {
vPlayersWatching.add(p);
}
}
protected void removePlayerWatching(Player p) {
if (vPlayersWatching == null) {
vPlayersWatching = new Vector<Player>();
}
if (vPlayersWatching.contains(p)) {
vPlayersWatching.remove(p);
}
}
protected void addPlayerListening(Player p) {
if (vPlayersListening == null) {
vPlayersListening = new Vector<Player>();
}
if (!vPlayersListening.contains(p)) {
vPlayersListening.add(p);
}
}
protected void removePlayerListening(Player p) {
if (vPlayersListening == null) {
vPlayersListening = new Vector<Player>();
}
if (vPlayersListening.contains(p)) {
vPlayersListening.remove(p);
}
}
protected Vector<Player> getPlayersListening() {
if (vPlayersListening == null) {
vPlayersListening = new Vector<Player>();
}
return vPlayersListening;
}
protected Vector<Player> getPlayersWatching() {
if (vPlayersWatching == null) {
vPlayersWatching = new Vector<Player>();
}
return vPlayersWatching;
}
public boolean isDancing() {
return isDancing;
}
public void setIsDancing(boolean isDancing) {
System.out
.println("Player Set To Dance " + Boolean.toString(isDancing));
this.isDancing = isDancing;
}
public boolean isPlayingMusic() {
return isPlayingMusic;
}
public void setIsPlayingMusic(boolean isPlayingMusic) {
this.isPlayingMusic = isPlayingMusic;
}
protected void setDanceTick(long tick) {
lDancetick = tick;
}
protected void setMusicTick(long tick) {
lMusicTick = tick;
}
public long getLEffectTick() {
return lEffectTick;
}
public void setLEffectTick(long lEffectTick) {
this.lEffectTick = lEffectTick;
}
protected Vector<String> getKnownDances() {
Vector<String> vKnownDances = new Vector<String>();
for (int i = 0; i < Constants.DANCE_STRINGS.length; i++) {
if (this.hasSkill(Constants.DANCE_SKILL_REQUIREMENTS[i])) {
vKnownDances.add(Constants.DANCE_STRINGS[i][0]);
}
}
return vKnownDances;
}
protected Vector<String> getKnownMusic() {
Vector<String> vKnownMusic = new Vector<String>();
for (int i = 0; i < Constants.MUSIC_STRINGS.length; i++) {
if (this.hasSkill(Constants.MUSIC_SKILL_REQUIREMENTS[i])) {
vKnownMusic.add(Constants.MUSIC_STRINGS[i][0]);
}
}
return vKnownMusic;
}
public int getIPerformanceID() {
return iPerformanceID;
}
public void setPerformanceID(int iPerformanceID) throws IOException {
this.iPerformanceID = iPerformanceID;
getClient().insertPacket(
PacketFactory.buildDeltasMessage(Constants.BASELINES_CREO,
(byte) 6, (short) 1, (short) 11, this,
this.iPerformanceID));
}
// These function names need be more descriptive.
public boolean getC60X11() {
return C60X11;
}
// These function names need be more descriptive.
public void setC60X11(boolean C60X11) throws IOException {
this.C60X11 = C60X11;
client.insertPacket(PacketFactory.buildDeltasMessage(
Constants.BASELINES_CREO, (byte) 6, (short) 1, (short) 0x11,
this, this.C60X11), Constants.PACKET_RANGE_CHAT_RANGE);
}
public byte[] setNearbyCraftingStation(TangibleItem station) {
return thePlayer.setNearbyCraftingStation(station);
}
public TangibleItem getNearbyCraftingStation() {
return thePlayer.getNearbyCraftingStation();
}
public byte[] setExperimentationAndManufacturingFlag(int flag) {
return thePlayer.setExperimentationAndManufacturingFlag(flag);
}
public int getExperimentationAndManufacturingFlag() {
return thePlayer.getExperimentationAndManufacturingFlag();
}
public byte[] setNumExperimentationPoints(int pointCount) {
return thePlayer.setNumExperimentationPoints(pointCount);
}
public int getNumExperimentationPoints() {
return thePlayer.getNumExperimentationPoints();
}
protected int applyBuff(MedicalItem buffItem) throws IOException {
int buffCRC = 0;
int buffIndex = buffItem.getHamIndex();
switch (buffIndex) {
case Constants.HAM_INDEX_HEALTH: {
buffCRC = Constants.BUFF_EFFECT_MEDICAL_ENHANCE_HEALTH;
break;
}
case Constants.HAM_INDEX_ACTION: {
buffCRC = Constants.BUFF_EFFECT_MEDICAL_ENHANCE_ACTION;
break;
}
case Constants.HAM_INDEX_STRENGTH: {
buffCRC = Constants.BUFF_EFFECT_MEDICAL_ENHANCE_STRENGTH;
break;
}
case Constants.HAM_INDEX_STAMINA: {
buffCRC = Constants.BUFF_EFFECT_MEDICAL_ENHANCE_STAMINA;
break;
}
case Constants.HAM_INDEX_CONSTITUTION: {
buffCRC = Constants.BUFF_EFFECT_MEDICAL_ENHANCE_CONSTITUTION;
break;
}
case Constants.HAM_INDEX_QUICKNESS: {
buffCRC = Constants.BUFF_EFFECT_MEDICAL_ENHANCE_QUICKNESS;
break;
}
default: {
System.out.println("Unknown stat index to buff: " + buffIndex);
return 0;
}
}
float fBuffDuration = buffItem.getDurationEffectSec();
if (client != null) {
if (getOnlineStatus()) {
int iPreviousHamModifier = iHamModifiers[buffItem.getHamIndex()];
int iNewHamModifier = buffItem.getHealAmount();
int effectiveBuff = iNewHamModifier - iPreviousHamModifier;
if (effectiveBuff > 0) {
BuffEffect effect = new BuffEffect();
effect.setAffectedPlayer(this);
effect.setBuffHamIndex(buffItem.getHamIndex());
effect
.setBuffIndex(Constants.BUFF_EFFECT_MEDICAL_ENHANCE_HEALTH
+ buffItem.getHamIndex());
effect.setBuffPotency(buffItem.getHealAmount());
effect.setStateApplied(0);
effect.setTimeRemainingMS((long) (fBuffDuration * 1000.0f));
addBuffEffect(effect);
updateHamModifiers(buffItem.getHamIndex(), effectiveBuff,
true, true);
client.insertPacket(PacketFactory
.buildObjectControllerMessageBuffStat(this,
Constants.BUFF_EFFECTS[buffCRC],
fBuffDuration));
return effectiveBuff;
}
}
}
return 0;
}
protected int applyDisease(MedicalItem diseaseItem) throws IOException {
return 0;
}
protected void applyFireBlanket(MedicalItem fireBlanket) throws IOException {
}
protected int healDamage(MedicalItem healItem) throws IOException {
int maxDamageToHeal = healItem.getHealAmount();
int index = healItem.getHamIndex();
int damageActuallyHealed = updateCurrentHam(index, maxDamageToHeal);
return Math.max(damageActuallyHealed, 0);
}
protected int applyPoison(MedicalItem poisonItem) throws IOException {
return 0;
}
protected void applyPoison(int hamIndex, int potency, long lDuration) {
lPoisonTimeMS[hamIndex] = lDuration;
lPoisonTickTimeMS[hamIndex] = 1;
iPoisonPotency[hamIndex] = potency;
addState(Constants.STATE_POISONED, lDuration);
}
protected void applyDisease(int hamIndex, int potency, long lDuration) {
lDiseaseTimeMS[hamIndex] = lDuration;
lDiseaseTickTimeMS[hamIndex] = 1;
iDiseasePotency[hamIndex] = potency;
addState(Constants.STATE_DISEASED, lDuration);
}
protected void applyBleed(int hamIndex, int potency, long lDuration) {
lBleedTimeMS[hamIndex] = lDuration;
lBleedTickTimeMS[hamIndex] = 1;
iBleedPotency[hamIndex] = potency;
addState(Constants.STATE_BLEEDING, lDuration);
}
protected void applyFire(int hamIndex, int potency, long lDuration) {
lFireTimeMS[hamIndex] = lDuration;
lFireTickTimeMS[hamIndex] = 1;
iFirePotency[hamIndex] = potency;
addState(Constants.STATE_BURNING, lDuration);
}
protected int healWounds(MedicalItem woundHealItem) throws IOException {
return 0;
}
protected void addBuffEffect(BuffEffect effect) {
// TODO -- If an effect is already present, and superior to the one
// being added, don't add it.
if (vBuffEffects == null)
return;
vBuffEffects[effect.getBuffIndex()] = effect;
effect.setAffectedPlayer(this);
addState((int) effect.getStateApplied(), effect.getTimeRemainingMS());
int appliedStance = effect.getStanceApplied();
setStance(null, (byte) appliedStance, true);
}
protected void removeBuffEffect(int index) {
vBuffEffects[index] = null;
try {
client.insertPacket(PacketFactory
.buildObjectControllerMessageBuffStat(this,
Constants.BUFF_EFFECTS[index], 0.0f));
} catch (IOException e) {
// D'oh!
}
}
private void updatePoisons(long lDeltaTimeMS) {
for (int i = 0; i < lPoisonTickTimeMS.length; i++) {
if (lPoisonTickTimeMS[i] > 0) {
lPoisonTickTimeMS[i] -= lDeltaTimeMS;
if (lPoisonTickTimeMS[i] <= 0) {
// Tick the poison
updateCurrentHam(i, -iPoisonPotency[i]);
lPoisonTickTimeMS[i] = Constants.DAMAGE_OVER_TIME_TICK_RATE_MS;
}
lPoisonTimeMS[i] -= lDeltaTimeMS;
if (lPoisonTimeMS[i] < 0) {
lPoisonTimeMS[i] = 0;
lPoisonTickTimeMS[i] = 0;
iPoisonPotency[i] = 0;
}
}
}
}
private void updateDiseases(long lDeltaTimeMS) {
for (int i = 0; i < lDiseaseTickTimeMS.length; i++) {
if (lDiseaseTickTimeMS[i] > 0) {
lDiseaseTickTimeMS[i] -= lDeltaTimeMS;
if (lDiseaseTickTimeMS[i] <= 0) {
// Tick the poison
updateHAMWounds(i, -iDiseasePotency[i], true);
lDiseaseTickTimeMS[i] = Constants.DAMAGE_OVER_TIME_TICK_RATE_MS;
}
lDiseaseTimeMS[i] -= lDeltaTimeMS;
if (lDiseaseTimeMS[i] < 0) {
lDiseaseTimeMS[i] = 0;
lDiseaseTickTimeMS[i] = 0;
iDiseasePotency[i] = 0;
}
}
}
}
private void updateBleeds(long lDeltaTimeMS) {
for (int i = 0; i < lBleedTickTimeMS.length; i++) {
if (lBleedTickTimeMS[i] > 0) {
lBleedTickTimeMS[i] -= lDeltaTimeMS;
if (lBleedTickTimeMS[i] <= 0) {
// Tick the poison
updateCurrentHam(i, -iBleedPotency[i]);
lBleedTickTimeMS[i] = Constants.DAMAGE_OVER_TIME_TICK_RATE_MS;
}
lBleedTimeMS[i] -= lDeltaTimeMS;
if (lBleedTimeMS[i] < 0) {
lBleedTimeMS[i] = 0;
lBleedTickTimeMS[i] = 0;
iBleedPotency[i] = 0;
}
}
}
}
private void updateFires(long lDeltaTimeMS) {
for (int i = 0; i < lFireTickTimeMS.length; i++) {
if (lFireTickTimeMS[i] > 0) {
lFireTickTimeMS[i] -= lDeltaTimeMS;
if (lFireTickTimeMS[i] <= 0) {
// Tick the poison
updateCurrentHam(i, -iFirePotency[i] * 2);
updateHAMWounds(i, -iFirePotency[i], true);
lFireTickTimeMS[i] = Constants.DAMAGE_OVER_TIME_TICK_RATE_MS;
}
lFireTimeMS[i] -= lDeltaTimeMS;
if (lFireTimeMS[i] < 0) {
lFireTimeMS[i] = 0;
lFireTickTimeMS[i] = 0;
iFirePotency[i] = 0;
}
}
}
}
protected boolean setCurrentDrinkFullness(int iAmountToIncrease)
throws IOException {
return thePlayer.setCurrentDrinkFullness(iAmountToIncrease);
}
protected boolean setCurrentFoodFullness(int iAmountToIncrease)
throws IOException {
return thePlayer.setCurrentFoodFullness(iAmountToIncrease);
}
private void updateCommandQueueEnqueues(long lDeltaTimeMS) {
if (!vCommandQueue.isEmpty()) {
CommandQueueItem queueItem = vCommandQueue.peekFirst();
if (!queueItem.hasBeenSent()) {
// Can we actually do the action?
// We will assume yes for now.
CombatAction action = queueItem.getCombatAction();
if (action != null) {
try {
client.getUpdateThread().handleAttack(queueItem);
} catch (IOException e) {
DataLog.logException("Error handling attack",
"ZoneClientThread.handleAttack()", true, true,
e);
}
}
int iSkillIDRequired = queueItem.getSkillIDRequired();
if (iSkillIDRequired != -1) {
if (!hasSkill(iSkillIDRequired)) {
// This allows for debug of more advanced attacks.
if (!client.getUpdateThread().getIsDeveloper()) {
queueItem
.setErrorMessageID(Constants.COMMAND_QUEUE_ERROR_TYPE_INSUFFICIENT_SKILL);
}
}
}
try {
byte[] packet = PacketFactory.buildCommandQueueDequeue(
this, queueItem);
// if (queueItem.getCRC() == Constants.DefaultAttackNPC ||
// (hasState(Constants.STATE_COMBAT))) {
// PacketUtils.printPacketToScreen(packet,
// "Dequeue of default attack");
// }
client.insertPacket(packet);
queueItem.setHasBeenSent(true);
} catch (IOException e) {
// D'oh!
}
}
long lTimeRemaining = queueItem.getCommandTimerMS(); // Probably in
// seconds.
lTimeRemaining -= lDeltaTimeMS;
if (lTimeRemaining <= 0) {
vCommandQueue.removeFirst();
} else {
queueItem.setCommandTimerMS(lTimeRemaining);
}
}
}
private void setCommandQueueErrorStance(int iNormalStance) {
switch (iNormalStance) {
case Constants.STANCE_STANDING: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_STANDING;
break;
}
case Constants.STANCE_KNEELING: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_KNEELING;
break;
}
case Constants.STANCE_PRONE: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_PRONE;
break;
}
case Constants.STANCE_SNEAKING: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_SNEAKING;
break;
}
case Constants.STANCE_LAYDOWN: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_LYING_DOWN;
break;
}
case Constants.STANCE_CLIMBING: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_CLIMBING;
break;
}
case Constants.STANCE_FLYING: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_FLYING;
break;
}
case Constants.STANCE_LAYDOWN2: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_LYING_DOWN;
break;
}
case Constants.STANCE_SITTING: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_SITTING;
break;
}
case Constants.STANCE_ANIMATING_SKILL: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_SKILL_ANIMATING;
break;
}
case Constants.STANCE_DRIVING: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_MOUNTED_VEHICLE;
break;
}
case Constants.STANCE_MOUNTED: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_MOUNTED_CREATURE;
break;
}
case Constants.STANCE_KNOCKED_DOWN: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_KNOCKED_DOWN;
break;
}
case Constants.STANCE_INCAPACITATED: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_INCAPACITATED;
break;
}
case Constants.STANCE_DEAD: {
iCommandQueueErrorStance = Constants.COMMAND_QUEUE_ERROR_STANCE_DEAD;
break;
}
default: {
// Cannot happen!
}
}
}
protected int getCommandQueueErrorStance() {
return iCommandQueueErrorStance;
}
private transient long lCommandQueueTimerMS = 0l;
protected void setTimeToNextCommandQueueAction(long lTimeMS) {
lCommandQueueTimerMS = lTimeMS;
}
protected long getTimeToNextCommandQueueAction() {
return lCommandQueueTimerMS;
}
protected byte[] addDefender(Player player) throws IOException {
long lDefenderID = player.getID();
if (vDefenderList == null) {
vDefenderList = new Vector<Long>();
}
if (!vDefenderList.contains(lDefenderID)) {
// Add it, send the packet.
vDefenderList.add(lDefenderID);
int iIndex = vDefenderList.indexOf(lDefenderID);
return PacketFactory.buildDeltasCREO6DefenderList(this,
lDefenderID, (short) iIndex);
}
return null;
}
protected byte[] removeDefender(Player player) throws IOException {
long lDefenderID = player.getID();
if (vDefenderList.contains(lDefenderID)) {
int iIndex = vDefenderList.indexOf(lDefenderID);
return PacketFactory.buildDeltasCREO6DefenderList(this, 0,
(short) iIndex);
}
return null;
}
private void initializeState() {
long lAllApplicableStatesOnFirstLogin = 0;
for (int i = 2; i <= Constants.STATE_BURNING; i++) {
lAllApplicableStatesOnFirstLogin = lAllApplicableStatesOnFirstLogin
| (1 << i);
}
lState = lState & lAllApplicableStatesOnFirstLogin;
}
public long getTimeInCombat() {
long toReturn = lTimeInCombat;
lTimeInCombat = 0;
return toReturn;
}
protected void removeQueuedCommandByActionID(int iActionID) {
for (int i = 0; i < vCommandQueue.size(); i++) {
CommandQueueItem item = vCommandQueue.get(i);
if (item.getCommandID() == iActionID) {
// System.out.println("Found enqueue with command ID " +
// iActionID + ", removing.");
item.setHasBeenSent(true);
vCommandQueue.remove(i);
return;
}
}
System.out.println("Error: Did not find enqueue with command ID "
+ iActionID);
}
protected void clearCombatQueue() {
// Fail-fast iterator, so remove the enqueue from the iterator, NOT from
// the list. The iterator will remove from the list.
Iterator<CommandQueueItem> vQueueItr = vCommandQueue.iterator();
while (vQueueItr.hasNext()) {
CommandQueueItem queueItem = vQueueItr.next();
if (queueItem.getCombatAction() != null) {
vQueueItr.remove();
}
}
}
protected boolean canPerformAction(int health, int action, int mind) {
if (Math.abs(health) >= iCurrentHam[Constants.HAM_INDEX_HEALTH]
|| Math.abs(action) >= iCurrentHam[Constants.HAM_INDEX_ACTION]
|| Math.abs(mind) >= iCurrentHam[Constants.HAM_INDEX_MIND]) {
return false;
}
return true;
}
protected void setHasSeenCloningWindow(boolean bState) {
bSeenCloneWindow = bState;
}
protected void setMaskScentDelayTime(long lTime) {
lMaskScentDelayTime = lTime;
}
protected long getMaskScentDelayTime() {
return lMaskScentDelayTime;
}
public void setIsJedi(boolean bIsJedi) {
this.bIsJedi = bIsJedi;
}
public boolean getIsJedi() {
return bIsJedi;
}
public void setIsSampling(boolean bIsSampling) {
this.bIsSampling = bIsSampling;
}
public boolean getIsSampling() {
return bIsSampling;
}
protected Vector<ManufacturingSchematic> getSchematicsForFactory(
byte iFactoryType) {
Vector<IntangibleObject> vAllDatapadIntangibles = tDatapad
.getIntangibleObjects();
Vector<ManufacturingSchematic> vDatapadSchematics = new Vector<ManufacturingSchematic>();
int mask = 0;
switch (iFactoryType) {
case Constants.FACTORY_TYPE_CLOTHING: {
mask = Constants.CRAFTING_TOOL_TAB_ARMOR
| Constants.CRAFTING_TOOL_TAB_CLOTHING;
break;
}
case Constants.FACTORY_TYPE_FOOD: {
mask = Constants.CRAFTING_TOOL_TAB_BIO_ENGINEER_CREATURES
| Constants.CRAFTING_TOOL_TAB_BIO_ENGINEER_TISSUES
| Constants.CRAFTING_TOOL_TAB_CHEMICAL
| Constants.CRAFTING_TOOL_TAB_FOOD;
break;
}
case Constants.FACTORY_TYPE_STRUCTURE: {
mask = Constants.CRAFTING_TOOL_TAB_FURNITURE
| Constants.CRAFTING_TOOL_TAB_STRUCTURE;
break;
}
case Constants.FACTORY_TYPE_WEAPON: {
mask = Constants.CRAFTING_TOOL_TAB_DROID
| Constants.CRAFTING_TOOL_TAB_GENERIC_ITEM
| Constants.CRAFTING_TOOL_TAB_MISCELLANEOUS
| Constants.CRAFTING_TOOL_TAB_VEHICLE
| Constants.CRAFTING_TOOL_TAB_WEAPON;
}
}
if (vAllDatapadIntangibles.isEmpty()) {
return vDatapadSchematics;
}
for (int i = 0; i < vAllDatapadIntangibles.size(); i++) {
IntangibleObject itno = vAllDatapadIntangibles.elementAt(i);
if (itno instanceof ManufacturingSchematic) {
ManufacturingSchematic msco = (ManufacturingSchematic) itno;
CraftingSchematic craftingSchematic = msco
.getCraftingSchematic();
int toolTab = craftingSchematic.getIToolTabBitmask();
if (((toolTab & mask) != 0)
|| (toolTab == Constants.CRAFTING_TOOL_TAB_GENERIC_ITEM && iFactoryType == Constants.FACTORY_TYPE_WEAPON)) {
vDatapadSchematics.add(msco);
}
}
}
return vDatapadSchematics;
}
}
| SWGANHServices/SWGANHJava | documents/SWGCombined/src/Player.java | Java | gpl-3.0 | 227,836 |
package tudu.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
* A user's role.
*
* @author Julien Dubois
*/
@Entity
@Table(name = "role")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role implements Serializable {
private static final long serialVersionUID = -5636845397516495671L;
@Id
private String role;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| jdubois/Tudu-Lists | src/main/java/tudu/domain/Role.java | Java | gpl-3.0 | 666 |
/*
Storybook: Open Source software for novelists and authors.
Copyright (C) 2008 - 2012 Martin Mustun
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 storybook.ui.edit;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import org.apache.commons.lang3.text.WordUtils;
import storybook.model.hbn.entity.AbstractEntity;
import storybook.model.hbn.entity.Person;
import storybook.toolkit.swing.FontUtil;
/**
* @author martin
*
*/
public class PersonCbPanelDecorator extends CbPanelDecorator {
private String oldCat = "";
public PersonCbPanelDecorator() {
}
@Override
public void decorateBeforeFirstEntity() {
oldCat = "";
}
@Override
public void decorateBeforeEntity(AbstractEntity entity) {
Person p = (Person) entity;
String cat = WordUtils.capitalize(p.getCategory().getName());
if (!oldCat.equals(cat)) {
JLabel lb = new JLabel(cat);
lb.setFont(FontUtil.getBoldFont());
panel.add(lb, "span");
oldCat = cat;
}
}
@Override
public void decorateEntity(JCheckBox cb, AbstractEntity entity) {
Person p = (Person) entity;
JLabel lbIcon = new JLabel(p.getIcon());
lbIcon.setToolTipText(p.getGender().getName());
panel.add(lbIcon, "split 2");
panel.add(cb);
}
@Override
public void decorateAfterEntity(AbstractEntity entity) {
}
}
| neb45/oStoryBook-SE-410 | src/storybook/ui/edit/PersonCbPanelDecorator.java | Java | gpl-3.0 | 1,866 |
/**
* This file is part of Graylog.
*
* Graylog 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.
*
* Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.indexer.searches;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
import static org.assertj.jodatime.api.Assertions.assertThat;
public class TimestampStatsTest {
@Test
public void testCreate() throws Exception {
DateTime min = new DateTime(2015, 1, 1, 0, 0, DateTimeZone.UTC);
DateTime max = new DateTime(2015, 1, 3, 0, 0, DateTimeZone.UTC);
DateTime avg = new DateTime(2015, 1, 2, 0, 0, DateTimeZone.UTC);
TimestampStats timestampStats = TimestampStats.create(min, max, avg);
assertThat(timestampStats.min()).isEqualTo(min);
assertThat(timestampStats.max()).isEqualTo(max);
assertThat(timestampStats.avg()).isEqualTo(avg);
}
@Test
public void testEmptyInstance() throws Exception {
assertThat(TimestampStats.EMPTY.min()).isEqualTo(new DateTime(0L, DateTimeZone.UTC));
assertThat(TimestampStats.EMPTY.max()).isEqualTo(new DateTime(0L, DateTimeZone.UTC));
assertThat(TimestampStats.EMPTY.avg()).isEqualTo(new DateTime(0L, DateTimeZone.UTC));
}
} | modulexcite/graylog2-server | graylog2-server/src/test/java/org/graylog2/indexer/searches/TimestampStatsTest.java | Java | gpl-3.0 | 1,790 |
/**
* Copyright © MyCollab
* <p>
* 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.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* <p>
* 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.mycollab.module.project.view.milestone;
import com.mycollab.module.file.AttachmentUtils;
import com.mycollab.module.project.ProjectTypeConstants;
import com.mycollab.module.project.domain.Milestone;
import com.mycollab.module.project.domain.SimpleMilestone;
import com.mycollab.module.project.i18n.OptionI18nEnum.MilestoneStatus;
import com.mycollab.module.project.view.settings.component.ProjectMemberSelectionField;
import com.mycollab.vaadin.AppUI;
import com.mycollab.vaadin.ui.AbstractBeanFieldGroupEditFieldFactory;
import com.mycollab.vaadin.ui.GenericBeanForm;
import com.mycollab.vaadin.web.ui.I18nValueComboBox;
import com.mycollab.vaadin.web.ui.WebThemes;
import com.mycollab.vaadin.web.ui.field.AttachmentUploadField;
import com.vaadin.data.HasValue;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.ui.DateField;
import com.vaadin.ui.IconGenerator;
import com.vaadin.ui.RichTextArea;
import org.vaadin.viritin.fields.MTextField;
import static com.mycollab.module.project.i18n.OptionI18nEnum.MilestoneStatus.*;
/**
* @author MyCollab Ltd.
* @since 3.0
*/
public class MilestoneEditFormFieldFactory extends AbstractBeanFieldGroupEditFieldFactory<SimpleMilestone> {
private static final long serialVersionUID = 1L;
private AttachmentUploadField attachmentUploadField;
MilestoneEditFormFieldFactory(GenericBeanForm<SimpleMilestone> form) {
super(form);
}
@Override
protected HasValue<?> onCreateField(Object propertyId) {
if (Milestone.Field.assignuser.equalTo(propertyId)) {
return new ProjectMemberSelectionField();
} else if (propertyId.equals("status")) {
return new ProgressStatusComboBox();
} else if (propertyId.equals("name")) {
return new MTextField().withRequiredIndicatorVisible(true);
} else if (propertyId.equals("description")) {
return new RichTextArea();
} else if ("section-attachments".equals(propertyId)) {
Milestone beanItem = attachForm.getBean();
if (beanItem.getId() != null) {
String attachmentPath = AttachmentUtils.getProjectEntityAttachmentPath(AppUI.getAccountId(),
beanItem.getProjectid(), ProjectTypeConstants.MILESTONE, "" + beanItem.getId());
attachmentUploadField = new AttachmentUploadField(attachmentPath);
} else {
attachmentUploadField = new AttachmentUploadField();
}
return attachmentUploadField;
} else if (Milestone.Field.startdate.equalTo(propertyId) || Milestone.Field.enddate.equalTo(propertyId)) {
return new DateField();
}
return null;
}
public AttachmentUploadField getAttachmentUploadField() {
return attachmentUploadField;
}
private static class ProgressStatusComboBox extends I18nValueComboBox<MilestoneStatus> {
private static final long serialVersionUID = 1L;
ProgressStatusComboBox() {
super(MilestoneStatus.class, InProgress, Future, Closed);
this.setWidth(WebThemes.FORM_CONTROL_WIDTH);
this.setItemIconGenerator((IconGenerator<MilestoneStatus>) it -> {
switch (it) {
case InProgress:
return VaadinIcons.SPINNER;
case Future:
return VaadinIcons.CLOCK;
default:
return VaadinIcons.MINUS_CIRCLE;
}
});
this.setValue(InProgress);
}
}
}
| esofthead/mycollab | mycollab-web/src/main/java/com/mycollab/module/project/view/milestone/MilestoneEditFormFieldFactory.java | Java | agpl-3.0 | 4,308 |
/*
* Copyright (c) 1999 Sun Microsystems, Inc. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for NON-COMMERCIAL purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies. Please refer to the file "copyright.html"
* for further important copyright and licensing information.
*
* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
package javax.telephony.mobile;
import javax.telephony.*;
/**
* The <CODE>MobileRadio</CODE> interface is used for
* simple radio management capabilities (turning on and off), if
* the platform supports it.
* and getting information about the current signal strength.
*
* <H4>Network States</H4>
*
* The <CODE>MobileRadio</CODE> state can either be on (setState(true)) or off (setState(false)).
*
* If state management is not user controllable, then the <CODE>setState</CODE> method
* will throw a <CODE>MethodNotSupportedException</CODE>
*
* If the device has been secured via password protection (e.g. PIN-code),
* the <CODE>setState</CODE> method may also throw the
* <CODE>InvalidStateException</CODE>, if an attempt is made to manipulate the
* radio while the device is secured.
*
* <H4>Mobile Radio Listeners </H4>
*
* All changes in a <CODE>MobileRadio</CODE> object are reported via the
* <CODE>MobileRadioListener</CODE> interface.
*
* Applications instantiate an object which implements this
* interface and begins this delivery of events to this object using the
* <CODE>MobileRadio.addRadioListener()</CODE> method.
*
* Applications receive events on a listener until the listener
* is removed via the <CODE>MobileRadio.removeRadioListener()</CODE> method.
*
* @see javax.telephony.mobile.MobileRadioEvent
* @see javax.telephony.mobile.MobileRadioListener
* @version 02/26/99 1.4
*/
public interface MobileRadio {
/**
* Returns the current MobileRadio state.
*
* @return true if the radio is on, otherwise false.
* @exception MethodNotSupportedException can not access the current radio state.
*/
public boolean getRadioState() throws MethodNotSupportedException;
/**
* Set the MobileRadio state.
*
* The <CODE>MobileProvider</CODE> must be OUT_OF_SERVICE before the MobileRadio object
* may turn the physical radio off.
* After the radio is successfully turned off the <CODE>MobileRadio</CODE> state
* must be changed to reflect the radio off status.
*
* When the radio is turned off, no further network events will be generated
* and the radio signal level is set to zero, until the radio is reenabled.
* <p>
* When the radio is turned on,
* the <CODE>MobileProvider</CODE> can be in any valid state, depending
* on whether there are networks detected and subscription details
* are OK.
*
* @param state The desired radio state.
* @exception MethodNotSupportedException Indicates the radio state can not
* be manipulated on this implementation.
* @exception InvalidStateException Indicates the network service
* state cannot be changed due to current <CODE>MobileProvider</CODE> state.
*/
public void setRadioState(boolean state)
throws MethodNotSupportedException, InvalidStateException;
/**
* Returns the <CODE>MobileRadio</CODE> startup state at boot.
* @return The current radio startup state.
* @exception MethodNotSupportedException Indicates the radio
* state startup management capability is not supported.
*/
public boolean getRadioStartState()
throws MethodNotSupportedException;
/**
* Sets the <CODE>MobileRadio</CODE> startup state at boot.
*
* A possible required password will not be
* given here for security reasons!
*
* The password required should
* be given some other way, determined by native implementation,
* or at next time when a <CODE>MobileProvider</CODE> object is requested
* from the JtapiPeer.
*
* @param state The new radio startup state. True, if radio
* is turned on. Otherwise, false.
* @exception MethodNotSupportedException Indicates the radio
* state startup management is not supported.
* @exception InvalidStateException Indicates the network service
* startup state cannot be changed due to current platform state.
*/
public void setRadioStartState(boolean state)
throws MethodNotSupportedException,InvalidStateException;
/**
* Get the current radio signal level.
* <p>
* When the radio is turned off the signal level is set to zero.
*
* The radio signal is mapped to positive integer values from 1 to
* <CODE>getMaxSignalLevel</CODE>. In GSM networks the signal strength
* is mapped to the range 1-5. (e.g. Level 1 = 20%, Level 5 = 100%)
*
* @see #getMaxSignalLevel
* @return The current radio signal level.
*/
public int getSignalLevel();
/**
* Get the maximum radio signal level.
* @see #getSignalLevel
* @return The maximum radio signal level.
*/
public int getMaxSignalLevel();
/**
* Add a listener for <CODE>MobileRadio</CODE> events.
*
* @param listener The listener object to add.
* @exception MethodNotSupportedException This implementation does not generate events.
*/
public void addRadioListener(MobileRadioListener listener)
throws MethodNotSupportedException;
/**
* Remove a listener from the <CODE>MobileRadio</CODE>.
*
* @param listener The listener to remove.
*/
public void removeRadioListener(MobileRadioListener listener);
}
| kerr-huang/openss7 | src/java/javax/telephony/mobile/MobileRadio.java | Java | agpl-3.0 | 6,040 |
/**
* Copyright © MyCollab
*
* 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.mycollab.vaadin.ui;
import com.mycollab.vaadin.web.ui.WebThemes;
import com.vaadin.ui.*;
import org.vaadin.viritin.layouts.MCssLayout;
import org.vaadin.viritin.layouts.MVerticalLayout;
/**
* @author MyCollab Ltd
* @since 5.2.2
*/
public class FormContainer extends MVerticalLayout {
public FormContainer() {
this.withStyleName("form").withFullWidth().withMargin(false);
this.setDefaultComponentAlignment(Alignment.TOP_CENTER);
}
public FormSection addSection(String sectionName, ComponentContainer container) {
FormSection formSection = new FormSection(sectionName, container);
this.addComponent(formSection);
return formSection;
}
public void addSection(Component sectionHeader, ComponentContainer container) {
sectionHeader.addStyleName(WebThemes.FORM_SECTION);
sectionHeader.setWidth("100%");
container.setWidth("100%");
this.addComponent(sectionHeader);
this.addComponent(container);
}
}
| esofthead/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/ui/FormContainer.java | Java | agpl-3.0 | 1,719 |
package es.tid.pce.computingEngine.algorithms.vlan;
import es.tid.pce.computingEngine.ComputingRequest;
import es.tid.pce.computingEngine.algorithms.ComputingAlgorithm;
import es.tid.pce.computingEngine.algorithms.ComputingAlgorithmManager;
import es.tid.pce.computingEngine.algorithms.ComputingAlgorithmPreComputation;
import es.tid.pce.computingEngine.algorithms.multiLayer.OperationsCounter;
import es.tid.pce.server.wson.ReservationManager;
import es.tid.tedb.DomainTEDB;
import es.tid.tedb.TEDB;
import java.net.Inet4Address;
import java.util.Hashtable;
/**
* Copy paste from AURE_SSON_algorithmManager
* @author jaume
*
*/
public class Correct_BETTER_WLAN_algorithmManager implements ComputingAlgorithmManager {
BETTER_WLAN_algorithmPreComputation preComp;
private ReservationManager reservationManager;
@Override
public ComputingAlgorithm getComputingAlgorithm(
ComputingRequest pathReq, TEDB ted) {
BETTER_WLAN_algorithm algo = new BETTER_WLAN_algorithm(pathReq, ted,reservationManager);
algo.setPreComp(preComp);
return algo;
}
@Override
public void setReservationManager(ReservationManager reservationManager) {
this.reservationManager=reservationManager;
}
@Override
public void setPreComputation(ComputingAlgorithmPreComputation pc) {
// TODO Auto-generated method stub
this.preComp=(BETTER_WLAN_algorithmPreComputation) pc;
}
@Override
public ComputingAlgorithm getComputingAlgorithm(ComputingRequest pathReq,
TEDB ted, OperationsCounter OPcounter) {
// TODO Auto-generated method stub
return null;
}
@Override
public ComputingAlgorithm getComputingAlgorithm(ComputingRequest pathReq,
TEDB ted, Hashtable<Inet4Address,DomainTEDB> intraTEDBs) {
// TODO Auto-generated method stub
return null;
}
}
| asgamb/pce | src/main/java/es/tid/pce/computingEngine/algorithms/vlan/Correct_BETTER_WLAN_algorithmManager.java | Java | agpl-3.0 | 1,792 |
/*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling 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.
jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sapienter.jbilling.server.util;
import com.sapienter.jbilling.server.util.db.JbillingTableDAS;
import com.sapienter.jbilling.server.util.db.PreferenceDAS;
import com.sapienter.jbilling.server.util.db.PreferenceDTO;
import com.sapienter.jbilling.server.util.db.PreferenceTypeDAS;
import com.sapienter.jbilling.server.util.db.PreferenceTypeDTO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import java.math.BigDecimal;
public class PreferenceBL {
private static Logger LOG = Logger.getLogger(PreferenceBL.class);
private PreferenceDAS preferenceDas = null;
private PreferenceTypeDAS typeDas = null;
private PreferenceDTO preference = null;
private PreferenceTypeDTO type = null;
private JbillingTableDAS jbDAS = null;
public PreferenceBL() {
init();
}
public PreferenceBL(Integer preferenceId) {
init();
preference = preferenceDas.find(preferenceId);
}
public PreferenceBL(Integer entityId, Integer preferenceTypeId) {
init();
set(entityId, preferenceTypeId);
}
private void init() {
preferenceDas = new PreferenceDAS();
typeDas = new PreferenceTypeDAS();
jbDAS = (JbillingTableDAS) Context.getBean(Context.Name.JBILLING_TABLE_DAS);
}
public void set(Integer entityId, Integer typeId) throws EmptyResultDataAccessException {
LOG.debug("Looking for preference " + typeId + ", for entity " + entityId
+ " and table '" + Constants.TABLE_ENTITY + "'");
preference = preferenceDas.findByType_Row( typeId, entityId, Constants.TABLE_ENTITY);
type = typeDas.find(typeId);
// throw exception if there is no preference, or if the type does not have a
// default value that can be returned.
if (preference == null) {
if (type == null || type.getDefaultValue() == null) {
throw new EmptyResultDataAccessException("Could not find preference " + typeId, 1);
}
}
}
public void createUpdateForEntity(Integer entityId, Integer preferenceId, Integer value) {
createUpdateForEntity(entityId, preferenceId, (value != null ? value.toString() : ""));
}
public void createUpdateForEntity(Integer entityId, Integer preferenceId, BigDecimal value) {
createUpdateForEntity(entityId, preferenceId, (value != null ? value.toString() : ""));
}
public void createUpdateForEntity(Integer entityId, Integer preferenceId, String value) {
set(entityId, preferenceId);
if (preference != null) {
// update preference
preference.setValue(value);
} else {
// create a new preference
preference = new PreferenceDTO();
preference.setValue(value);
preference.setForeignId(entityId);
preference.setJbillingTable(jbDAS.findByName(Constants.TABLE_ENTITY));
preference.setPreferenceType(new PreferenceTypeDAS().find(preferenceId));
preference = preferenceDas.save(preference);
}
}
/**
* Returns the preference value if set. If the preference is null or has no
* set value (is blank), the preference type default value will be returned.
*
* @return preference value as a string
*/
public String getString() {
if (preference != null && StringUtils.isNotBlank(preference.getValue())) {
return preference.getValue();
} else {
return type != null ? type.getDefaultValue() : null;
}
}
public Integer getInt() {
String value = getString();
return value != null ? Integer.valueOf(value) : null;
}
public Float getFloat() {
String value = getString();
return value != null ? Float.valueOf(value) : null;
}
public BigDecimal getDecimal() {
String value = getString();
return value != null ? new BigDecimal(value) : null;
}
/**
* Returns the preference value as a string.
*
* @see #getString()
* @return string value of preference
*/
public String getValueAsString() {
return getString();
}
/**
* Returns the default value for the given preference type.
*
* @param preferenceTypeId preference type id
* @return default preference value
*/
public String getDefaultValue(Integer preferenceTypeId) {
type = typeDas.find(preferenceTypeId);
return type != null ? type.getDefaultValue() : null;
}
/**
* Returns true if the preference value is null, false if value is set.
*
* This method ignores the preference type default value, unlike {@link #getString()}
* and {@link #getValueAsString()} which will return the type default value if the
* preference itself is unset.
*
* @return true if preference value is null, false if value is set.
*/
public boolean isNull() {
return preference == null || preference.getValue() == null;
}
public PreferenceDTO getEntity() {
return preference;
}
}
| maduhu/jBilling | src/java/com/sapienter/jbilling/server/util/PreferenceBL.java | Java | agpl-3.0 | 6,202 |
package org.openlmis.restapi.controller;
import lombok.NoArgsConstructor;
import org.openlmis.restapi.domain.LoginInformation;
import org.openlmis.restapi.domain.RestLoginRequest;
import org.openlmis.restapi.response.RestResponse;
import org.openlmis.restapi.service.RestLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@NoArgsConstructor
public class RestLoginController extends BaseController {
@Autowired
private RestLoginService restLoginService;
@RequestMapping(value = "/rest-api/login", method = RequestMethod.POST, headers = ACCEPT_JSON)
public ResponseEntity<RestResponse> login(@RequestBody RestLoginRequest restLogin) {
try {
LoginInformation loginInformation = restLoginService.login(restLogin.getUsername(), restLogin.getPassword());
return RestResponse.response("userInformation", loginInformation);
} catch (BadCredentialsException e) {
return new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
}
} | OpenLMIS/open-lmis | modules/rest-api/src/main/java/org/openlmis/restapi/controller/RestLoginController.java | Java | agpl-3.0 | 1,436 |
package org.ethereum.net.rlpx.discover;
import org.junit.Test;
import java.util.Comparator;
import java.util.concurrent.TimeUnit;
/**
* Created by Anton Nashatyrev on 03.08.2015.
*/
public class QueueTest {
boolean exception = false;
@Test
public void simple() throws Exception {
final PeerConnectionTester.MutablePriorityQueue<String, String> queue =
new PeerConnectionTester.MutablePriorityQueue<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
final int threadCnt = 8;
final int elemCnt = 1000;
Runnable adder = new Runnable() {
@Override
public void run() {
try {
System.out.println("Adding...");
for (int i = 0; i < elemCnt && !exception; i++) {
queue.add("aaa" + i);
if (i % 100 == 0) Thread.sleep(10);
}
System.out.println("Done.");
} catch (Exception e) {
exception = true;
e.printStackTrace();
}
}
};
ThreadGroup tg = new ThreadGroup("test");
Thread t1[] = new Thread[threadCnt];
for (int i = 0; i < t1.length; i++) {
t1[i] = new Thread(tg, adder);
t1[i].start();
}
Runnable taker = new Runnable() {
@Override
public void run() {
try {
System.out.println("Taking...");
for (int i = 0; i < elemCnt && !exception; i++) {
queue.poll(1, TimeUnit.SECONDS);
}
System.out.println("OK: " + queue.size());
} catch (Exception e) {
exception = true;
e.printStackTrace();
}
}
};
Thread t2[] = new Thread[threadCnt];
for (int i = 0; i < t2.length; i++) {
t2[i] = new Thread(tg, taker);
t2[i].start();
}
for (Thread thread : t1) {
thread.join();
}
for (Thread thread : t2) {
thread.join();
}
if (exception) throw new RuntimeException("Test failed");
}
}
| dbenrosen/EtherPay | ethereumj-core/src/test/java/org/ethereum/net/rlpx/discover/QueueTest.java | Java | agpl-3.0 | 2,426 |
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.*/
/*
* Created on 2-jul-2003
*
*/
package org.pentaho.di.ui.trans.steps.sapinput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.database.SAPR3DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPreviewFactory;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.steps.sapinput.SapInputMeta;
import org.pentaho.di.trans.steps.sapinput.SapOutputField;
import org.pentaho.di.trans.steps.sapinput.SapParameter;
import org.pentaho.di.trans.steps.sapinput.SapType;
import org.pentaho.di.trans.steps.sapinput.sap.SAPConnection;
import org.pentaho.di.trans.steps.sapinput.sap.SAPConnectionFactory;
import org.pentaho.di.trans.steps.sapinput.sap.SAPField;
import org.pentaho.di.trans.steps.sapinput.sap.SAPFunction;
import org.pentaho.di.trans.steps.sapinput.sap.SAPFunctionSignature;
import org.pentaho.di.trans.steps.sapinput.sap.SAPLibraryTester;
import org.pentaho.di.ui.core.dialog.EnterNumberDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.ui.trans.step.TableItemInsertListener;
public class SapInputDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = SapInputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private CCombo wConnection;
private Label wlFunction;
private Text wFunction;
private Button wbFunction;
private Label wlInput;
private TableView wInput;
private Label wlOutput;
private TableView wOutput;
private Button wGet;
private Listener lsGet;
private SAPFunction function;
private SapInputMeta input;
// asc info
private Button wAbout;
private Link wAscLink;
/**
* List of ColumnInfo that should have the field names of the selected database table
*/
private List<ColumnInfo> inputFieldColumns = new ArrayList<ColumnInfo>();
/**
* List of ColumnInfo that should have the previous fields combo box
*/
private List<ColumnInfo> outputFieldColumns = new ArrayList<ColumnInfo>();
/**
* all fields from the previous steps
*/
private RowMetaInterface prevFields = null;
public SapInputDialog(Shell parent, Object in, TransMeta transMeta, String sname)
{
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(SapInputMeta)in;
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
if (!SAPLibraryTester.isJCoLibAvailable()) {
int style = SWT.ICON_ERROR;
MessageBox messageBox = new MessageBox(shell, style);
messageBox.setMessage(BaseMessages.getString(PKG, "SapInputDialog.JCoLibNotFound"));
messageBox.open();
// dispose();
// return stepname;
}
if (!SAPLibraryTester.isJCoImplAvailable()) {
int style = SWT.ICON_ERROR;
MessageBox messageBox = new MessageBox(shell, style);
messageBox.setMessage(BaseMessages.getString(PKG, "SapInputDialog.JCoImplNotFound"));
messageBox.open();
// dispose();
// return stepname;
}
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
ModifyListener lsConnectionMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
backupChanged = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "SapInputDialog.shell.Title")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "SapInputDialog.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
Control lastControl = wStepname;
// Connection line
//
wConnection = addConnectionLine(shell, lastControl, middle, margin);
List<String> items = new ArrayList<String>();
for (DatabaseMeta dbMeta : transMeta.getDatabases()) {
if (dbMeta.getDatabaseInterface() instanceof SAPR3DatabaseMeta) {
items.add(dbMeta.getName());
}
}
wConnection.setItems(items.toArray(new String[items.size()]));
if (input.getDatabaseMeta()==null && transMeta.nrDatabases()==1) wConnection.select(0);
wConnection.addModifyListener(lsConnectionMod);
lastControl = wConnection;
// Function
//
wlFunction=new Label(shell, SWT.RIGHT);
wlFunction.setText(BaseMessages.getString(PKG, "SapInputDialog.Function.Label")); //$NON-NLS-1$
props.setLook(wlFunction);
FormData fdlFunction = new FormData();
fdlFunction.left = new FormAttachment(0, 0);
fdlFunction.right = new FormAttachment(middle, -margin);
fdlFunction.top = new FormAttachment(lastControl, margin);
wlFunction.setLayoutData(fdlFunction);
wbFunction = new Button(shell, SWT.PUSH);
props.setLook(wbFunction);
wbFunction.setText(BaseMessages.getString(PKG, "SapInputDialog.FindFunctionButton.Label")); //$NON-NLS-1$
FormData fdbFunction = new FormData();
fdbFunction.right = new FormAttachment(100, 0);
fdbFunction.top = new FormAttachment(lastControl, margin);
wbFunction.setLayoutData(fdbFunction);
wbFunction.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { getFunction(); }});
wFunction=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFunction);
wFunction.addModifyListener(lsMod);
FormData fdFunction = new FormData();
fdFunction.left = new FormAttachment(middle, 0);
fdFunction.right = new FormAttachment(wbFunction, -margin);
fdFunction.top = new FormAttachment(lastControl, margin);
wFunction.setLayoutData(fdFunction);
lastControl = wFunction;
// The parameter input fields...
//
wlInput=new Label(shell, SWT.NONE);
wlInput.setText(BaseMessages.getString(PKG, "SapInputDialog.Input.Label")); //$NON-NLS-1$
props.setLook(wlInput);
FormData fdlInput = new FormData();
fdlInput.left = new FormAttachment(0, 0);
fdlInput.top = new FormAttachment(lastControl, margin);
wlInput.setLayoutData(fdlInput);
ColumnInfo[] ciKey=new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.Field"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[]{""}, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.SAPType"), ColumnInfo.COLUMN_TYPE_CCOMBO, SapType.getDescriptions()),
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.TableOrStruct"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.SAPParameterName"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.TargetType"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes()), //$NON-NLS-1$
};
inputFieldColumns.add(ciKey[0]);
wInput=new TableView(transMeta, shell,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL,
ciKey,
input.getParameters().size(),
lsMod,
props
);
FormData fdInput = new FormData();
fdInput.left = new FormAttachment(0, 0);
fdInput.top = new FormAttachment(wlInput, margin);
fdInput.right = new FormAttachment(100, 0);
fdInput.bottom= new FormAttachment(40, 0);
wInput.setLayoutData(fdInput);
lastControl = wInput;
// THE BUTTONS
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$
// wPreview = new Button(shell, SWT.PUSH);
// wPreview.setText(BaseMessages.getString(PKG, "System.Button.Preview")); //$NON-NLS-1$
wGet=new Button(shell, SWT.PUSH);
wGet.setText(BaseMessages.getString(PKG, "SapInputDialog.GetFields.Button")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$
wAbout=new Button(shell, SWT.PUSH);
wAbout.setText(BaseMessages.getString(PKG, "SapInputDialog.About.Button"));
// Preview not possible without inputRowSets in BaseStep.getRow()
// setButtonPositions(new Button[] { wOK, wPreview, wAbout , wGet, wCancel}, margin, null);
setButtonPositions(new Button[] { wOK, wAbout , wGet, wCancel}, margin, null);
// The output fields...
//
wlOutput=new Label(shell, SWT.NONE);
wlOutput.setText(BaseMessages.getString(PKG, "SapInputDialog.Output.Label")); //$NON-NLS-1$
props.setLook(wlOutput);
FormData fdlOutput = new FormData();
fdlOutput.left = new FormAttachment(0, 0);
fdlOutput.top = new FormAttachment(wInput, margin);
wlOutput.setLayoutData(fdlOutput);
ColumnInfo[] ciReturn=new ColumnInfo[] {
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.SAPField"), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[]{}, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.SAPType"), ColumnInfo.COLUMN_TYPE_CCOMBO, SapType.getDescriptions(), false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.TableOrStruct"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.NewName"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(BaseMessages.getString(PKG, "SapInputDialog.ColumnInfo.TargetType"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes()), //$NON-NLS-1$
};
outputFieldColumns.add(ciReturn[0]);
wOutput=new TableView(transMeta, shell,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL,
ciReturn,
input.getOutputFields().size(),
lsMod,
props
);
FormData fdOutput = new FormData();
fdOutput.left = new FormAttachment(0, 0);
fdOutput.top = new FormAttachment(wlOutput, margin);
fdOutput.right = new FormAttachment(100, 0);
fdOutput.bottom= new FormAttachment(wOK, -8*margin);
wOutput.setLayoutData(fdOutput);
lastControl = wOutput;
this.wAscLink = new Link(this.shell, SWT.NONE);
FormData fdAscLink = new FormData();
fdAscLink.left = new FormAttachment(0, 0);
fdAscLink.top = new FormAttachment(wOutput, margin);
wAscLink.setLayoutData(fdAscLink);
this.wAscLink.setText(BaseMessages.getString(PKG, "SapInputDialog.Provided.Info"));
lastControl = wAscLink;
// Add listeners
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
lsPreview = new Listener() { public void handleEvent(Event e) { preview(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
Listener lsAbout = new Listener() { public void handleEvent(Event e) { about(); } };
wOK.addListener (SWT.Selection, lsOK );
// wPreview.addListener(SWT.Selection, lsPreview);
wGet.addListener (SWT.Selection, lsGet );
wCancel.addListener(SWT.Selection, lsCancel);
this.wAbout.addListener(SWT.Selection, lsAbout);
this.wAscLink.addListener(SWT.Selection, new Listener() {
public void handleEvent(final Event event) {
Program.launch(event.text);
}
});
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wFunction.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
getData();
// Set the shell size, based upon previous time...
setSize();
input.setChanged(backupChanged);
setComboValues();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
protected void getFunction() {
DatabaseMeta databaseMeta = transMeta.findDatabase(wConnection.getText());
if (databaseMeta==null) {
showDatabaseWarning(false);
return;
}
SapFunctionBrowser browser = new SapFunctionBrowser(shell, transMeta, SWT.NONE, databaseMeta, wFunction.getText());
function = browser.open();
if (function!=null) {
get();
}
}
private void setComboValues() {
Runnable fieldLoader = new Runnable() {
public void run() {
try {
prevFields = transMeta.getPrevStepFields(stepname);
} catch (KettleException e) {
prevFields = new RowMeta();
String msg = BaseMessages.getString(PKG, "SapInputDialog.DoMapping.UnableToFindInput");
logError(msg);
}
String[] prevStepFieldNames = prevFields.getFieldNames();
Arrays.sort(prevStepFieldNames);
for (int i = 0; i < inputFieldColumns.size(); i++) {
ColumnInfo colInfo = (ColumnInfo) outputFieldColumns.get(i);
colInfo.setComboValues(prevStepFieldNames);
}
}
};
new Thread(fieldLoader).start();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
logDebug(BaseMessages.getString(PKG, "SapInputDialog.Log.GettingKeyInfo")); //$NON-NLS-1$
// The database connection name...
//
if (input.getDatabaseMeta()!=null) wConnection.setText(input.getDatabaseMeta().getName());
else if (transMeta.nrDatabases()==1)
{
wConnection.setText( transMeta.getDatabase(0).getName() );
}
// The name of the function to use
//
function = input.getFunction();
if (input.getFunction()!=null) {
wFunction.setText(Const.NVL(input.getFunction().getName(), "")); //$NON-NLS-1$
}
// The parameters...
//
for (int i=0;i<input.getParameters().size();i++) {
SapParameter parameter = input.getParameters().get(i);
TableItem item = wInput.table.getItem(i);
int colnr=1;
item.setText(colnr++, Const.NVL(parameter.getFieldName(), ""));
item.setText(colnr++, parameter.getSapType().getDescription());
item.setText(colnr++, Const.NVL(parameter.getTableName(), ""));
item.setText(colnr++, Const.NVL(parameter.getParameterName(), ""));
item.setText(colnr++, ValueMeta.getTypeDesc(parameter.getTargetType()));
}
wInput.setRowNums();
wInput.optWidth(true);
// The parameters...
//
for (int i=0;i<input.getOutputFields().size();i++) {
SapOutputField outputField = input.getOutputFields().get(i);
TableItem item = wOutput.table.getItem(i);
int colnr=1;
item.setText(colnr++, Const.NVL(outputField.getSapFieldName(), ""));
item.setText(colnr++, outputField.getSapType().getDescription());
item.setText(colnr++, Const.NVL(outputField.getTableName(), ""));
item.setText(colnr++, Const.NVL(outputField.getNewName(), ""));
item.setText(colnr++, ValueMeta.getTypeDesc(outputField.getTargetType()));
}
wOutput.setRowNums();
wOutput.optWidth(true);
}
private void cancel()
{
stepname=null;
input.setChanged(backupChanged);
dispose();
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
if (transMeta.findDatabase(wConnection.getText())==null)
{
int answer = showDatabaseWarning(true);
if (answer==SWT.CANCEL) {
return;
}
}
// check tablecount
Set<String> tables = new HashSet<String>();
int nrParameters = wOutput.nrNonEmpty();
for (int i=0;i<nrParameters;i++) {
TableItem item = wOutput.getNonEmpty(i);
String tableName = item.getText(3);
tables.add(tableName);
}
if (tables.size() > 1)
{
int answer = showMultipleOutputTablesWarning(true);
if (answer==SWT.CANCEL) {
return;
}
}
getInfo(input);
dispose();
}
// Preview the data
// unused
// preserve for later
private void preview()
{
// Create the XML input step
SapInputMeta oneMeta = new SapInputMeta();
getInfo(oneMeta);
TransMeta previewMeta = TransPreviewFactory.generatePreviewTransformation(transMeta, oneMeta, wStepname.getText());
transMeta.getVariable("Internal.Transformation.Filename.Directory");
previewMeta.getVariable("Internal.Transformation.Filename.Directory");
EnterNumberDialog numberDialog = new EnterNumberDialog(shell, props.getDefaultPreviewSize(), BaseMessages.getString(PKG, "CsvInputDialog.PreviewSize.DialogTitle"), BaseMessages.getString(PKG, "CsvInputDialog.PreviewSize.DialogMessage"));
int previewSize = numberDialog.open();
if (previewSize>0)
{
TransPreviewProgressDialog progressDialog = new TransPreviewProgressDialog(shell, previewMeta, new String[] { wStepname.getText() }, new int[] { previewSize } );
progressDialog.open();
Trans trans = progressDialog.getTrans();
String loggingText = progressDialog.getLoggingText();
if (!progressDialog.isCancelled())
{
if (trans.getResult()!=null && trans.getResult().getNrErrors()>0)
{
EnterTextDialog etd = new EnterTextDialog(shell, BaseMessages.getString(PKG, "System.Dialog.PreviewError.Title"),
BaseMessages.getString(PKG, "System.Dialog.PreviewError.Message"), loggingText, true );
etd.setReadOnly();
etd.open();
}
}
PreviewRowsDialog prd =new PreviewRowsDialog(shell, transMeta, SWT.NONE, wStepname.getText(), progressDialog.getPreviewRowsMeta(wStepname.getText()), progressDialog.getPreviewRows(wStepname.getText()), loggingText);
prd.open();
}
}
private void about() {
new SapInputAboutDialog(SapInputDialog.this.shell).open();
}
private int showDatabaseWarning(boolean includeCancel) {
MessageBox mb = new MessageBox(shell, SWT.OK | ( includeCancel ? SWT.CANCEL : SWT.NONE ) | SWT.ICON_ERROR );
mb.setMessage(BaseMessages.getString(PKG, "SapInputDialog.InvalidConnection.DialogMessage")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "SapInputDialog.InvalidConnection.DialogTitle")); //$NON-NLS-1$
return mb.open();
}
private int showMultipleOutputTablesWarning(boolean includeCancel) {
MessageBox mb = new MessageBox(shell, SWT.OK | ( includeCancel ? SWT.CANCEL : SWT.NONE ) | SWT.ICON_ERROR );
mb.setMessage(BaseMessages.getString(PKG, "SapInputDialog.MultipleOutputTables.DialogMessage")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "SapInputDialog.MultipleOutputTables.DialogTitle")); //$NON-NLS-1$
return mb.open();
}
private void getInfo(SapInputMeta meta) {
meta.setDatabaseMeta( transMeta.findDatabase(wConnection.getText()) );
meta.setFunction(function);
// Grab the parameters...
//
meta.getParameters().clear();
int nrParameters = wInput.nrNonEmpty();
for (int i=0;i<nrParameters;i++) {
TableItem item = wInput.getNonEmpty(i);
int colnr=1;
String fieldName = item.getText(colnr++);
SapType sapType = SapType.findTypeForDescription( item.getText(colnr++) );
String tableName = item.getText(colnr++);
String parameterName = item.getText(colnr++);
int targetType = ValueMeta.getType( item.getText(colnr++) );
meta.getParameters().add( new SapParameter(fieldName, sapType, tableName, parameterName, targetType) );
}
// and the output fields.
//
meta.getOutputFields().clear();
int nrFields = wOutput.nrNonEmpty();
for (int i=0;i<nrFields;i++) {
TableItem item = wOutput.getNonEmpty(i);
int colnr=1;
String sapFieldName = item.getText(colnr++);
SapType sapType = SapType.findTypeForDescription( item.getText(colnr++) );
String tableName = item.getText(colnr++);
String newName = item.getText(colnr++);
int targetType = ValueMeta.getType( item.getText(colnr++) );
meta.getOutputFields().add( new SapOutputField(sapFieldName, sapType, tableName, newName, targetType) );
}
}
private void get()
{
try
{
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null && !r.isEmpty())
{
TableItemInsertListener listener = new TableItemInsertListener()
{
public boolean tableItemInserted(TableItem tableItem, ValueMetaInterface v)
{
tableItem.setText(2, "=");
return true;
}
};
BaseStepDialog.getFieldsFromPrevious(r, wInput, 1, new int[] { 1, 3}, new int[] {}, -1, -1, listener);
}
DatabaseMeta databaseMeta = transMeta.findDatabase(wConnection.getText());
if (databaseMeta==null) {
showDatabaseWarning(false);
return;
}
// Fill in the parameters too
//
if (function!=null) {
wFunction.setText(function.getName());
if (wInput.nrNonEmpty()!=0 || wOutput.nrNonEmpty()!=0) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION);
mb.setMessage(BaseMessages.getString(PKG, "SapInputDialog.ClearInputOutput.DialogMessage")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "SapInputDialog.ClearInputOutput.DialogTitle")); //$NON-NLS-1$
int answer = mb.open();
if (answer==SWT.NO) {
return;
}
}
wInput.clearAll(false);
wOutput.clearAll(false);
Cursor hourGlass = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
SAPConnection sc = SAPConnectionFactory.create();
try {
shell.setCursor(hourGlass);
sc.open(databaseMeta);
SAPFunctionSignature signature = sc.getFunctionSignature(function);
// Populate the input view
// TODO: clean this up a bit, feels a bit messy
//
int rownr=0;
for (SAPField field : signature.getInput()) {
TableItem item;
if (rownr==0) {
item = wInput.table.getItem(0);
} else {
item = new TableItem(wInput.table, SWT.NONE);
}
rownr++;
SapType type = getSapType(field);
int colnr=1;
item.setText(colnr++, Const.NVL(field.getName(), ""));
item.setText(colnr++, type==null ? "" : type.getDescription());
item.setText(colnr++, Const.NVL(field.getTable(), ""));
item.setText(colnr++, Const.NVL(field.getName(), ""));
item.setText(colnr++, field.getTypePentaho());
}
wInput.setRowNums();
wInput.optWidth(true);
// Get the output rows
//
rownr=0;
for (SAPField field : signature.getOutput()) {
TableItem item;
if (rownr==0) {
item = wOutput.table.getItem(0);
} else {
item = new TableItem(wOutput.table, SWT.NONE);
}
rownr++;
SapType type = getSapType(field);
int colnr=1;
item.setText(colnr++, Const.NVL(field.getName(), ""));
item.setText(colnr++, type==null ? "" : type.getDescription());
item.setText(colnr++, Const.NVL(field.getTable(), ""));
item.setText(colnr++, Const.NVL(field.getName(), ""));
item.setText(colnr++, field.getTypePentaho());
}
wOutput.setRowNums();
wOutput.optWidth(true);
} catch(Exception e) {
throw new KettleException(e);
} finally {
sc.close();
shell.setCursor(null);
hourGlass.dispose();
}
}
}
catch(KettleException ke)
{
new ErrorDialog(shell, BaseMessages.getString(PKG, "SapInputDialog.GetFieldsFailed.DialogTitle"), BaseMessages.getString(PKG, "SapInputDialog.GetFieldsFailed.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
private SapType getSapType(SAPField field) {
String type = field.getType();
if (type!=null && type.startsWith("input_")) {
type = type.substring("input_".length());
} else if (type!=null && type.startsWith("output_")) {
type = type.substring("output_".length());
}
return SapType.findTypeForCode(type);
}
public String toString()
{
return stepname;
}
}
| dianhu/Kettle-Research | src-ui/org/pentaho/di/ui/trans/steps/sapinput/SapInputDialog.java | Java | lgpl-2.1 | 28,261 |
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Alexandre Russel
*
* $Id$
*/
package org.nuxeo.ecm.platform.annotations.repository.descriptor;
import org.nuxeo.common.xmap.annotation.XNode;
import org.nuxeo.common.xmap.annotation.XObject;
import org.nuxeo.ecm.platform.annotations.repository.service.SecurityManager;
/**
* @author Alexandre Russel
*
*/
@XObject("securityManager")
public class SecurityManagerDescriptor {
@XNode("@class")
private Class<? extends SecurityManager> klass;
public Class<? extends SecurityManager> getKlass() {
return klass;
}
public void setKlass(Class<? extends SecurityManager> klass) {
this.klass = klass;
}
}
| deadcyclo/nuxeo-features | annot/nuxeo-annot-repo/src/main/java/org/nuxeo/ecm/platform/annotations/repository/descriptor/SecurityManagerDescriptor.java | Java | lgpl-2.1 | 1,277 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2012, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------------------
* MonthDateFormatTests.java
* -------------------------
* (C) Copyright 2005-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 10-May-2005 : Version 1 (DG);
*
*/
package org.jfree.chart.axis;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
/**
* Some tests for the {@link MonthDateFormat} class.
*/
public class MonthDateFormatTest {
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
MonthDateFormat mf1 = new MonthDateFormat();
MonthDateFormat mf2 = new MonthDateFormat();
assertEquals(mf1, mf2);
assertEquals(mf2, mf1);
boolean[] showYear1 = new boolean [12];
showYear1[0] = true;
boolean[] showYear2 = new boolean [12];
showYear1[1] = true;
// time zone
mf1 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.US, 1,
showYear1, new SimpleDateFormat("yy"));
assertFalse(mf1.equals(mf2));
mf2 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.US, 1,
showYear1, new SimpleDateFormat("yy"));
assertEquals(mf1, mf2);
// locale
mf1 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 1,
showYear1, new SimpleDateFormat("yy"));
assertFalse(mf1.equals(mf2));
mf2 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 1,
showYear1, new SimpleDateFormat("yy"));
assertEquals(mf1, mf2);
// chars
mf1 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 2,
showYear1, new SimpleDateFormat("yy"));
assertFalse(mf1.equals(mf2));
mf2 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 2,
showYear1, new SimpleDateFormat("yy"));
assertEquals(mf1, mf2);
// showYear[]
mf1 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 2,
showYear2, new SimpleDateFormat("yy"));
assertFalse(mf1.equals(mf2));
mf2 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 2,
showYear2, new SimpleDateFormat("yy"));
assertEquals(mf1, mf2);
// yearFormatter
mf1 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 2,
showYear2, new SimpleDateFormat("yyyy"));
assertFalse(mf1.equals(mf2));
mf2 = new MonthDateFormat(TimeZone.getTimeZone("PST"), Locale.FRANCE, 2,
showYear2, new SimpleDateFormat("yyyy"));
assertEquals(mf1, mf2);
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashCode() {
MonthDateFormat mf1 = new MonthDateFormat();
MonthDateFormat mf2 = new MonthDateFormat();
assertEquals(mf1, mf2);
int h1 = mf1.hashCode();
int h2 = mf2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
MonthDateFormat mf1 = new MonthDateFormat();
MonthDateFormat mf2 = (MonthDateFormat) mf1.clone();
assertNotSame(mf1, mf2);
assertSame(mf1.getClass(), mf2.getClass());
assertEquals(mf1, mf2);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() throws IOException, ClassNotFoundException {
MonthDateFormat mf1 = new MonthDateFormat();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(mf1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
MonthDateFormat mf2 = (MonthDateFormat) in.readObject();
in.close();
assertEquals(mf1, mf2);
}
}
| oskopek/jfreechart-fse | src/test/java/org/jfree/chart/axis/MonthDateFormatTest.java | Java | lgpl-2.1 | 6,006 |
/*
* (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* <a href="mailto:[email protected]">Tiry</a>
*/
package org.nuxeo.ecm.automation.core.operations.traces;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Context;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.automation.core.annotations.Param;
import org.nuxeo.ecm.automation.core.trace.Trace;
import org.nuxeo.ecm.automation.core.trace.TracerFactory;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.runtime.api.Framework;
/**
* @author <a href="mailto:[email protected]">Tiry</a>
* @since 5.8
*/
@Operation(id = AutomationTraceGetOperation.ID, category = Constants.CAT_EXECUTION, label = "Traces.getTrace", description = "Retrieve trace associated to a Chain or an Operation", addToStudio = false)
public class AutomationTraceGetOperation {
public static final String ID = "Traces.Get";
@Param(name = "traceKey", required = false)
protected String traceKey = null;
@Param(name = "index", required = false)
protected int index = -1;
@Context
protected OperationContext ctx;
protected boolean canManageTraces() {
NuxeoPrincipal principal = (NuxeoPrincipal) ctx.getPrincipal();
return principal != null && (principal.isAdministrator());
}
@OperationMethod
public String run() {
if (canManageTraces()) {
return null;
}
TracerFactory tracerFactory = Framework.getLocalService(TracerFactory.class);
if (traceKey == null) {
Trace trace = tracerFactory.getLastErrorTrace();
if (trace != null) {
return trace.getFormattedText();
} else {
return "no previous error trace found";
}
} else {
Trace trace = tracerFactory.getTrace(traceKey);
if (trace != null) {
return trace.getFormattedText();
} else {
return "no trace found";
}
}
}
}
| deadcyclo/nuxeo-features | nuxeo-automation/nuxeo-automation-core/src/main/java/org/nuxeo/ecm/automation/core/operations/traces/AutomationTraceGetOperation.java | Java | lgpl-2.1 | 2,764 |
/*
* Copyright 2006-2011 the original author or 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 org.intermine.bio.dataloader.job;
/**
*
* @since 2.2
*/
@SuppressWarnings("serial")
public class StepBuilderException extends RuntimeException {
public StepBuilderException(Exception e) {
super(e);
}
}
| Arabidopsis-Information-Portal/intermine | bio/sources/araport/araport-chado-db/main/src/org/intermine/bio/dataloader/job/StepBuilderException.java | Java | lgpl-2.1 | 843 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.jsp.search.config;
/** The interface a field facet configuration must implement. */
public interface I_CmsSearchConfigurationFacetField extends I_CmsSearchConfigurationFacet {
/** Returns the index field that is used for the facet.
* @return The index field that is used for the facet.
*/
String getField();
/** Returns the maximal number of entries that should be shown in the facet.
* @return The maximal number of entries that should be shown in the facet. (Solr: facet.limit)
*/
Integer getLimit();
/** Returns the prefix all entries of a facet must match.
* @return The prefix all entries of a facet must match. (Solr: facet.prefix)
*/
String getPrefix();
/** Returns the sort order that should be used for the facet entries (either "count" or "index").
* @return The sort order that should be used for the facet entries (either "count" or "index"). (Solr: facet.sort)
*/
SortOrder getSortOrder();
/** Returns the (modified) filter query that should be send as filter query when a facet entry is checked.
* @param facetValue The modifier that should be applied the each filter query appended when checking a facet entry.
* The modifier can contain the macro "%(value)" that is substituted by the facet entry's value.
* If the modifier is <code>null</code>, the unmodified filter query is returned.
* @return The filter query's value.
*/
String modifyFilterQuery(String facetValue);
}
| ggiudetti/opencms-core | src/org/opencms/jsp/search/config/I_CmsSearchConfigurationFacetField.java | Java | lgpl-2.1 | 2,639 |
/*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs;
public interface BugAnnotationVisitor {
public void visitClassAnnotation(ClassAnnotation classAnnotation);
public void visitFieldAnnotation(FieldAnnotation fieldAnnotation);
public void visitMethodAnnotation(MethodAnnotation methodAnnotation);
public void visitIntAnnotation(IntAnnotation intAnnotation);
public void visitStringAnnotation(StringAnnotation stringAnnotation);
public void visitLocalVariableAnnotation(LocalVariableAnnotation localVariableAnnotation);
public void visitTypeAnnotation(TypeAnnotation typeAnnotation);
public void visitSourceLineAnnotation(SourceLineAnnotation sourceLineAnnotation);
}
| sewe/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/BugAnnotationVisitor.java | Java | lgpl-2.1 | 1,522 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.gwt.shared;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* This class represents the result of a "return link" lookup, which is what happens if the user
* clicks the "go to last page" button in the sitemap editor. It contains a link string (possibly null)
* and a status to indicate possible errors.<p>
*
* @since 8.0.0
*/
public class CmsReturnLinkInfo implements IsSerializable {
/**
* The moved status.<p>
*/
public enum Status {
/** The link was successfully looked up. */
ok,
/** The resource(s) was not found. */
notfound
}
/** The return link (null if not found). */
private String m_link;
/** The status of the lookup operation. */
private Status m_status;
/**
* Creates a new instance.<p>
*
* @param link the return link
* @param status the link lookup status
*/
public CmsReturnLinkInfo(String link, Status status) {
m_link = link;
m_status = status;
}
/**
* Protected default constructor for serialization.<p>
*/
protected CmsReturnLinkInfo() {
// do nothing
}
/**
* Returns the return link.<p>
*
* @return the return link
*/
public String getLink() {
return m_link;
}
/**
* Returns the link lookup status.<p>
*
* @return the link lookup status
*/
public Status getStatus() {
return m_status;
}
}
| it-tavis/opencms-core | src/org/opencms/gwt/shared/CmsReturnLinkInfo.java | Java | lgpl-2.1 | 2,613 |
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.tag;
import lucee.commons.io.res.Resource;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.PageException;
import lucee.runtime.ext.tag.TagImpl;
import lucee.runtime.net.mail.MailClient;
import lucee.runtime.op.Caster;
import lucee.runtime.type.util.ArrayUtil;
import lucee.runtime.type.util.ListUtil;
/**
* Retrieves and deletes e-mail messages from a POP mail server.
*/
public abstract class _Mail extends TagImpl {
private String server;
private int port=-1;
private String username;
private String password;
private String action="getheaderonly";
private String name;
private String[] messageNumber;
private String[] uid;
private Resource attachmentPath;
private int timeout=60;
private int startrow=1;
private int maxrows=-1;
private boolean generateUniqueFilenames=false;
@Override
public void release() {
port=-1;
username=null;
password=null;
action="getheaderonly";
name=null;
messageNumber=null;
uid=null;
attachmentPath=null;
timeout=60;
startrow=1;
maxrows=-1;
generateUniqueFilenames=false;
super.release();
}
/**
* @param server The server to set.
*/
public void setServer(String server) {
this.server = server;
}
/**
* @param port The port to set.
*/
public void setPort(double port) {
this.port = (int)port;
}
/**
* @param username The username to set.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @param password The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @param action The action to set.
*/
public void setAction(String action) {
this.action = action.trim().toLowerCase();
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @param messageNumber The messageNumber to set.
* @throws PageException
*/
public void setMessagenumber(String messageNumber) throws PageException {
this.messageNumber = ArrayUtil.trim(ListUtil.toStringArray(ListUtil.listToArrayRemoveEmpty(messageNumber,',')));
if(this.messageNumber.length==0)this.messageNumber=null;
}
/**
* @param uid The uid to set.
* @throws PageException
*/
public void setUid(String uid) throws PageException {
this.uid = ArrayUtil.trim(ListUtil.toStringArray(ListUtil.listToArrayRemoveEmpty(uid,',')));
if(this.uid.length==0)this.uid=null;
}
/**
* @param attachmentPath The attachmentPath to set.
* @throws PageException
*/
public void setAttachmentpath(String attachmentPath) throws PageException {
//try {
Resource attachmentDir=pageContext.getConfig().getResource(attachmentPath);
if(!attachmentDir.exists() && !attachmentDir.mkdir()) {
attachmentDir=pageContext.getConfig().getTempDirectory().getRealResource(attachmentPath);
if(!attachmentDir.exists() && !attachmentDir.mkdir())
throw new ApplicationException("directory ["+attachmentPath+"] doesent exist and can't created");
}
if(!attachmentDir.isDirectory())throw new ApplicationException("file ["+attachmentPath+"] is not a directory");
pageContext.getConfig().getSecurityManager().checkFileLocation(attachmentDir);
this.attachmentPath = attachmentDir;
/*}
catch(IOException ioe) {
throw Caster.toPageException(ioe);
}*/
}
/**
* @param maxrows The maxrows to set.
*/
public void setMaxrows(double maxrows) {
this.maxrows = (int)maxrows;
}
/**
* @param startrow The startrow to set.
*/
public void setStartrow(double startrow) {
this.startrow = (int)startrow;
}
/**
* @param timeout The timeout to set.
*/
public void setTimeout(double timeout) {
this.timeout = (int)timeout;
}
/**
* @param generateUniqueFilenames The generateUniqueFilenames to set.
*/
public void setGenerateuniquefilenames(boolean generateUniqueFilenames) {
this.generateUniqueFilenames = generateUniqueFilenames;
}
/**
* @param debug The debug to set.
*/
public void setDebug(boolean debug) {
// does nothing this.debug = debug;
}
@Override
public int doStartTag() throws PageException {
// check attrs
if(port==-1)port=getDefaultPort();
//PopClient client = new PopClient(server,port,username,password);
MailClient client = MailClient.getInstance(getType(),server,port,username,password);
client.setTimeout(timeout*1000);
client.setMaxrows(maxrows);
if(startrow>1)client.setStartrow(startrow-1);
client.setUniqueFilenames(generateUniqueFilenames);
if(attachmentPath!=null)client.setAttachmentDirectory(attachmentPath);
if(uid!=null)messageNumber=null;
try {
client.connect();
if(action.equals("getheaderonly")) {
required(getTagName(),action,"name",name);
pageContext.setVariable(name,client.getMails(messageNumber,uid,false));
}
else if(action.equals("getall")) {
required(getTagName(),action,"name",name);
pageContext.setVariable(name,client.getMails(messageNumber,uid,true));
}
else if(action.equals("delete")) {
client.deleteMails(messageNumber,uid);
}
else throw new ApplicationException("invalid value for attribute action, valid values are [getHeaderOnly,getAll,delete]");
}
catch(Exception e) {
throw Caster.toPageException(e);
}
finally{
client.disconnectEL();
}
return SKIP_BODY;
}
protected abstract int getType();
protected abstract int getDefaultPort();
protected abstract String getTagName();
} | lucee/unoffical-Lucee-no-jre | source/java/core/src/lucee/runtime/tag/_Mail.java | Java | lgpl-2.1 | 7,053 |
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2014 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 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 org.lenskit.basic;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import it.unimi.dsi.fastutil.longs.LongSet;
import it.unimi.dsi.fastutil.longs.LongSets;
import org.lenskit.data.dao.ItemDAO;
import org.lenskit.data.dao.UserEventDAO;
import org.lenskit.data.events.Event;
import org.lenskit.data.history.UserHistory;
import org.lenskit.api.ItemScorer;
import org.lenskit.api.Result;
import org.lenskit.api.ResultList;
import org.lenskit.api.ResultMap;
import org.lenskit.results.Results;
import org.lenskit.util.collections.LongUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Recommender that recommends the top N items by a scorer.
* Implements all methods required by {@link AbstractItemRecommender}. The
* default exclude set is all items rated by the user.
*
* <p>Recommendations are returned in descending order of score.
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
* @since 1.1
*/
public class TopNItemRecommender extends AbstractItemRecommender {
private static final Logger logger = LoggerFactory.getLogger(TopNItemRecommender.class);
protected final UserEventDAO userEventDAO;
protected final ItemDAO itemDAO;
protected final ItemScorer scorer;
@Inject
public TopNItemRecommender(UserEventDAO uedao, ItemDAO idao, ItemScorer scorer) {
userEventDAO = uedao;
itemDAO = idao;
this.scorer = scorer;
}
public ItemScorer getScorer() {
return scorer;
}
/**
* Implement recommendation by calling {@link ItemScorer#score(long, Collection)} and sorting
* the results by score. This method uses {@link #getDefaultExcludes(long)} to get the default
* exclude set for the user, if none is provided.
*/
@Override
protected List<Long> recommend(long user, int n, LongSet candidates, LongSet exclude) {
candidates = getEffectiveCandidates(user, candidates, exclude);
logger.debug("Computing {} recommendations for user {} from {} candidates",
n, user, candidates.size());
// FIXME Make this more efficient - don't allocate extra BasicResults
Map<Long, Double> scores = scorer.score(user, candidates);
Iterable<Result> res = Iterables.transform(scores.entrySet(), Results.fromEntryFunction());
return getTopNResults(n, res).idList();
}
/**
* Implement recommendation by calling {@link ItemScorer#scoreWithDetails(long, Collection)} and sorting
* the results. This method uses {@link #getDefaultExcludes(long)} to get the default
* exclude set for the user, if none is provided.
*/
@Override
protected ResultList recommendWithDetails(long user, int n, LongSet candidates, LongSet exclude) {
candidates = getEffectiveCandidates(user, candidates, exclude);
logger.debug("Computing {} recommendations for user {} from {} candidates",
n, user, candidates.size());
ResultMap scores = scorer.scoreWithDetails(user, candidates);
return getTopNResults(n, scores);
}
private LongSet getEffectiveCandidates(long user, LongSet candidates, LongSet exclude) {
if (candidates == null) {
candidates = getPredictableItems(user);
}
if (exclude == null) {
exclude = getDefaultExcludes(user);
}
if (!exclude.isEmpty()) {
candidates = LongUtils.setDifference(candidates, exclude);
}
return candidates;
}
@Nonnull
private ResultList getTopNResults(int n, Iterable<Result> scores) {
Ordering<Result> ord = Results.scoreOrder();
List<Result> topN;
if (n < 0) {
topN = ord.reverse().immutableSortedCopy(scores);
} else {
topN = ord.greatestOf(scores, n);
}
return Results.newResultList(topN);
}
/**
* Get the default exclude set for a user. The base implementation gets
* all the items they have interacted with.
*
* @param user The user ID.
* @return The set of items to exclude.
*/
protected LongSet getDefaultExcludes(long user) {
return getDefaultExcludes(userEventDAO.getEventsForUser(user));
}
/**
* Get the default exclude set for a user. The base implementation returns
* all the items they have interacted with (from {@link UserHistory#itemSet()}).
*
* @param user The user history.
* @return The set of items to exclude.
*/
protected LongSet getDefaultExcludes(@Nullable UserHistory<? extends Event> user) {
if (user == null) {
return LongSets.EMPTY_SET;
} else {
return user.itemSet();
}
}
/**
* Determine the items for which predictions can be made for a certain user.
* This implementation is naive and asks the DAO for all items; subclasses
* should override it with something more efficient if practical.
*
* @param user The user's ID.
* @return All items for which predictions can be generated for the user.
*/
protected LongSet getPredictableItems(long user) {
return itemDAO.getItemIds();
}
}
| amaliujia/lenskit | lenskit-core/src/main/java/org/lenskit/basic/TopNItemRecommender.java | Java | lgpl-2.1 | 6,408 |
package test.icecaptools;
import icecaptools.DefaultObserver;
import icecaptools.FieldOffsetCalculator;
import icecaptools.compiler.FieldInfo;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class TestObjectSize {
@Test
public void testSimple() throws Exception {
List<String> classes = new LinkedList<String>();
DefaultObserver observer = new DefaultObserver();
String className = "test.icecapvm.minitests.TestVolatile2$VolatileObject";
classes.add(className);
FieldOffsetCalculator foCalc = new FieldOffsetCalculator();
foCalc.calculate(classes.iterator(), observer);
List<FieldInfo> objectFields = foCalc.getObjectFields(className);
Assert.assertEquals(5, objectFields.size());
Iterator<FieldInfo> fields = objectFields.iterator();
while (fields.hasNext())
{
FieldInfo fieldInfo = fields.next();
if (fieldInfo.getName().equals("x"))
{
Assert.assertEquals(0, fieldInfo.getOffset());
}
else if (fieldInfo.getName().equals("y"))
{
Assert.assertEquals(8, fieldInfo.getOffset());
}
else if (fieldInfo.getName().equals("z"))
{
}
}
}
}
| lgassman/embebidos-unq | icecaptools/src/test/icecaptools/TestObjectSize.java | Java | lgpl-3.0 | 1,428 |
/**
* Copyright (C) 2013 Inera AB (http://www.inera.se)
*
* This file is part of Inera Axel (http://code.google.com/p/inera-axel).
*
* Inera Axel 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.
*
* Inera Axel is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package se.inera.axel.shs.xml.agreement;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.io.Serializable;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "intervaltime")
public class Intervaltime implements Serializable {
@XmlAttribute(name = "day")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String day;
@XmlAttribute(name = "hour")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String hour;
@XmlAttribute(name = "min")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String min;
/**
* Gets the value of the day property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDay() {
return day;
}
/**
* Sets the value of the day property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDay(String value) {
this.day = value;
}
/**
* Gets the value of the hour property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHour() {
return hour;
}
/**
* Sets the value of the hour property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHour(String value) {
this.hour = value;
}
/**
* Gets the value of the min property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMin() {
return min;
}
/**
* Sets the value of the min property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMin(String value) {
this.min = value;
}
}
| sklaxel/inera-axel | shs/shs-protocol/src/main/java/se/inera/axel/shs/xml/agreement/Intervaltime.java | Java | lgpl-3.0 | 2,851 |
package org.cassandraunit;
import com.datastax.driver.core.ResultSet;
import org.cassandraunit.dataset.cql.ClassPathCQLDataSet;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
*
* @author Laurent Liger
*
*/
public class CQLDataLoadTestWithBlankLineEndings {
@Rule
public CassandraCQLUnit cassandraCQLUnit = new CassandraCQLUnit(new ClassPathCQLDataSet("cql/statementsWithBlankEndings.cql", "mykeyspace"));
@Test
public void testCQLDataAreInPlace() throws Exception {
ResultSet result = cassandraCQLUnit.session.execute("select * from testCQLTable WHERE id=1690e8da-5bf8-49e8-9583-4dff8a570737");
String val = result.iterator().next().getString("value");
assertEquals("Cql loaded string",val);
}
}
| glaucio-melo-movile/cassandra-unit | cassandra-unit/src/test/java/org/cassandraunit/CQLDataLoadTestWithBlankLineEndings.java | Java | lgpl-3.0 | 794 |
package modelos;
/**
*
* @author sabik
*/
public class Cliente implements MockPersistente {
Integer id;
String nombre;
Float ingresosMensuales;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Float getIngresosMensuales() {
return ingresosMensuales;
}
public void setIngresosMensuales(Float ingresosMensuales) {
this.ingresosMensuales = ingresosMensuales;
}
@Override
public Cliente find(Integer idCliente) {
return null;
}
}
| ivansabik/tutorial-junit | etapa-5/src/modelos/Cliente.java | Java | unlicense | 719 |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template const_set_serializer.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver10;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.projectfloodlight.openflow.protocol.OFPortConfig;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import java.util.EnumSet;
import java.util.Collections;
public class OFPortConfigSerializerVer10 {
public final static int PORT_DOWN_VAL = 0x1;
public final static int NO_STP_VAL = 0x2;
public final static int NO_RECV_VAL = 0x4;
public final static int NO_RECV_STP_VAL = 0x8;
public final static int NO_FLOOD_VAL = 0x10;
public final static int NO_FWD_VAL = 0x20;
public final static int NO_PACKET_IN_VAL = 0x40;
public final static int BSN_MIRROR_DEST_VAL = (int) 0x80000000;
public static Set<OFPortConfig> readFrom(ByteBuf bb) throws OFParseError {
try {
return ofWireValue(bb.readInt());
} catch (IllegalArgumentException e) {
throw new OFParseError(e);
}
}
public static void writeTo(ByteBuf bb, Set<OFPortConfig> set) {
bb.writeInt(toWireValue(set));
}
public static void putTo(Set<OFPortConfig> set, PrimitiveSink sink) {
sink.putInt(toWireValue(set));
}
public static Set<OFPortConfig> ofWireValue(int val) {
EnumSet<OFPortConfig> set = EnumSet.noneOf(OFPortConfig.class);
if((val & PORT_DOWN_VAL) != 0)
set.add(OFPortConfig.PORT_DOWN);
if((val & NO_STP_VAL) != 0)
set.add(OFPortConfig.NO_STP);
if((val & NO_RECV_VAL) != 0)
set.add(OFPortConfig.NO_RECV);
if((val & NO_RECV_STP_VAL) != 0)
set.add(OFPortConfig.NO_RECV_STP);
if((val & NO_FLOOD_VAL) != 0)
set.add(OFPortConfig.NO_FLOOD);
if((val & NO_FWD_VAL) != 0)
set.add(OFPortConfig.NO_FWD);
if((val & NO_PACKET_IN_VAL) != 0)
set.add(OFPortConfig.NO_PACKET_IN);
if((val & BSN_MIRROR_DEST_VAL) != 0)
set.add(OFPortConfig.BSN_MIRROR_DEST);
return Collections.unmodifiableSet(set);
}
public static int toWireValue(Set<OFPortConfig> set) {
int wireValue = 0;
for(OFPortConfig e: set) {
switch(e) {
case PORT_DOWN:
wireValue |= PORT_DOWN_VAL;
break;
case NO_STP:
wireValue |= NO_STP_VAL;
break;
case NO_RECV:
wireValue |= NO_RECV_VAL;
break;
case NO_RECV_STP:
wireValue |= NO_RECV_STP_VAL;
break;
case NO_FLOOD:
wireValue |= NO_FLOOD_VAL;
break;
case NO_FWD:
wireValue |= NO_FWD_VAL;
break;
case NO_PACKET_IN:
wireValue |= NO_PACKET_IN_VAL;
break;
case BSN_MIRROR_DEST:
wireValue |= BSN_MIRROR_DEST_VAL;
break;
default:
throw new IllegalArgumentException("Illegal enum value for type OFPortConfig in version 1.0: " + e);
}
}
return wireValue;
}
}
| floodlight/loxigen-artifacts | openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver10/OFPortConfigSerializerVer10.java | Java | apache-2.0 | 4,603 |
/*
* Copyright 2003-2018 Dave Griffith, Bas Leijdekkers
*
* 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.siyeh.ig.memory;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Query;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class InnerClassMayBeStaticInspection extends BaseInspection {
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("inner.class.may.be.static.display.name");
}
@Override
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message("inner.class.may.be.static.problem.descriptor");
}
@Override
public boolean runForWholeFile() {
return true;
}
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
return new InnerClassMayBeStaticFix();
}
private static class InnerClassMayBeStaticFix extends InspectionGadgetsFix {
@Override
@NotNull
public String getFamilyName() {
return InspectionGadgetsBundle.message("make.static.quickfix");
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
final PsiJavaToken classNameToken = (PsiJavaToken)descriptor.getPsiElement();
final PsiClass innerClass = (PsiClass)classNameToken.getParent();
if (innerClass == null) {
return;
}
final SearchScope useScope = innerClass.getUseScope();
final Query<PsiReference> query = ReferencesSearch.search(innerClass, useScope);
final Collection<PsiReference> references = query.findAll();
final List<PsiElement> elements = new ArrayList<>(references.size() + 1);
for (PsiReference reference : references) {
elements.add(reference.getElement());
}
elements.add(innerClass);
if (!FileModificationService.getInstance().preparePsiElementsForWrite(elements)) {
return;
}
WriteAction.run(() -> makeStatic(innerClass, references));
}
private static void makeStatic(PsiClass innerClass, Collection<? extends PsiReference> references) {
final Project project = innerClass.getProject();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
for (final PsiReference reference : references) {
final PsiElement element = reference.getElement();
final PsiElement parent = element.getParent();
if (!(parent instanceof PsiNewExpression)) {
continue;
}
final PsiNewExpression newExpression = (PsiNewExpression)parent;
final PsiJavaCodeReferenceElement classReference = newExpression.getClassReference();
if (classReference == null) {
continue;
}
final PsiExpressionList argumentList = newExpression.getArgumentList();
if (argumentList == null) {
continue;
}
final PsiReferenceParameterList parameterList = classReference.getParameterList();
final String genericParameters = parameterList != null ? parameterList.getText() : "";
final PsiExpression expression = factory
.createExpressionFromText("new " + classReference.getQualifiedName() + genericParameters + argumentList.getText(), innerClass);
codeStyleManager.shortenClassReferences(newExpression.replace(expression));
}
final PsiModifierList modifiers = innerClass.getModifierList();
if (modifiers == null) {
return;
}
modifiers.setModifierProperty(PsiModifier.STATIC, true);
}
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new InnerClassMayBeStaticVisitor();
}
private static class InnerClassMayBeStaticVisitor extends BaseInspectionVisitor {
@Override
public void visitClass(@NotNull PsiClass aClass) {
if (aClass.getContainingClass() != null && !aClass.hasModifierProperty(PsiModifier.STATIC)) {
return;
}
if (PsiUtil.isLocalOrAnonymousClass(aClass)) {
return;
}
final PsiClass[] innerClasses = aClass.getInnerClasses();
for (final PsiClass innerClass : innerClasses) {
if (innerClass.hasModifierProperty(PsiModifier.STATIC)) {
continue;
}
final InnerClassReferenceVisitor visitor = new InnerClassReferenceVisitor(innerClass);
innerClass.accept(visitor);
if (!visitor.canInnerClassBeStatic()) {
continue;
}
registerClassError(innerClass);
}
}
}
} | mdanielwork/intellij-community | plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/memory/InnerClassMayBeStaticInspection.java | Java | apache-2.0 | 5,784 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.openapi.roots.impl;
import com.intellij.openapi.CompositeDisposable;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.LibraryEx;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author dsl
*/
public class RootModelImpl extends RootModelBase implements ModifiableRootModel {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.impl.RootModelImpl");
private final Set<ContentEntry> myContent = new TreeSet<>(ContentComparator.INSTANCE);
private final List<OrderEntry> myOrderEntries = new Order();
// cleared by myOrderEntries modification, see Order
@Nullable private OrderEntry[] myCachedOrderEntries;
@NotNull private final ModuleLibraryTable myModuleLibraryTable;
final ModuleRootManagerImpl myModuleRootManager;
private boolean myWritable;
private final VirtualFilePointerManager myFilePointerManager;
private boolean myDisposed = false;
private final Set<ModuleExtension> myExtensions = new TreeSet<>();
private final RootConfigurationAccessor myConfigurationAccessor;
private final ProjectRootManagerImpl myProjectRootManager;
// have to register all child disposables using this fake object since all clients just call ModifiableModel.dispose()
private final CompositeDisposable myDisposable = new CompositeDisposable();
RootModelImpl(@NotNull ModuleRootManagerImpl moduleRootManager,
ProjectRootManagerImpl projectRootManager,
VirtualFilePointerManager filePointerManager) {
myModuleRootManager = moduleRootManager;
myProjectRootManager = projectRootManager;
myFilePointerManager = filePointerManager;
myWritable = false;
addSourceOrderEntries();
myModuleLibraryTable = new ModuleLibraryTable(this, myProjectRootManager);
for (ModuleExtension extension : Extensions.getExtensions(ModuleExtension.EP_NAME, moduleRootManager.getModule())) {
ModuleExtension model = extension.getModifiableModel(false);
registerOnDispose(model);
myExtensions.add(model);
}
myConfigurationAccessor = new RootConfigurationAccessor();
}
private void addSourceOrderEntries() {
myOrderEntries.add(new ModuleSourceOrderEntryImpl(this));
}
RootModelImpl(@NotNull Element element,
@NotNull ModuleRootManagerImpl moduleRootManager,
ProjectRootManagerImpl projectRootManager,
VirtualFilePointerManager filePointerManager, boolean writable) throws InvalidDataException {
myProjectRootManager = projectRootManager;
myFilePointerManager = filePointerManager;
myModuleRootManager = moduleRootManager;
myModuleLibraryTable = new ModuleLibraryTable(this, myProjectRootManager);
for (Element child : element.getChildren(ContentEntryImpl.ELEMENT_NAME)) {
myContent.add(new ContentEntryImpl(child, this));
}
boolean moduleSourceAdded = false;
for (Element child : element.getChildren(OrderEntryFactory.ORDER_ENTRY_ELEMENT_NAME)) {
final OrderEntry orderEntry = OrderEntryFactory.createOrderEntryByElement(child, this, myProjectRootManager);
if (orderEntry instanceof ModuleSourceOrderEntry) {
if (moduleSourceAdded) continue;
moduleSourceAdded = true;
}
myOrderEntries.add(orderEntry);
}
if (!moduleSourceAdded) {
myOrderEntries.add(new ModuleSourceOrderEntryImpl(this));
}
myWritable = writable;
RootModelImpl originalRootModel = moduleRootManager.getRootModel();
for (ModuleExtension extension : originalRootModel.myExtensions) {
ModuleExtension model = extension.getModifiableModel(false);
model.readExternal(element);
registerOnDispose(model);
myExtensions.add(model);
}
myConfigurationAccessor = new RootConfigurationAccessor();
}
@Override
public boolean isWritable() {
return myWritable;
}
public RootConfigurationAccessor getConfigurationAccessor() {
return myConfigurationAccessor;
}
//creates modifiable model
RootModelImpl(@NotNull RootModelImpl rootModel,
ModuleRootManagerImpl moduleRootManager,
final boolean writable,
final RootConfigurationAccessor rootConfigurationAccessor,
@NotNull VirtualFilePointerManager filePointerManager,
ProjectRootManagerImpl projectRootManager) {
myFilePointerManager = filePointerManager;
myModuleRootManager = moduleRootManager;
myProjectRootManager = projectRootManager;
myModuleLibraryTable = new ModuleLibraryTable(this, myProjectRootManager);
myWritable = writable;
myConfigurationAccessor = rootConfigurationAccessor;
final Set<ContentEntry> thatContent = rootModel.myContent;
for (ContentEntry contentEntry : thatContent) {
if (contentEntry instanceof ClonableContentEntry) {
ContentEntry cloned = ((ClonableContentEntry)contentEntry).cloneEntry(this);
myContent.add(cloned);
}
}
setOrderEntriesFrom(rootModel);
for (ModuleExtension extension : rootModel.myExtensions) {
ModuleExtension model = extension.getModifiableModel(writable);
registerOnDispose(model);
myExtensions.add(model);
}
}
private void setOrderEntriesFrom(@NotNull RootModelImpl rootModel) {
removeAllOrderEntries();
for (OrderEntry orderEntry : rootModel.myOrderEntries) {
if (orderEntry instanceof ClonableOrderEntry) {
myOrderEntries.add(((ClonableOrderEntry)orderEntry).cloneEntry(this, myProjectRootManager, myFilePointerManager));
}
}
}
private void removeAllOrderEntries() {
for (OrderEntry entry : myOrderEntries) {
Disposer.dispose((OrderEntryBaseImpl)entry);
}
myOrderEntries.clear();
}
@Override
@NotNull
public OrderEntry[] getOrderEntries() {
OrderEntry[] cachedOrderEntries = myCachedOrderEntries;
if (cachedOrderEntries == null) {
myCachedOrderEntries = cachedOrderEntries = myOrderEntries.toArray(new OrderEntry[myOrderEntries.size()]);
}
return cachedOrderEntries;
}
Iterator<OrderEntry> getOrderIterator() {
return Collections.unmodifiableList(myOrderEntries).iterator();
}
@Override
public void removeContentEntry(@NotNull ContentEntry entry) {
assertWritable();
LOG.assertTrue(myContent.contains(entry));
if (entry instanceof RootModelComponentBase) {
Disposer.dispose((RootModelComponentBase)entry);
RootModelImpl entryModel = ((RootModelComponentBase)entry).getRootModel();
LOG.assertTrue(entryModel == this, "Removing from " + this + " content entry obtained from " + entryModel);
}
myContent.remove(entry);
}
@Override
public void addOrderEntry(@NotNull OrderEntry entry) {
assertWritable();
LOG.assertTrue(!myOrderEntries.contains(entry));
myOrderEntries.add(entry);
}
@NotNull
@Override
public LibraryOrderEntry addLibraryEntry(@NotNull Library library) {
assertWritable();
final LibraryOrderEntry libraryOrderEntry = new LibraryOrderEntryImpl(library, this, myProjectRootManager);
if (!libraryOrderEntry.isValid()) {
LibraryEx libraryEx = ObjectUtils.tryCast(library, LibraryEx.class);
boolean libraryDisposed = libraryEx != null ? libraryEx.isDisposed() : Disposer.isDisposed(library);
throw new AssertionError("Invalid libraryOrderEntry, library: " + library
+ " of type " + library.getClass()
+ ", disposed: " + libraryDisposed
+ ", kind: " + (libraryEx != null ? libraryEx.getKind() : "<undefined>"));
}
myOrderEntries.add(libraryOrderEntry);
return libraryOrderEntry;
}
@NotNull
@Override
public LibraryOrderEntry addInvalidLibrary(@NotNull String name, @NotNull String level) {
assertWritable();
final LibraryOrderEntry libraryOrderEntry = new LibraryOrderEntryImpl(name, level, this, myProjectRootManager);
myOrderEntries.add(libraryOrderEntry);
return libraryOrderEntry;
}
@NotNull
@Override
public ModuleOrderEntry addModuleOrderEntry(@NotNull Module module) {
assertWritable();
LOG.assertTrue(!module.equals(getModule()));
LOG.assertTrue(Comparing.equal(myModuleRootManager.getModule().getProject(), module.getProject()));
final ModuleOrderEntryImpl moduleOrderEntry = new ModuleOrderEntryImpl(module, this);
myOrderEntries.add(moduleOrderEntry);
return moduleOrderEntry;
}
@NotNull
@Override
public ModuleOrderEntry addInvalidModuleEntry(@NotNull String name) {
assertWritable();
LOG.assertTrue(!name.equals(getModule().getName()));
final ModuleOrderEntryImpl moduleOrderEntry = new ModuleOrderEntryImpl(name, this);
myOrderEntries.add(moduleOrderEntry);
return moduleOrderEntry;
}
@Nullable
@Override
public LibraryOrderEntry findLibraryOrderEntry(@NotNull Library library) {
for (OrderEntry orderEntry : getOrderEntries()) {
if (orderEntry instanceof LibraryOrderEntry && library.equals(((LibraryOrderEntry)orderEntry).getLibrary())) {
return (LibraryOrderEntry)orderEntry;
}
}
return null;
}
@Override
public void removeOrderEntry(@NotNull OrderEntry entry) {
assertWritable();
removeOrderEntryInternal(entry);
}
private void removeOrderEntryInternal(OrderEntry entry) {
LOG.assertTrue(myOrderEntries.contains(entry));
Disposer.dispose((OrderEntryBaseImpl)entry);
myOrderEntries.remove(entry);
}
@Override
public void rearrangeOrderEntries(@NotNull OrderEntry[] newEntries) {
assertWritable();
assertValidRearrangement(newEntries);
myOrderEntries.clear();
ContainerUtil.addAll(myOrderEntries, newEntries);
}
private void assertValidRearrangement(@NotNull OrderEntry[] newEntries) {
String error = checkValidRearrangement(newEntries);
LOG.assertTrue(error == null, error);
}
@Nullable
private String checkValidRearrangement(@NotNull OrderEntry[] newEntries) {
if (newEntries.length != myOrderEntries.size()) {
return "Size mismatch: old size=" + myOrderEntries.size() + "; new size=" + newEntries.length;
}
Set<OrderEntry> set = new HashSet<>();
for (OrderEntry newEntry : newEntries) {
if (!myOrderEntries.contains(newEntry)) {
return "Trying to add nonexisting order entry " + newEntry;
}
if (set.contains(newEntry)) {
return "Trying to add duplicate order entry " + newEntry;
}
set.add(newEntry);
}
return null;
}
@Override
public void clear() {
final Sdk jdk = getSdk();
removeAllContentEntries();
removeAllOrderEntries();
setSdk(jdk);
addSourceOrderEntries();
}
private void removeAllContentEntries() {
for (ContentEntry entry : myContent) {
if (entry instanceof RootModelComponentBase) {
Disposer.dispose((RootModelComponentBase)entry);
}
}
myContent.clear();
}
@Override
public void commit() {
myModuleRootManager.commitModel(this);
myWritable = false;
}
public void docommit() {
assert isWritable();
if (areOrderEntriesChanged()) {
getSourceModel().setOrderEntriesFrom(this);
}
for (ModuleExtension extension : myExtensions) {
if (extension.isChanged()) {
extension.commit();
}
}
if (areContentEntriesChanged()) {
getSourceModel().removeAllContentEntries();
for (ContentEntry contentEntry : myContent) {
ContentEntry cloned = ((ClonableContentEntry)contentEntry).cloneEntry(getSourceModel());
getSourceModel().myContent.add(cloned);
}
}
}
@Override
@NotNull
public LibraryTable getModuleLibraryTable() {
return myModuleLibraryTable;
}
@Override
public Project getProject() {
return myProjectRootManager.getProject();
}
@Override
@NotNull
public ContentEntry addContentEntry(@NotNull VirtualFile file) {
return addContentEntry(new ContentEntryImpl(file, this));
}
@Override
@NotNull
public ContentEntry addContentEntry(@NotNull String url) {
return addContentEntry(new ContentEntryImpl(url, this));
}
@Override
public boolean isDisposed() {
return myDisposed;
}
@NotNull
private ContentEntry addContentEntry(@NotNull ContentEntry e) {
if (myContent.contains(e)) {
for (ContentEntry contentEntry : getContentEntries()) {
if (ContentComparator.INSTANCE.compare(contentEntry, e) == 0) return contentEntry;
}
}
myContent.add(e);
return e;
}
public void writeExternal(@NotNull Element element) throws WriteExternalException {
for (ModuleExtension extension : myExtensions) {
extension.writeExternal(element);
}
for (ContentEntry contentEntry : getContent()) {
if (contentEntry instanceof ContentEntryImpl) {
final Element subElement = new Element(ContentEntryImpl.ELEMENT_NAME);
((ContentEntryImpl)contentEntry).writeExternal(subElement);
element.addContent(subElement);
}
}
for (OrderEntry orderEntry : getOrderEntries()) {
if (orderEntry instanceof WritableOrderEntry) {
((WritableOrderEntry)orderEntry).writeExternal(element);
}
}
}
@Override
public void setSdk(@Nullable Sdk jdk) {
assertWritable();
final JdkOrderEntry jdkLibraryEntry;
if (jdk != null) {
jdkLibraryEntry = new ModuleJdkOrderEntryImpl(jdk, this, myProjectRootManager);
}
else {
jdkLibraryEntry = null;
}
replaceEntryOfType(JdkOrderEntry.class, jdkLibraryEntry);
}
@Override
public void setInvalidSdk(@NotNull String jdkName, String jdkType) {
assertWritable();
replaceEntryOfType(JdkOrderEntry.class, new ModuleJdkOrderEntryImpl(jdkName, jdkType, this, myProjectRootManager));
}
@Override
public void inheritSdk() {
assertWritable();
replaceEntryOfType(JdkOrderEntry.class, new InheritedJdkOrderEntryImpl(this, myProjectRootManager));
}
@Override
public <T extends OrderEntry> void replaceEntryOfType(@NotNull Class<T> entryClass, @Nullable final T entry) {
assertWritable();
for (int i = 0; i < myOrderEntries.size(); i++) {
OrderEntry orderEntry = myOrderEntries.get(i);
if (entryClass.isInstance(orderEntry)) {
myOrderEntries.remove(i);
if (entry != null) {
myOrderEntries.add(i, entry);
}
return;
}
}
if (entry != null) {
myOrderEntries.add(0, entry);
}
}
@Override
public String getSdkName() {
for (OrderEntry orderEntry : getOrderEntries()) {
if (orderEntry instanceof JdkOrderEntry) {
return ((JdkOrderEntry)orderEntry).getJdkName();
}
}
return null;
}
public void assertWritable() {
LOG.assertTrue(myWritable);
}
public boolean isDependsOn(final Module module) {
for (OrderEntry entry : getOrderEntries()) {
if (entry instanceof ModuleOrderEntry) {
final Module module1 = ((ModuleOrderEntry)entry).getModule();
if (module1 == module) {
return true;
}
}
}
return false;
}
public boolean isOrderEntryDisposed() {
for (OrderEntry entry : myOrderEntries) {
if (entry instanceof RootModelComponentBase && ((RootModelComponentBase)entry).isDisposed()) return true;
}
return false;
}
@Override
protected Set<ContentEntry> getContent() {
return myContent;
}
private static class ContentComparator implements Comparator<ContentEntry> {
public static final ContentComparator INSTANCE = new ContentComparator();
@Override
public int compare(@NotNull final ContentEntry o1, @NotNull final ContentEntry o2) {
return o1.getUrl().compareTo(o2.getUrl());
}
}
@Override
@NotNull
public Module getModule() {
return myModuleRootManager.getModule();
}
@Override
public boolean isChanged() {
if (!myWritable) return false;
for (ModuleExtension moduleExtension : myExtensions) {
if (moduleExtension.isChanged()) return true;
}
return areOrderEntriesChanged() || areContentEntriesChanged();
}
private boolean areContentEntriesChanged() {
return ArrayUtil.lexicographicCompare(getContentEntries(), getSourceModel().getContentEntries()) != 0;
}
private boolean areOrderEntriesChanged() {
OrderEntry[] orderEntries = getOrderEntries();
OrderEntry[] sourceOrderEntries = getSourceModel().getOrderEntries();
if (orderEntries.length != sourceOrderEntries.length) return true;
for (int i = 0; i < orderEntries.length; i++) {
OrderEntry orderEntry = orderEntries[i];
OrderEntry sourceOrderEntry = sourceOrderEntries[i];
if (!orderEntriesEquals(orderEntry, sourceOrderEntry)) {
return true;
}
}
return false;
}
private static boolean orderEntriesEquals(@NotNull OrderEntry orderEntry1, @NotNull OrderEntry orderEntry2) {
if (!((OrderEntryBaseImpl)orderEntry1).sameType(orderEntry2)) return false;
if (orderEntry1 instanceof JdkOrderEntry) {
if (!(orderEntry2 instanceof JdkOrderEntry)) return false;
if (orderEntry1 instanceof InheritedJdkOrderEntry && orderEntry2 instanceof ModuleJdkOrderEntry) {
return false;
}
if (orderEntry2 instanceof InheritedJdkOrderEntry && orderEntry1 instanceof ModuleJdkOrderEntry) {
return false;
}
if (orderEntry1 instanceof ModuleJdkOrderEntry && orderEntry2 instanceof ModuleJdkOrderEntry) {
String name1 = ((ModuleJdkOrderEntry)orderEntry1).getJdkName();
String name2 = ((ModuleJdkOrderEntry)orderEntry2).getJdkName();
if (!Comparing.strEqual(name1, name2)) {
return false;
}
}
}
if (orderEntry1 instanceof ExportableOrderEntry) {
if (!(((ExportableOrderEntry)orderEntry1).isExported() == ((ExportableOrderEntry)orderEntry2).isExported())) {
return false;
}
if (!(((ExportableOrderEntry)orderEntry1).getScope() == ((ExportableOrderEntry)orderEntry2).getScope())) {
return false;
}
}
if (orderEntry1 instanceof ModuleOrderEntry) {
LOG.assertTrue(orderEntry2 instanceof ModuleOrderEntry);
ModuleOrderEntryImpl entry1 = (ModuleOrderEntryImpl)orderEntry1;
ModuleOrderEntryImpl entry2 = (ModuleOrderEntryImpl)orderEntry2;
return entry1.isProductionOnTestDependency() == entry2.isProductionOnTestDependency()
&& Comparing.equal(entry1.getModuleName(), entry2.getModuleName());
}
if (orderEntry1 instanceof LibraryOrderEntry) {
LOG.assertTrue(orderEntry2 instanceof LibraryOrderEntry);
LibraryOrderEntry libraryOrderEntry1 = (LibraryOrderEntry)orderEntry1;
LibraryOrderEntry libraryOrderEntry2 = (LibraryOrderEntry)orderEntry2;
boolean equal = Comparing.equal(libraryOrderEntry1.getLibraryName(), libraryOrderEntry2.getLibraryName())
&& Comparing.equal(libraryOrderEntry1.getLibraryLevel(), libraryOrderEntry2.getLibraryLevel());
if (!equal) return false;
Library library1 = libraryOrderEntry1.getLibrary();
Library library2 = libraryOrderEntry2.getLibrary();
if (library1 != null && library2 != null) {
if (!Arrays.equals(((LibraryEx)library1).getExcludedRootUrls(), ((LibraryEx)library2).getExcludedRootUrls())) {
return false;
}
}
}
final OrderRootType[] allTypes = OrderRootType.getAllTypes();
for (OrderRootType type : allTypes) {
final String[] orderedRootUrls1 = orderEntry1.getUrls(type);
final String[] orderedRootUrls2 = orderEntry2.getUrls(type);
if (!Arrays.equals(orderedRootUrls1, orderedRootUrls2)) {
return false;
}
}
return true;
}
void makeExternalChange(@NotNull Runnable runnable) {
if (myWritable || myDisposed) return;
myModuleRootManager.makeRootsChange(runnable);
}
@Override
public void dispose() {
assert !myDisposed;
Disposer.dispose(myDisposable);
myExtensions.clear();
myWritable = false;
myDisposed = true;
}
private class Order extends ArrayList<OrderEntry> {
@Override
public void clear() {
super.clear();
clearCachedEntries();
}
@NotNull
@Override
public OrderEntry set(int i, @NotNull OrderEntry orderEntry) {
super.set(i, orderEntry);
((OrderEntryBaseImpl)orderEntry).setIndex(i);
clearCachedEntries();
return orderEntry;
}
@Override
public boolean add(@NotNull OrderEntry orderEntry) {
super.add(orderEntry);
((OrderEntryBaseImpl)orderEntry).setIndex(size() - 1);
clearCachedEntries();
return true;
}
@Override
public void add(int i, OrderEntry orderEntry) {
super.add(i, orderEntry);
clearCachedEntries();
setIndicies(i);
}
@Override
public OrderEntry remove(int i) {
OrderEntry entry = super.remove(i);
setIndicies(i);
clearCachedEntries();
return entry;
}
@Override
public boolean remove(Object o) {
int index = indexOf(o);
if (index < 0) return false;
remove(index);
clearCachedEntries();
return true;
}
@Override
public boolean addAll(Collection<? extends OrderEntry> collection) {
int startSize = size();
boolean result = super.addAll(collection);
setIndicies(startSize);
clearCachedEntries();
return result;
}
@Override
public boolean addAll(int i, Collection<? extends OrderEntry> collection) {
boolean result = super.addAll(i, collection);
setIndicies(i);
clearCachedEntries();
return result;
}
@Override
public void removeRange(int i, int i1) {
super.removeRange(i, i1);
clearCachedEntries();
setIndicies(i);
}
@Override
public boolean removeAll(Collection<?> collection) {
boolean result = super.removeAll(collection);
setIndicies(0);
clearCachedEntries();
return result;
}
@Override
public boolean retainAll(Collection<?> collection) {
boolean result = super.retainAll(collection);
setIndicies(0);
clearCachedEntries();
return result;
}
private void clearCachedEntries() {
myCachedOrderEntries = null;
}
private void setIndicies(int startIndex) {
for (int j = startIndex; j < size(); j++) {
((OrderEntryBaseImpl)get(j)).setIndex(j);
}
}
}
private RootModelImpl getSourceModel() {
assertWritable();
return myModuleRootManager.getRootModel();
}
@Override
public String toString() {
return "RootModelImpl{" +
"module=" + getModule().getName() +
", writable=" + myWritable +
", disposed=" + myDisposed +
'}';
}
@Nullable
@Override
public <T> T getModuleExtension(@NotNull final Class<T> klass) {
for (ModuleExtension extension : myExtensions) {
if (klass.isAssignableFrom(extension.getClass())) {
//noinspection unchecked
return (T)extension;
}
}
return null;
}
void registerOnDispose(@NotNull Disposable disposable) {
myDisposable.add(disposable);
}
}
| michaelgallacher/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/roots/impl/RootModelImpl.java | Java | apache-2.0 | 24,750 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.apache.nifi.logging.repository;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.logging.LogLevel;
import org.apache.nifi.logging.LogMessage;
import org.apache.nifi.logging.LogObserver;
import org.apache.nifi.logging.LogRepository;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class NopLogRepository implements LogRepository {
private final ConcurrentMap<String, LogLevel> observationLevels = new ConcurrentHashMap<>();
private volatile ComponentLog logger;
@Override
public void addLogMessage(LogMessage logMessage) {
}
@Override
public void addLogMessage(final LogLevel level, final String messageFormat, final Object[] params) {
}
@Override
public void addLogMessage(final LogLevel level, final String messageFormat, final Object[] params, final Throwable t) {
}
@Override
public void addObserver(final String observerIdentifier, final LogLevel level, final LogObserver observer) {
}
@Override
public void setObservationLevel(final String observerIdentifier, final LogLevel level) {
observationLevels.put(observerIdentifier, level);
}
@Override
public LogLevel getObservationLevel(final String observerIdentifier) {
return observationLevels.get(observerIdentifier);
}
@Override
public LogObserver removeObserver(final String observerIdentifier) {
observationLevels.remove(observerIdentifier);
return null;
}
@Override
public void removeAllObservers() {
observationLevels.clear();
}
@Override
public void setLogger(final ComponentLog logger) {
this.logger = logger;
}
@Override
public ComponentLog getLogger() {
return logger;
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public boolean isInfoEnabled() {
return true;
}
@Override
public boolean isWarnEnabled() {
return true;
}
@Override
public boolean isErrorEnabled() {
return true;
}
}
| MikeThomsen/nifi | nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/logging/repository/NopLogRepository.java | Java | apache-2.0 | 2,935 |
/** The MIT License (MIT)
*
* Copyright (c) 2014 INFN Division of Catania
*
* 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 scoap3withapi;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
*
* @author Carla Carrubba
* @author Giusi Inserra
*/
public class Scoap3_step2 {
static ArrayList listRecordsNOINFN;
static ArrayList listFinalINFN;
public static void executeStep2(String nameDirSource, String date) {
String dir_destination=createDirDestination(date);
File dir = new File(nameDirSource);
String[] children = dir.list();
if (children != null) {
for (int i = 0; i < children.length; i++) {
// Get filename of file or directory
String filename = children[i];
System.out.println("-------FILENAME---" + i + ")--->" + filename);
String pathFile = nameDirSource + "/" + filename;
findRecordsINFNandNotINFN(pathFile);
createFile(listFinalINFN, Integer.toString(i), pathFile, "INFN", "PUBLICATIONINFN", dir_destination);
createFile(listRecordsNOINFN, Integer.toString(i), pathFile, "OTHER", "PUBLICATIONOTHER",dir_destination);
}
}
}
private static String createDirDestination(String date) {
String Dir = "MARCXML_SCOAP3_DIVISION_from_"+Scoap3withAPI.startDate+"_to_"+Scoap3withAPI.todayDate;
File f = new File(Dir);
boolean esiste = f.exists();
if (!esiste) {
boolean success = (new File(Dir)).mkdir();
if (success) {
File dirINFN = new File(Dir+"/INFN");
if(!dirINFN.exists())
(new File(Dir+"/INFN")).mkdir();
File dirOTHER = new File(Dir+"/OTHER");
if(!dirOTHER.exists())
(new File(Dir+"/OTHER")).mkdir();
} else {
System.out.println("Impossible to create: " + Dir);
}
} else {
File directoryINFN = new File(Dir+"/INFN");
if (directoryINFN.exists()) {
File[] filesINFN = directoryINFN.listFiles();
for (File ffINFN : filesINFN) {
ffINFN.delete();
}
}
File directoryOTHER = new File(Dir+"/OTHER");
if (directoryOTHER.exists()) {
File[] filesOTHER = directoryOTHER.listFiles();
for (File ffOTHER : filesOTHER) {
ffOTHER.delete();
}
}
}
return Dir;
}
public static void findRecordsINFNandNotINFN(String pathFile) {
int start = 0;
int stop = 100;
ArrayList listRecordsINFN = new ArrayList();
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File(pathFile));
Element root = document.getRootElement();
String nomeRadice = root.getName();
List children = root.getChildren();
Iterator iterator = children.iterator();
while (iterator.hasNext()) {
Element itemRecord = (Element) iterator.next();
String nomeTag = itemRecord.getName();
List childrenRecord = itemRecord.getChildren();
Iterator iteratorRecord = childrenRecord.iterator();
while (iteratorRecord.hasNext()) {
Element childRecord = (Element) iteratorRecord.next();
String childNome = childRecord.getName();
if (childNome.equals("datafield")) {
List childrenDataField = childRecord.getChildren();
Iterator iteratorchildrenDataField = childrenDataField.iterator();
while (iteratorchildrenDataField.hasNext()) {
Element childDataField = (Element) iteratorchildrenDataField.next();
String childDataFieldNome = childDataField.getName();
String valueDataField = childDataField.getText();
if (valueDataField.toUpperCase().contains("INFN") || valueDataField.toUpperCase().contains("I.N.F.N.")
|| valueDataField.toUpperCase().contains("NATIONAL INSTITUTE OF NUCLEAR PHYSICS")
|| valueDataField.toUpperCase().contains("ISTITUTO NAZIONALE DI FISICA NUCLEARE")) {
listRecordsINFN.add(start);
}
}
}
}
start++;
}
} catch (Exception e) {
System.err.println("Error in reading file");
e.printStackTrace();
}
listFinalINFN = listRecordsINFN;
listFinalINFN = getListNotDuplicate(listRecordsINFN);
// System.out.println("num_records INFN--->" + listFinalINFN.size());
listRecordsNOINFN = new ArrayList();
int count = 0;
if (listFinalINFN.size() > 0) {
for (int i = 0; i < listFinalINFN.size(); i++) {
int elem = (Integer) listFinalINFN.get(i);
while (count < 100) {
if (count != elem) {
listRecordsNOINFN.add(count);
count++;
} else {
count = elem + 1;
if (i == listFinalINFN.size() - 1) {
while (count < 100) {
listRecordsNOINFN.add(count);
count++;
}
}
break;
}
}
}
} else {
for (int i = 0; i < start; i++) {
listRecordsNOINFN.add(i);
}
}
// System.out.println("num_records NO INFN--->" + listRecordsNOINFN.size());
}
public static ArrayList getListNotDuplicate(ArrayList listOriginal) {
ArrayList listNuova = new ArrayList();
if (listOriginal.size() > 1) {
int k = 1;
int j, i = 0;
boolean duplicato;
listNuova.add(listOriginal.get(0));
for (i = 1; i < listOriginal.size(); i++) {
duplicato = false;
for (j = 0; j < i; j++) {
if (listOriginal.get(i) == listOriginal.get(j)) {
duplicato = true;
}
}
if (!duplicato) {
listNuova.add(listOriginal.get(i));
}
}
return listNuova;
} else {
return listOriginal;
}
}
public static void createFile(ArrayList listRecords, String index, String pathFile, String type, String typeCollection, String dir_dest) {
int start = 0;
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File(pathFile));
Element root = document.getRootElement();
String nomeRadice = root.getName();
List children = root.getChildren();
Iterator iterator = children.iterator();
Document docMarc = new Document();
Element rootMarc = new Element("collection");
docMarc.setRootElement(rootMarc);
while (iterator.hasNext()) {
Element itemRecord = (Element) iterator.next();
for (int j = 0; j < listRecords.size(); j++) {
if (start == (Integer) listRecords.get(j)) {
Element elemCopy = (Element) itemRecord.clone();
//ADD TAG COLLECTION
Element datafield = new Element("datafield");
datafield.setAttribute(new Attribute("tag", "980"));
datafield.setAttribute(new Attribute("ind1", " "));
datafield.setAttribute(new Attribute("ind2", " "));
Element subfield = new Element("subfield");
subfield.setAttribute(new Attribute("code", "a"));
subfield.setText(typeCollection);
elemCopy.addContent(datafield);
datafield.addContent(subfield);
//ADD TAG LANGUAGE
Element datafield_lang = new Element("datafield");
datafield_lang.setAttribute(new Attribute("tag", "041"));
datafield_lang.setAttribute(new Attribute("ind1", " "));
datafield_lang.setAttribute(new Attribute("ind2", " "));
Element subfield_lang = new Element("subfield");
subfield_lang.setAttribute(new Attribute("code", "a"));
subfield_lang.setText("eng");
elemCopy.addContent(datafield_lang);
datafield_lang.addContent(subfield_lang);
//ADD TAG AUDIENCE
Element datafield_audience = new Element("datafield");
datafield_audience.setAttribute(new Attribute("tag", "042"));
datafield_audience.setAttribute(new Attribute("ind1", " "));
datafield_audience.setAttribute(new Attribute("ind2", " "));
Element subfield_audience = new Element("subfield");
subfield_audience.setAttribute(new Attribute("code", "a"));
subfield_audience.setText("Researchers");
elemCopy.addContent(datafield_audience);
datafield_audience.addContent(subfield_audience);
//ADD TAG TYPE
Element datafield_type = new Element("datafield");
datafield_type.setAttribute(new Attribute("tag", "043"));
datafield_type.setAttribute(new Attribute("ind1", " "));
datafield_type.setAttribute(new Attribute("ind2", " "));
Element subfield_type = new Element("subfield");
subfield_type.setAttribute(new Attribute("code", "a"));
subfield_type.setText("info:eu-repo/semantics/article");
elemCopy.addContent(datafield_type);
datafield_type.addContent(subfield_type);
elemCopy.detach();
String nomeTag = itemRecord.getName();
rootMarc.addContent(elemCopy);
}
}
start++;
}
XMLOutputter xmlOutput = new XMLOutputter();
String newpathFile=dir_dest+"/" + type + "/Records" + type + "_" + index + ".xml";
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(docMarc, new FileWriter(newpathFile));
deleteFirstRow(newpathFile);
} catch (Exception e) {
System.err.println("Error in reading file");
e.printStackTrace();
}
}
public static void deleteFirstRow(String pathFile) {
FileInputStream fstream = null;
DataInputStream in = null;
BufferedWriter out = null;
try {
fstream = new FileInputStream(pathFile);
in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
StringBuilder fileContent = new StringBuilder();
strLine = br.readLine();
while ((strLine = br.readLine()) != null) {
fileContent.append(strLine);
fileContent.append(System.getProperty("line.separator"));
}
FileWriter fstreamWrite = new FileWriter(pathFile);
out = new BufferedWriter(fstreamWrite);
out.write(fileContent.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fstream.close();
out.flush();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| csgf/scoap3-harvester-api | src/scoap3withapi/Scoap3_step2.java | Java | apache-2.0 | 14,454 |
package org.apache.lucene.demo;
/**
* Copyright 2004 The Apache Software Foundation
*
* 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.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.FilterIndexReader;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Hits;
import org.apache.lucene.queryParser.QueryParser;
class SearchFiles {
/** Use the norms from one field for all fields. Norms are read into memory,
* using a byte of memory per document per searched field. This can cause
* search of large collections with a large number of fields to run out of
* memory. If all of the fields contain only a single token, then the norms
* are all identical, then single norm vector may be shared. */
private static class OneNormsReader extends FilterIndexReader {
private String field;
public OneNormsReader(IndexReader in, String field) {
super(in);
this.field = field;
}
public byte[] norms(String field) throws IOException {
return in.norms(this.field);
}
}
public static void main(String[] args) throws Exception {
String usage =
"Usage: java org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-raw] [-norms field]";
if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
System.out.println(usage);
System.exit(0);
}
String index = "index";
String field = "contents";
String queries = null;
int repeat = 0;
boolean raw = false;
String normsField = null;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
index = args[i+1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i+1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i+1];
i++;
} else if ("-repeat".equals(args[i])) {
repeat = Integer.parseInt(args[i+1]);
i++;
} else if ("-raw".equals(args[i])) {
raw = true;
} else if ("-norms".equals(args[i])) {
normsField = args[i+1];
i++;
}
}
IndexReader reader = IndexReader.open(index);
if (normsField != null)
reader = new OneNormsReader(reader, normsField);
Searcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer();
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new FileReader(queries));
} else {
in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
}
while (true) {
if (queries == null) // prompt the user
System.out.print("Query: ");
String line = in.readLine();
if (line == null || line.length() == -1)
break;
Query query = QueryParser.parse(line, field, analyzer);
System.out.println("Searching for: " + query.toString(field));
Hits hits = searcher.search(query);
if (repeat > 0) { // repeat & time as benchmark
Date start = new Date();
for (int i = 0; i < repeat; i++) {
hits = searcher.search(query);
}
Date end = new Date();
System.out.println("Time: "+(end.getTime()-start.getTime())+"ms");
}
System.out.println(hits.length() + " total matching documents");
final int HITS_PER_PAGE = 10;
for (int start = 0; start < hits.length(); start += HITS_PER_PAGE) {
int end = Math.min(hits.length(), start + HITS_PER_PAGE);
for (int i = start; i < end; i++) {
if (raw) { // output raw format
System.out.println("doc="+hits.id(i)+" score="+hits.score(i));
continue;
}
Document doc = hits.doc(i);
String path = doc.get("path");
if (path != null) {
System.out.println((i+1) + ". " + path);
String title = doc.get("title");
if (title != null) {
System.out.println(" Title: " + doc.get("title"));
}
} else {
System.out.println((i+1) + ". " + "No path for this document");
}
}
if (queries != null) // non-interactive
break;
if (hits.length() > end) {
System.out.print("more (y/n) ? ");
line = in.readLine();
if (line.length() == 0 || line.charAt(0) == 'n')
break;
}
}
}
reader.close();
}
}
| lpxz/grail-lucene358684 | src/demo/org/apache/lucene/demo/SearchFiles.java | Java | apache-2.0 | 5,468 |
package org.radargun.sysmonitor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.management.MBeanServerConnection;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
/**
* @author Galder Zamarreno
*/
public class CpuUsageMonitor extends AbstractActivityMonitor {
private static Log log = LogFactory.getLog(CpuUsageMonitor.class);
static final String PROCESS_CPU_TIME_ATTR = "ProcessCpuTime";
final MBeanServerConnection con;
final long cpuTimeMultiplier;
final int procCount;
long cpuTime;
long prevCpuTime;
long upTime;
long prevUpTime;
static {
PERCENT_FORMATTER.setMinimumFractionDigits(1);
PERCENT_FORMATTER.setMaximumIntegerDigits(3);
}
CpuUsageMonitor(MBeanServerConnection con) throws Exception {
this.con = con;
this.cpuTimeMultiplier = getCpuMultiplier(con);
OperatingSystemMXBean os = ManagementFactory.newPlatformMXBeanProxy(con,
ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
procCount = os.getAvailableProcessors();
}
public void run() {
try {
prevCpuTime = cpuTime;
prevUpTime = upTime;
Long jmxCpuTime = (Long) con.getAttribute(OS_NAME, PROCESS_CPU_TIME_ATTR);
cpuTime = jmxCpuTime * cpuTimeMultiplier;
Long jmxUpTime = (Long) con.getAttribute(RUNTIME_NAME, PROCESS_UP_TIME);
upTime = jmxUpTime;
long upTimeDiff = (upTime * 1000000) - (prevUpTime * 1000000);
long procTimeDiff = (cpuTime / procCount) - (prevCpuTime / procCount);
long cpuUsage = upTimeDiff > 0 ? Math.min((long)
(1000 * (float) procTimeDiff / (float) upTimeDiff), 1000) : 0;
addMeasurementAsPercentage(cpuUsage);
log.trace("Cpu usage: " + formatPercent(cpuUsage * 0.1d));
} catch (Exception e) {
log.error("Exception!", e);
}
}
}
| nmldiegues/stibt | radargun/framework/src/main/java/org/radargun/sysmonitor/CpuUsageMonitor.java | Java | apache-2.0 | 2,093 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.apache.curator.framework.recipes.nodes;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.imps.TestCleanState;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.BaseClassForTests;
import org.apache.curator.test.compatibility.Timing2;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("deprecation")
public class TestPersistentEphemeralNode extends BaseClassForTests
{
private static final Logger log = LoggerFactory.getLogger(TestPersistentEphemeralNode.class);
private static final String DIR = "/test";
private static final String PATH = ZKPaths.makePath(DIR, "/foo");
private final Collection<CuratorFramework> curatorInstances = Lists.newArrayList();
private final Collection<PersistentEphemeralNode> createdNodes = Lists.newArrayList();
private final Timing2 timing = new Timing2();
@AfterEach
@Override
public void teardown() throws Exception
{
try
{
for ( PersistentEphemeralNode node : createdNodes )
{
CloseableUtils.closeQuietly(node);
}
for ( CuratorFramework curator : curatorInstances )
{
TestCleanState.closeAndTestClean(curator);
}
}
finally
{
super.teardown();
}
}
@Test
public void testListenersReconnectedIsFast() throws Exception
{
server.stop();
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
try
{
client.start();
try ( PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()) )
{
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
final CountDownLatch connectedLatch = new CountDownLatch(1);
final CountDownLatch reconnectedLatch = new CountDownLatch(1);
ConnectionStateListener listener = new ConnectionStateListener()
{
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
if ( newState == ConnectionState.CONNECTED )
{
connectedLatch.countDown();
}
if ( newState == ConnectionState.RECONNECTED )
{
reconnectedLatch.countDown();
}
}
};
client.getConnectionStateListenable().addListener(listener);
timing.sleepABit();
server.restart();
assertTrue(timing.awaitLatch(connectedLatch));
timing.sleepABit();
assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS));
server.stop();
timing.sleepABit();
server.restart();
timing.sleepABit();
assertTrue(timing.awaitLatch(reconnectedLatch));
}
}
finally
{
TestCleanState.closeAndTestClean(client);
}
}
@Test
public void testNoServerAtStart() throws Exception
{
server.stop();
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
PersistentEphemeralNode node = null;
try
{
client.start();
node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes());
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
final CountDownLatch connectedLatch = new CountDownLatch(1);
ConnectionStateListener listener = new ConnectionStateListener()
{
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
if ( newState == ConnectionState.CONNECTED )
{
connectedLatch.countDown();
}
}
};
client.getConnectionStateListenable().addListener(listener);
timing.sleepABit();
server.restart();
assertTrue(timing.awaitLatch(connectedLatch));
timing.sleepABit();
assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS));
}
finally
{
CloseableUtils.closeQuietly(node);
TestCleanState.closeAndTestClean(client);
}
}
@Test
public void testNullCurator()
{
assertThrows(NullPointerException.class, ()-> {
new PersistentEphemeralNode(null, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
});
}
@Test
public void testNullPath()
{
assertThrows(IllegalArgumentException.class, ()-> {
CuratorFramework curator = newCurator();
new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, null, new byte[0]);
});
}
@Test
public void testNullData()
{
assertThrows(NullPointerException.class, ()-> {
CuratorFramework curator = newCurator();
new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, null);
});
}
@Test
public void testNullMode()
{
assertThrows(NullPointerException.class, ()->{
CuratorFramework curator = newCurator();
new PersistentEphemeralNode(curator, null, PATH, new byte[0]);
});
}
@Test
public void testSettingDataSequential() throws Exception
{
setDataTest(PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL);
}
@Test
public void testSettingData() throws Exception
{
setDataTest(PersistentEphemeralNode.Mode.EPHEMERAL);
}
protected void setDataTest(PersistentEphemeralNode.Mode mode) throws Exception
{
PersistentEphemeralNode node = null;
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
try
{
client.start();
node = new PersistentEphemeralNode(client, mode, PATH, "a".getBytes());
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
assertTrue(node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS));
assertArrayEquals(client.getData().forPath(node.getActualPath()), "a".getBytes());
final Semaphore semaphore = new Semaphore(0);
Watcher watcher = new Watcher()
{
@Override
public void process(WatchedEvent arg0)
{
semaphore.release();
}
};
client.checkExists().usingWatcher(watcher).forPath(node.getActualPath());
node.setData("b".getBytes());
assertTrue(timing.acquireSemaphore(semaphore));
assertEquals(node.getActualPath(), node.getActualPath());
assertArrayEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()), "b".getBytes());
node.setData("c".getBytes());
assertTrue(timing.acquireSemaphore(semaphore));
assertEquals(node.getActualPath(), node.getActualPath());
assertArrayEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()), "c".getBytes());
node.close();
assertTrue(timing.acquireSemaphore(semaphore));
}
finally
{
CloseableUtils.closeQuietly(node);
TestCleanState.closeAndTestClean(client);
}
}
@Test
public void testDeletesNodeWhenClosed() throws Exception
{
CuratorFramework curator = newCurator();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
String path = null;
try
{
node.waitForInitialCreate(5, TimeUnit.SECONDS);
path = node.getActualPath();
assertNodeExists(curator, path);
}
finally
{
CloseableUtils.closeQuietly(node);
}
assertNodeDoesNotExist(curator, path);
}
@Test
public void testClosingMultipleTimes() throws Exception
{
CuratorFramework curator = newCurator();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
String path = node.getActualPath();
node.close();
assertNodeDoesNotExist(curator, path);
node.close();
assertNodeDoesNotExist(curator, path);
}
@Test
public void testDeletesNodeWhenSessionDisconnects() throws Exception
{
CuratorFramework curator = newCurator();
CuratorFramework observer = newCurator();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
try
{
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
assertNodeExists(observer, node.getActualPath());
// Register a watch that will fire when the node is deleted...
Trigger deletedTrigger = Trigger.deletedOrSetData();
observer.checkExists().usingWatcher(deletedTrigger).forPath(node.getActualPath());
node.debugCreateNodeLatch = new CountDownLatch(1);
curator.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
// Make sure the node got deleted
assertTrue(deletedTrigger.firedWithin(timing.forSessionSleep().seconds(), TimeUnit.SECONDS));
node.debugCreateNodeLatch.countDown();
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
@Test
public void testRecreatesNodeWhenSessionReconnects() throws Exception
{
CuratorFramework curator = newCurator();
CuratorFramework observer = newCurator();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
try
{
node.start();
node.waitForInitialCreate(5, TimeUnit.SECONDS);
assertNodeExists(observer, node.getActualPath());
Trigger deletedTrigger = Trigger.deletedOrSetData();
observer.checkExists().usingWatcher(deletedTrigger).forPath(node.getActualPath());
node.debugCreateNodeLatch = new CountDownLatch(1);
curator.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
// Make sure the node got deleted...
assertTrue(deletedTrigger.firedWithin(timing.forSessionSleep().seconds(), TimeUnit.SECONDS));
node.debugCreateNodeLatch.countDown();
// Check for it to be recreated...
Trigger createdTrigger = Trigger.created();
Stat stat = observer.checkExists().usingWatcher(createdTrigger).forPath(node.getActualPath());
assertTrue(stat != null || createdTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS));
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
@Test
public void testRecreatesNodeWhenSessionReconnectsMultipleTimes() throws Exception
{
CuratorFramework curator = newCurator();
CuratorFramework observer = newCurator();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
try
{
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
String path = node.getActualPath();
assertNodeExists(observer, path);
// We should be able to disconnect multiple times and each time the node should be recreated.
for ( int i = 0; i < 5; i++ )
{
Trigger deletionTrigger = Trigger.deletedOrSetData();
Stat stat = observer.checkExists().usingWatcher(deletionTrigger).forPath(path);
assertNotNull(stat, "node should exist: " + path);
node.debugCreateNodeLatch = new CountDownLatch(1);
// Kill the session, thus cleaning up the node...
curator.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
// Make sure the node ended up getting deleted...
assertTrue(deletionTrigger.firedWithin(timing.multiple(1.5).forSessionSleep().seconds(), TimeUnit.SECONDS));
node.debugCreateNodeLatch.countDown();
// Now put a watch in the background looking to see if it gets created...
Trigger creationTrigger = Trigger.created();
stat = observer.checkExists().usingWatcher(creationTrigger).forPath(path);
assertTrue(stat != null || creationTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS));
}
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
@Test
public void testRecreatesNodeWhenEphemeralOwnerSessionExpires() throws Exception
{
CuratorFramework curator = newCurator();
CuratorFramework nodeCreator = newCurator();
CuratorFramework observer = newCurator();
nodeCreator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(PATH, new byte[0]);
Trigger dataChangedTrigger = Trigger.dataChanged();
observer.getData().usingWatcher(dataChangedTrigger).forPath(PATH);
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
try
{
node.waitForInitialCreate(5, TimeUnit.SECONDS);
assertNodeExists(observer, node.getActualPath());
assertTrue(dataChangedTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS));
Trigger deletedTrigger = Trigger.deletedOrSetData();
observer.checkExists().usingWatcher(deletedTrigger).forPath(node.getActualPath());
nodeCreator.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
// Make sure the node got deleted...
assertTrue(deletedTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS));
// Check for it to be recreated...
Trigger createdTrigger = Trigger.created();
Stat stat = observer.checkExists().usingWatcher(createdTrigger).forPath(node.getActualPath());
assertTrue(stat != null || createdTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS));
}
finally
{
node.close();
}
}
@Test
public void testRecreatesNodeWhenItGetsDeleted() throws Exception
{
CuratorFramework curator = newCurator();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
try
{
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
String originalNode = node.getActualPath();
assertNodeExists(curator, originalNode);
// Delete the original node...
curator.delete().forPath(originalNode);
// Since we're using an ephemeral node, and the original session hasn't been interrupted the name of the new
// node that gets created is going to be exactly the same as the original.
Trigger createdWatchTrigger = Trigger.created();
Stat stat = curator.checkExists().usingWatcher(createdWatchTrigger).forPath(originalNode);
assertTrue(stat != null || createdWatchTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS));
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
@Test
public void testNodesCreateUniquePaths() throws Exception
{
CuratorFramework curator = newCurator();
try ( PersistentEphemeralNode node1 = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0]) )
{
node1.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node1.start();
node1.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
String path1 = node1.getActualPath();
PersistentEphemeralNode node2 = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0]);
node2.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node2.start();
try
{
node2.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
String path2 = node2.getActualPath();
assertFalse(path1.equals(path2));
}
finally
{
node2.close();
}
}
}
@Test
public void testData() throws Exception
{
CuratorFramework curator = newCurator();
byte[] data = "Hello World".getBytes();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
try
{
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), data));
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
/**
* Test that if a persistent ephemeral node is created and the node already exists
* that if data is present in the PersistentEphermalNode that it is still set.
* @throws Exception
*/
@Test
public void testSetDataWhenNodeExists() throws Exception
{
CuratorFramework curator = newCurator();
curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(PATH, "InitialData".getBytes());
byte[] data = "Hello World".getBytes();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
try
{
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), data));
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
@Test
public void testSetDataWhenDisconnected() throws Exception
{
CuratorFramework curator = newCurator();
byte[] initialData = "Hello World".getBytes();
byte[] updatedData = "Updated".getBytes();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, initialData);
try
{
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), initialData));
server.stop();
final CountDownLatch dataUpdateLatch = new CountDownLatch(1);
Watcher watcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
if ( event.getType() == EventType.NodeDataChanged )
{
dataUpdateLatch.countDown();
}
}
};
curator.getData().usingWatcher(watcher).inBackground().forPath(node.getActualPath());
node.setData(updatedData);
server.restart();
assertTrue(timing.awaitLatch(dataUpdateLatch));
assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData));
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
@Test
public void testSetUpdatedDataWhenReconnected() throws Exception
{
CuratorFramework curator = newCurator();
byte[] initialData = "Hello World".getBytes();
byte[] updatedData = "Updated".getBytes();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, initialData);
try
{
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), initialData));
node.setData(updatedData);
assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData));
server.restart();
final CountDownLatch dataUpdateLatch = new CountDownLatch(1);
curator.getData().inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
dataUpdateLatch.countDown();
}
}).forPath(node.getActualPath());
assertTrue(timing.awaitLatch(dataUpdateLatch));
assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData));
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
/**
* See CURATOR-190
* For protected nodes on reconnect the current protected name was passed to the create builder meaning that it got
* appended to the new protected node name. This meant that a new node got created on each reconnect.
* @throws Exception
*/
@Test
public void testProtected() throws Exception
{
CuratorFramework curator = newCurator();
PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.PROTECTED_EPHEMERAL, PATH,
new byte[0]);
try
{
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
assertNodeExists(curator, node.getActualPath());
server.restart();
curator.blockUntilConnected(5, TimeUnit.SECONDS);
assertNodeExists(curator, node.getActualPath());
//There should only be a single child, the persisted ephemeral node
List<String> children = curator.getChildren().forPath(DIR);
assertFalse(children == null);
assertEquals(children.size(), 1);
}
finally
{
CloseableUtils.closeQuietly(node);
}
}
@Test
public void testNoCreatePermission() throws Exception
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder
.connectString(server.getConnectString())
.authorization("digest", "me1:pass1".getBytes())
.retryPolicy(new RetryOneTime(1))
.build();
PersistentEphemeralNode node = null;
try {
client.start();
ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS);
List<ACL> aclList = Lists.newArrayList(acl);
client.create().withACL(aclList).forPath(DIR, new byte[0]);
client.close();
//New client without authentication
client = newCurator();
node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, PATH,
new byte[0]);
node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
node.start();
node.waitForInitialCreate(timing.seconds(), TimeUnit.SECONDS);
assertNodeDoesNotExist(client, PATH);
assertTrue(node.isAuthFailure());
} finally {
CloseableUtils.closeQuietly(node);
CloseableUtils.closeQuietly(client);
}
}
@Test
public void testNoWritePermission() throws Exception
{
final ACLProvider aclProvider = new ACLProvider() {
final ACL acl = new ACL(ZooDefs.Perms.READ | ZooDefs.Perms.CREATE | ZooDefs.Perms.DELETE, ZooDefs.Ids.ANYONE_ID_UNSAFE);
final List<ACL> aclList = Collections.singletonList(acl);
@Override
public List<ACL> getDefaultAcl() {
return aclList;
}
@Override
public List<ACL> getAclForPath(String path) {
return aclList;
}
};
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder
.connectString(server.getConnectString())
.aclProvider(aclProvider)
.retryPolicy(new RetryOneTime(1))
.build();
PersistentEphemeralNode node = null;
try {
client.start();
node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, PATH,
new byte[0]);
node.start();
assertTrue(node.waitForInitialCreate(timing.seconds(), TimeUnit.SECONDS), "Node not created");
assertNodeExists(client, PATH);
assertFalse(node.isAuthFailure(), "AuthFailure when creating node.");
byte[] NEW_DATA = "NEW_DATA".getBytes();
node.setData(NEW_DATA);
timing.sleepABit();
byte[] read_data = client.getData().forPath(PATH);
assertNotEquals(read_data, NEW_DATA, "Data matches - write went through.");
assertTrue(node.isAuthFailure(), "AuthFailure response not received.");
} finally {
CloseableUtils.closeQuietly(node);
CloseableUtils.closeQuietly(client);
}
}
private void assertNodeExists(CuratorFramework curator, String path) throws Exception
{
assertNotNull(path);
assertTrue(curator.checkExists().forPath(path) != null);
}
private void assertNodeDoesNotExist(CuratorFramework curator, String path) throws Exception
{
assertTrue(curator.checkExists().forPath(path) == null);
}
private CuratorFramework newCurator() throws IOException
{
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
client.start();
curatorInstances.add(client);
return client;
}
private static final class Trigger implements Watcher
{
private final Set<EventType> types;
private final CountDownLatch latch;
public Trigger(Event.EventType... types)
{
assertNotNull(types);
this.types = ImmutableSet.copyOf(types);
this.latch = new CountDownLatch(1);
}
@Override
public void process(WatchedEvent event)
{
if ( types.contains(event.getType()) )
{
latch.countDown();
}
else if ( event.getType() != EventType.None )
{
log.warn("Unexpected watcher event: " + event);
}
}
public boolean firedWithin(long duration, TimeUnit unit)
{
try
{
return latch.await(duration, unit);
}
catch ( InterruptedException e )
{
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
}
}
private static Trigger created()
{
return new Trigger(Event.EventType.NodeCreated);
}
private static Trigger deletedOrSetData()
{
return new Trigger(Event.EventType.NodeDeleted, EventType.NodeDataChanged);
}
private static Trigger dataChanged()
{
return new Trigger(EventType.NodeDataChanged);
}
}
}
| mosoft521/curator | curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNode.java | Java | apache-2.0 | 33,044 |
/* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.apache.manifoldcf.authorities.mappers.regexp;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.authorities.interfaces.*;
import org.apache.manifoldcf.authorities.system.Logging;
import org.apache.manifoldcf.authorities.system.ManifoldCF;
import java.io.*;
import java.util.*;
/** This is the regexp mapper implementation, which uses a regular expression to manipulate a user name.
*/
public class RegexpMapper extends org.apache.manifoldcf.authorities.mappers.BaseMappingConnector
{
public static final String _rcsid = "@(#)$Id$";
// Match map for username
private MatchMap matchMap = null;
/** Constructor.
*/
public RegexpMapper()
{
}
/** Close the connection. Call this before discarding the mapping connection.
*/
@Override
public void disconnect()
throws ManifoldCFException
{
matchMap = null;
super.disconnect();
}
// All methods below this line will ONLY be called if a connect() call succeeded
// on this instance!
private MatchMap getSession()
throws ManifoldCFException
{
if (matchMap == null)
matchMap = new MatchMap(params.getParameter(RegexpParameters.userNameMapping));
return matchMap;
}
/** Map an input user name to an output name.
*@param userName is the name to map
*@return the mapped user name
*/
@Override
public String mapUser(String userName)
throws ManifoldCFException
{
MatchMap mm = getSession();
String outputUserName = mm.translate(userName);
if (Logging.mappingConnectors.isDebugEnabled())
Logging.mappingConnectors.debug("RegexpMapper: Input user name '"+userName+"'; output user name '"+outputUserName+"'");
return outputUserName;
}
// UI support methods.
//
// These support methods are involved in setting up authority connection configuration information. The configuration methods cannot assume that the
// current authority object is connected. That is why they receive a thread context argument.
/** Output the configuration header section.
* This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any
* javascript methods that might be needed by the configuration editing HTML.
*@param threadContext is the local thread context.
*@param out is the output to which any HTML should be sent.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector.
*/
@Override
public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out,
Locale locale, ConfigParams parameters, List<String> tabsArray)
throws ManifoldCFException, IOException
{
tabsArray.add(Messages.getString(locale,"RegexpMapper.UserMapping"));
out.print(
"<script type=\"text/javascript\">\n"+
"<!--\n"+
"function checkConfig()\n"+
"{\n"+
" if (editconnection.usernameregexp.value != \"\" && !isRegularExpression(editconnection.usernameregexp.value))\n"+
" {\n"+
" alert(\"" + Messages.getBodyJavascriptString(locale,"RegexpMapper.UserNameRegularExpressionMustBeValidRegularExpression") + "\");\n"+
" editconnection.usernameregexp.focus();\n"+
" return false;\n"+
" }\n"+
" return true;\n"+
"}\n"+
"\n"+
"function checkConfigForSave()\n"+
"{\n"+
" if (editconnection.usernameregexp.value == \"\")\n"+
" {\n"+
" alert(\"" + Messages.getBodyJavascriptString(locale,"RegexpMapper.UserNameRegularExpressionCannotBeNull") + "\");\n"+
" SelectTab(\"" + Messages.getBodyJavascriptString(locale,"RegexpMapper.UserMapping") + "\");\n"+
" editconnection.usernameregexp.focus();\n"+
" return false;\n"+
" }\n"+
" return true;\n"+
"}\n"+
"//-->\n"+
"</script>\n"
);
}
/** Output the configuration body section.
* This method is called in the body section of the authority connector's configuration page. Its purpose is to present the required form elements for editing.
* The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the
* form is "editconnection".
*@param threadContext is the local thread context.
*@param out is the output to which any HTML should be sent.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*@param tabName is the current tab name.
*/
@Override
public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out,
Locale locale, ConfigParams parameters, String tabName)
throws ManifoldCFException, IOException
{
String userNameMapping = parameters.getParameter(RegexpParameters.userNameMapping);
if (userNameMapping == null)
userNameMapping = "^(.*)\\\\@([A-Z|a-z|0-9|_|-]*)\\\\.(.*)$=$(2)\\\\$(1l)";
MatchMap matchMap = new MatchMap(userNameMapping);
String usernameRegexp = matchMap.getMatchString(0);
String livelinkUserExpr = matchMap.getReplaceString(0);
// The "User Mapping" tab
if (tabName.equals(Messages.getString(locale,"RegexpMapper.UserMapping")))
{
out.print(
"<table class=\"displaytable\">\n"+
" <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+
" <tr>\n"+
" <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"RegexpMapper.UserNameRegularExpressionColon") + "</nobr></td>\n"+
" <td class=\"value\"><input type=\"text\" size=\"40\" name=\"usernameregexp\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(usernameRegexp)+"\"/></td>\n"+
" </tr>\n"+
" <tr>\n"+
" <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"RegexpMapper.UserExpressionColon") + "</nobr></td>\n"+
" <td class=\"value\"><input type=\"text\" size=\"40\" name=\"livelinkuserexpr\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(livelinkUserExpr)+"\"/></td>\n"+
" </tr>\n"+
"</table>\n"
);
}
else
{
// Hiddens for "User Mapping" tab
out.print(
"<input type=\"hidden\" name=\"usernameregexp\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(usernameRegexp)+"\"/>\n"+
"<input type=\"hidden\" name=\"livelinkuserexpr\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(livelinkUserExpr)+"\"/>\n"
);
}
}
/** Process a configuration post.
* This method is called at the start of the authority connector's configuration page, whenever there is a possibility that form data for a connection has been
* posted. Its purpose is to gather form information and modify the configuration parameters accordingly.
* The name of the posted form is "editconnection".
*@param threadContext is the local thread context.
*@param variableContext is the set of variables available from the post, including binary file post information.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*@return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page).
*/
@Override
public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext,
Locale locale, ConfigParams parameters)
throws ManifoldCFException
{
// User name parameters
String usernameRegexp = variableContext.getParameter("usernameregexp");
String livelinkUserExpr = variableContext.getParameter("livelinkuserexpr");
if (usernameRegexp != null && livelinkUserExpr != null)
{
MatchMap matchMap = new MatchMap();
matchMap.appendMatchPair(usernameRegexp,livelinkUserExpr);
parameters.setParameter(RegexpParameters.userNameMapping,matchMap.toString());
}
return null;
}
/** View configuration.
* This method is called in the body section of the authority connector's view configuration page. Its purpose is to present the connection information to the user.
* The coder can presume that the HTML that is output from this configuration will be within appropriate <html> and <body> tags.
*@param threadContext is the local thread context.
*@param out is the output to which any HTML should be sent.
*@param parameters are the configuration parameters, as they currently exist, for this connection being configured.
*/
@Override
public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out,
Locale locale, ConfigParams parameters)
throws ManifoldCFException, IOException
{
MatchMap matchMap = new MatchMap(parameters.getParameter(RegexpParameters.userNameMapping));
String usernameRegexp = matchMap.getMatchString(0);
String livelinkUserExpr = matchMap.getReplaceString(0);
out.print(
"<table class=\"displaytable\">\n"+
" <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+
" <tr>\n"+
" <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"RegexpMapper.UserNameRegularExpressionColon") + "</nobr></td>\n"+
" <td class=\"value\"><nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(usernameRegexp)+"</nobr></td>\n"+
" </tr>\n"+
" <tr>\n"+
" <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"RegexpMapper.UserExpressionColon") + "</nobr></td>\n"+
" <td class=\"value\"><nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(livelinkUserExpr)+"</nobr></td>\n"+
" </tr>\n"+
"</table>\n"
);
}
}
| cogfor/mcf-cogfor | connectors/regexpmapper/connector/src/main/java/org/apache/manifoldcf/authorities/mappers/regexp/RegexpMapper.java | Java | apache-2.0 | 10,450 |
package org.nutz.mvc.impl;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionChain;
import org.nutz.mvc.ActionChainMaker;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.UrlMapping;
import org.nutz.mvc.annotation.BlankAtException;
public class UrlMappingImpl implements UrlMapping {
private static final Log log = Logs.get();
private Map<String, ActionInvoker> map;// 这个对象有点多余,考虑换成AtMap吧!!
private MappingNode<ActionInvoker> root;
public UrlMappingImpl() {
this.map = new HashMap<String, ActionInvoker>();
this.root = new MappingNode<ActionInvoker>();
}
public void add(ActionChainMaker maker, ActionInfo ai, NutConfig config) {
//检查所有的path
String[] paths = ai.getPaths();
for (int i = 0; i < paths.length; i++) {
String path = paths[i];
if (Strings.isBlank(path))
throw new BlankAtException(ai.getModuleType(), ai.getMethod());
if (path.charAt(0) != '/')
paths[i] = '/' + path;
}
ActionChain chain = maker.eval(config, ai);
for (String path : ai.getPaths()) {
// 尝试获取,看看有没有创建过这个 URL 调用者
ActionInvoker invoker = map.get(path);
// 如果没有增加过这个 URL 的调用者,为其创建备忘记录,并加入索引
if (null == invoker) {
invoker = new ActionInvoker();
map.put(path, invoker);
root.add(path, invoker);
// 记录一下方法与 url 的映射
config.getAtMap().addMethod(path, ai.getMethod());
}
// 将动作链,根据特殊的 HTTP 方法,保存到调用者内部
if (ai.isForSpecialHttpMethod()) {
for (String httpMethod : ai.getHttpMethods())
invoker.addChain(httpMethod, chain);
}
// 否则,将其设置为默认动作链
else {
invoker.setDefaultChain(chain);
}
}
printActionMapping(ai);
// TODO 下面个IF要不要转换到NutLoading中去呢?
// 记录一个 @At.key
if (!Strings.isBlank(ai.getPathKey()))
config.getAtMap().add(ai.getPathKey(), ai.getPaths()[0]);
}
public ActionInvoker get(ActionContext ac) {
String path = Mvcs.getRequestPath(ac.getRequest());
ActionInvoker invoker = root.get(ac, path);
if (invoker != null) {
ActionChain chain = invoker.getActionChain(ac);
if (chain != null) {
if (log.isDebugEnabled()) {
log.debugf("Found mapping for [%s] path=%s : %s", ac.getRequest().getMethod(), path, chain);
}
return invoker;
}
}
if (log.isDebugEnabled())
log.debugf("Search mapping for path=%s : NOT Action match", path);
return null;
}
protected void printActionMapping(ActionInfo ai) {
/*
* 打印基本调试信息
*/
if (log.isDebugEnabled()) {
// 打印路径
String[] paths = ai.getPaths();
StringBuilder sb = new StringBuilder();
if (null != paths && paths.length > 0) {
sb.append(" '").append(paths[0]).append("'");
for (int i = 1; i < paths.length; i++)
sb.append(", '").append(paths[i]).append("'");
} else {
throw Lang.impossible();
}
// 打印方法名
Method method = ai.getMethod();
String str;
if (null != method)
str = String.format("%-30s : %-10s",Lang.simpleMetodDesc(method), method.getReturnType().getSimpleName());
else
throw Lang.impossible();
log.debugf( "%s >> %s | @Ok(%-5s) @Fail(%-5s) | by %d Filters | (I:%s/O:%s)",
Strings.alignLeft(sb, 30, ' '),
str,
ai.getOkView(),
ai.getFailView(),
(null == ai.getFilterInfos() ? 0 : ai.getFilterInfos().length),
ai.getInputEncoding(),
ai.getOutputEncoding());
}
}
}
| qinqinnb/nutz | src/org/nutz/mvc/impl/UrlMappingImpl.java | Java | apache-2.0 | 4,682 |
/*
* Copyright 2013 the original author or 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.jayway.restassured.itest.java;
import com.jayway.restassured.itest.java.support.WithJetty;
import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.http.ContentType.URLENC;
import static org.hamcrest.Matchers.equalTo;
public class BodyWithCustomContentTypeITest extends WithJetty {
@Test
public void bodyIsUrlEncodedWhenSettingBody() throws Exception {
given().
contentType(URLENC).
body("firstName=John&lastName=Doe&").
expect().
body("greeting.firstName", equalTo("John")).
body("greeting.lastName", equalTo("Doe")).
when().
post("/greetXML");
}
}
| lanwen/rest-assured | examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java/BodyWithCustomContentTypeITest.java | Java | apache-2.0 | 1,360 |
// Copyright (c) 2013, Facebook, Inc. All rights reserved.
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.facebook.hive.orc;
import it.unimi.dsi.fastutil.ints.IntArrays;
import it.unimi.dsi.fastutil.ints.IntComparator;
import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap;
import org.apache.hadoop.hive.ql.io.slice.SizeOf;
import java.io.IOException;
import java.io.OutputStream;
class IntDictionaryEncoder extends DictionaryEncoder {
private long newKey;
private int numElements = 0;
private final int numBytes;
private final boolean useVInts;
protected final DynamicLongArray keys;
protected final DynamicIntArray counts;
protected Long2IntOpenHashMapWithByteSize dictionary = new Long2IntOpenHashMapWithByteSize();
public IntDictionaryEncoder(int numBytes, boolean useVInts, MemoryEstimate memoryEstimate) {
this(true, numBytes, useVInts, memoryEstimate);
}
public IntDictionaryEncoder(boolean sortKeys, int numBytes, boolean useVInts,
MemoryEstimate memoryEstimate) {
super(sortKeys, memoryEstimate);
this.numBytes = numBytes;
this.useVInts = useVInts;
this.keys = new DynamicLongArray(memoryEstimate);
this.counts = new DynamicIntArray(memoryEstimate);
}
public long getValue(int position) {
return keys.get(position);
}
private class Long2IntOpenHashMapWithByteSize extends Long2IntOpenHashMap {
private static final long serialVersionUID = 0L;
public Long2IntOpenHashMapWithByteSize() {
super();
memoryEstimate.incrementTotalMemory(getByteSize());
}
@Override
protected void rehash(final int newN) {
// rehash resizes the arrays, so need to account for this in the memory estimate
memoryEstimate.decrementTotalMemory(getByteSize());
super.rehash(newN);
memoryEstimate.incrementTotalMemory(getByteSize());
}
public int getByteSize() {
int size = key.length * 8 + value.length * 4 + used.length;
return size;
}
// A cleanup method that should be called before allowing the object to leave scope
public void cleanup() {
// Account for the destruction of the arrays used by this object
memoryEstimate.decrementTotalMemory(getByteSize());
}
}
/**
*
*/
public class LongPositionComparator implements IntComparator {
@Override
public int compare(Integer pos, Integer cmpPos) {
return this.compare(pos.intValue(), cmpPos.intValue());
}
@Override
public int compare(int pos, int cmpPos) {
return compareValue(keys.get(pos), keys.get(cmpPos));
}
}
public void visitDictionary(Visitor<Long> visitor, IntDictionaryEncoderVisitorContext context) throws IOException {
int[] keysArray = null;
if (sortKeys) {
keysArray = new int[numElements];
for (int idx = 0; idx < numElements; idx++) {
keysArray[idx] = idx;
}
IntArrays.quickSort(keysArray, new LongPositionComparator());
}
for (int pos = 0; pos < numElements; pos++) {
context.setOriginalPosition(keysArray == null? pos : keysArray[pos]);
visitor.visit(context);
}
}
public void visit(Visitor<Long> visitor) throws IOException {
visitDictionary(visitor, new IntDictionaryEncoderVisitorContext());
}
@Override
public void clear() {
keys.clear();
counts.clear();
dictionary.cleanup();
dictionary = new Long2IntOpenHashMapWithByteSize();
// Decrement the dictionary memory by the total size of all the elements
memoryEstimate.decrementDictionaryMemory(SizeOf.SIZE_OF_LONG * numElements);
numElements = 0;
}
private int compareValue (long k, long cmpKey) {
if (k > cmpKey) {
return 1;
} else if (k < cmpKey) {
return -1;
}
return 0;
}
@Override
protected int compareValue(int position) {
long cmpKey = keys.get(position);
return compareValue(newKey, cmpKey);
}
public int add (long value) {
newKey = value;
if (dictionary.containsKey(value)) {
int index = dictionary.get(value);
counts.increment(index, 1);
return dictionary.get(value);
} else {
int valRow = numElements;
numElements++;
dictionary.put(value, valRow);
keys.add(newKey);
counts.add(1);
// Add the size of one element to the dictionary size in memory
memoryEstimate.incrementDictionaryMemory(SizeOf.SIZE_OF_LONG);
return valRow;
}
}
public class IntDictionaryEncoderVisitorContext implements VisitorContext<Long> {
int originalPosition;
public void setOriginalPosition(int pos) {
originalPosition = pos;
}
public int getOriginalPosition() {
return originalPosition;
}
public Long getKey() {
return keys.get(originalPosition);
}
public void writeBytes(OutputStream outputStream) throws IOException {
long cur = keys.get(originalPosition);
SerializationUtils.writeIntegerType(outputStream, cur, numBytes, true, useVInts);
}
// TODO: this should be different
public int getLength() {
return 8;
}
public int getCount() {
return counts.get(originalPosition);
}
@Override
public int getIndexStride() {
throw new UnsupportedOperationException("IntDictionaryEncoder does not currently track the" +
" index stride");
}
}
public int getUncompressedLength() {
// The amount of memory used by entries in the dictionary
return numElements * 8;
}
/**
* Get the number of elements in the set.
*/
@Override
public int size() {
return numElements;
}
// A cleanup method that should be called before allowing the object to leave scope
public void cleanup() {
keys.cleanup();
counts.cleanup();
dictionary.cleanup();
// Decrement the dictionary memory by the total size of all the elements
memoryEstimate.decrementDictionaryMemory(SizeOf.SIZE_OF_LONG * numElements);
}
}
| facebookarchive/hive-dwrf | hive-dwrf/src/main/java/com/facebook/hive/orc/IntDictionaryEncoder.java | Java | apache-2.0 | 6,735 |
/**
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smackx.xhtmlim.packet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.namespace.QName;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.MessageView;
import org.jivesoftware.smack.util.XmlStringBuilder;
/**
* An XHTML sub-packet, which is used by XMPP clients to exchange formatted text. The XHTML
* extension is only a subset of XHTML 1.0.
* <p>
* The following link summarizes the requirements of XHTML IM:
* <a href="http://www.xmpp.org/extensions/xep-0071.html">XEP-0071: XHTML-IM</a>.
* </p>
*
* @author Gaston Dombiak
*/
public final class XHTMLExtension implements ExtensionElement {
public static final String ELEMENT = "html";
public static final String NAMESPACE = "http://jabber.org/protocol/xhtml-im";
public static final QName QNAME = new QName(NAMESPACE, ELEMENT);
private final List<CharSequence> bodies = new ArrayList<>();
/**
* Returns the XML element name of the extension sub-packet root element.
* Always returns "html"
*
* @return the XML element name of the stanza extension.
*/
@Override
public String getElementName() {
return ELEMENT;
}
/**
* Returns the XML namespace of the extension sub-packet root element.
* According the specification the namespace is always "http://jabber.org/protocol/xhtml-im"
*
* @return the XML namespace of the stanza extension.
*/
@Override
public String getNamespace() {
return NAMESPACE;
}
/**
* Returns the XML representation of a XHTML extension according the specification.
*
* Usually the XML representation will be inside of a Message XML representation like
* in the following example:
* <pre>
* <message id="MlIpV-4" to="[email protected]" from="[email protected]/Smack">
* <subject>Any subject you want</subject>
* <body>This message contains something interesting.</body>
* <html xmlns="http://jabber.org/protocol/xhtml-im">
* <body><p style='font-size:large'>This message contains something <em>interesting</em>.</p></body>
* </html>
* </message>
* </pre>
*
*/
@Override
public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
XmlStringBuilder xml = new XmlStringBuilder(this);
xml.rightAngleBracket();
// Loop through all the bodies and append them to the string buffer
for (CharSequence body : getBodies()) {
xml.append(body);
}
xml.closeElement(this);
return xml;
}
/**
* Returns a List of the bodies in the packet.
*
* @return a List of the bodies in the packet.
*/
public List<CharSequence> getBodies() {
synchronized (bodies) {
return Collections.unmodifiableList(new ArrayList<>(bodies));
}
}
/**
* Adds a body to the packet.
*
* @param body the body to add.
*/
public void addBody(CharSequence body) {
synchronized (bodies) {
bodies.add(body);
}
}
/**
* Returns a count of the bodies in the XHTML packet.
*
* @return the number of bodies in the XHTML packet.
*/
public int getBodiesCount() {
synchronized (bodies) {
return bodies.size();
}
}
public static XHTMLExtension from(MessageView message) {
return message.getExtension(XHTMLExtension.class);
}
}
| igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/xhtmlim/packet/XHTMLExtension.java | Java | apache-2.0 | 4,288 |
/**
* Copyright 2015-2017 Red Hat, Inc, and individual contributors.
*
* 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.wildfly.swarm.bootstrap.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* @author Juan Gonzalez
*/
public class BootstrapUtil {
private BootstrapUtil() {
}
/**
* Extracts a jar file into a target destination directory
* @param jarFile
* @param destDir
* @throws IOException
*/
public static void explodeJar(JarFile jarFile, String destDir) throws IOException {
Enumeration<java.util.jar.JarEntry> enu = jarFile.entries();
while (enu.hasMoreElements()) {
JarEntry je = enu.nextElement();
File fl = new File(destDir, je.getName());
if (!fl.exists()) {
fl.getParentFile().mkdirs();
fl = new File(destDir, je.getName());
}
if (je.isDirectory()) {
continue;
}
InputStream is = null;
try {
is = jarFile.getInputStream(je);
Files.copy(is, fl.toPath(), StandardCopyOption.REPLACE_EXISTING);
} finally {
if (is != null) {
is.close();
}
}
}
}
} | heiko-braun/wildfly-swarm-1 | core/bootstrap/src/main/java/org/wildfly/swarm/bootstrap/util/BootstrapUtil.java | Java | apache-2.0 | 2,003 |
/*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.utils;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* Created by gl49 on 2018/6/8.
*/
public class NetUtil {
private static final int DEFAULT_TIMEOUT_IN_SECONDS = 5000;
/**
* ping the url, return true if ping ok, false otherwise
*/
public static boolean pingUrl(String address) {
try {
URL urlObj = new URL(address);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setConnectTimeout(DEFAULT_TIMEOUT_IN_SECONDS);
connection.setReadTimeout(DEFAULT_TIMEOUT_IN_SECONDS);
int statusCode = connection.getResponseCode();
cleanUpConnection(connection);
return (200 <= statusCode && statusCode <= 399);
} catch (Throwable ignore) {
}
return false;
}
/**
* according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html, we should clean up the
* connection by reading the response body so that the connection could be reused.
*/
private static void cleanUpConnection(HttpURLConnection conn) {
InputStreamReader isr = null;
InputStreamReader esr = null;
try {
isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
CharStreams.toString(isr);
} catch (IOException e) {
InputStream errorStream = conn.getErrorStream();
if (errorStream != null) {
esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8);
try {
CharStreams.toString(esr);
} catch (IOException ioe) {
//ignore
}
}
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException ex) {
// ignore
}
}
if (esr != null) {
try {
esr.close();
} catch (IOException ex) {
// ignore
}
}
}
}
}
| lepdou/apollo | apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/NetUtil.java | Java | apache-2.0 | 2,757 |
package org.ovirt.engine.core.common.businessentities.profiles;
import java.util.HashMap;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.Identifiable;
public enum ProfileType implements Identifiable {
DISK(1),
CPU(2);
private final int value;
private static final Map<Integer, ProfileType> valueToStatus = new HashMap<>();
static {
for (ProfileType status : values()) {
valueToStatus.put(status.getValue(), status);
}
}
private ProfileType(int value) {
this.value = value;
}
@Override
public int getValue() {
return value;
}
public static ProfileType forValue(int value) {
return valueToStatus.get(value);
}
}
| OpenUniversity/ovirt-engine | backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/profiles/ProfileType.java | Java | apache-2.0 | 750 |
package org.apereo.cas.support.saml.web.idp.profile.sso;
import lombok.extern.slf4j.Slf4j;
import net.shibboleth.utilities.java.support.xml.ParserPool;
import org.apache.commons.lang3.tuple.Pair;
import org.apereo.cas.authentication.AuthenticationSystemSupport;
import org.apereo.cas.authentication.principal.ServiceFactory;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.saml.OpenSamlConfigBean;
import org.apereo.cas.support.saml.SamlIdPConstants;
import org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver;
import org.apereo.cas.support.saml.web.idp.profile.AbstractSamlProfileHandlerController;
import org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileObjectBuilder;
import org.apereo.cas.support.saml.web.idp.profile.builders.enc.SamlIdPObjectSigner;
import org.apereo.cas.support.saml.web.idp.profile.builders.enc.SamlObjectSignatureValidator;
import org.apereo.cas.support.saml.web.idp.profile.sso.request.SSOSamlHttpRequestExtractor;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.messaging.decoder.servlet.BaseHttpServletRequestXMLMessageDecoder;
import org.opensaml.saml.common.SignableSAMLObject;
import org.opensaml.saml.saml2.binding.decoding.impl.HTTPPostDecoder;
import org.opensaml.saml.saml2.binding.decoding.impl.HTTPRedirectDeflateDecoder;
import org.opensaml.saml.saml2.core.AuthnRequest;
import org.opensaml.saml.saml2.core.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The {@link SSOSamlPostProfileHandlerController} is responsible for
* handling profile requests for SAML2 Web SSO.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Slf4j
public class SSOSamlPostProfileHandlerController extends AbstractSamlProfileHandlerController {
private final SSOSamlHttpRequestExtractor samlHttpRequestExtractor;
public SSOSamlPostProfileHandlerController(final SamlIdPObjectSigner samlObjectSigner,
final ParserPool parserPool,
final AuthenticationSystemSupport authenticationSystemSupport,
final ServicesManager servicesManager,
final ServiceFactory<WebApplicationService> webApplicationServiceFactory,
final SamlRegisteredServiceCachingMetadataResolver samlRegisteredServiceCachingMetadataResolver,
final OpenSamlConfigBean configBean,
final SamlProfileObjectBuilder<Response> responseBuilder,
final CasConfigurationProperties casProperties,
final SamlObjectSignatureValidator samlObjectSignatureValidator,
final SSOSamlHttpRequestExtractor samlHttpRequestExtractor) {
super(samlObjectSigner,
parserPool,
authenticationSystemSupport,
servicesManager,
webApplicationServiceFactory,
samlRegisteredServiceCachingMetadataResolver,
configBean,
responseBuilder,
casProperties,
samlObjectSignatureValidator);
this.samlHttpRequestExtractor = samlHttpRequestExtractor;
}
/**
* Handle SSO POST profile request.
*
* @param response the response
* @param request the request
* @throws Exception the exception
*/
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_REDIRECT)
public void handleSaml2ProfileSsoRedirectRequest(final HttpServletResponse response,
final HttpServletRequest request) throws Exception {
handleSsoPostProfileRequest(response, request, new HTTPRedirectDeflateDecoder());
}
/**
* Handle SSO POST profile request.
*
* @param response the response
* @param request the request
* @throws Exception the exception
*/
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST)
public void handleSaml2ProfileSsoPostRequest(final HttpServletResponse response,
final HttpServletRequest request) throws Exception {
handleSsoPostProfileRequest(response, request, new HTTPPostDecoder());
}
/**
* Handle profile request.
*
* @param response the response
* @param request the request
* @param decoder the decoder
* @throws Exception the exception
*/
public void handleSsoPostProfileRequest(final HttpServletResponse response,
final HttpServletRequest request,
final BaseHttpServletRequestXMLMessageDecoder decoder) throws Exception {
final Pair<? extends SignableSAMLObject, MessageContext> authnRequest =
this.samlHttpRequestExtractor.extract(request, decoder, AuthnRequest.class);
initiateAuthenticationRequest(authnRequest, response, request);
}
}
| dodok1/cas | support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/sso/SSOSamlPostProfileHandlerController.java | Java | apache-2.0 | 5,515 |
package com.pushtorefresh.storio3.sqlite.annotations;
@StorIOSQLiteType(table = "table")
public class BoxedTypesMethodsFactoryMethodIgnoreNull {
private Boolean field1;
private Short field2;
private Integer field3;
private Long field4;
private Float field5;
private Double field6;
@StorIOSQLiteCreator
public static BoxedTypesMethodsFactoryMethodIgnoreNull create(Boolean field1, Short field2, Integer field3, Long field4,
Float field5, Double field6) {
return new BoxedTypesMethodsFactoryMethodIgnoreNull(field1, field2, field3, field4, field5, field6);
}
private BoxedTypesMethodsFactoryMethodIgnoreNull(Boolean field1, Short field2, Integer field3, Long field4, Float field5,
Double field6) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
this.field4 = field4;
this.field5 = field5;
this.field6 = field6;
}
@StorIOSQLiteColumn(name = "field1", ignoreNull = true)
public Boolean getField1() {
return field1;
}
@StorIOSQLiteColumn(name = "field2", ignoreNull = true)
public Short getField2() {
return field2;
}
@StorIOSQLiteColumn(name = "field3", ignoreNull = true)
public Integer getField3() {
return field3;
}
@StorIOSQLiteColumn(name = "field4", key = true, ignoreNull = true)
public Long getField4() {
return field4;
}
@StorIOSQLiteColumn(name = "field5", ignoreNull = true)
public Float getField5() {
return field5;
}
@StorIOSQLiteColumn(name = "field6", ignoreNull = true)
public Double getField6() {
return field6;
}
} | pushtorefresh/storio | storio-sqlite-annotations-processor-test/src/test/resources/BoxedTypesMethodsFactoryMethodIgnoreNull.java | Java | apache-2.0 | 1,801 |
/*-------------------------------------------------------------------------------------------------------------------*\
| Copyright (C) 2016 PayPal |
| |
| 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.paypal.selion.platform.grid;
import com.paypal.selion.internal.platform.grid.MobileNodeType;
import com.paypal.selion.internal.platform.grid.WebDriverPlatform;
import com.paypal.selion.platform.grid.browsercapabilities.DefaultCapabilitiesBuilder;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
/**
* A service provider interface that mobile driver providers for SeLion client (that use IOSDriver, Selendroid
* or Appium etc.) must implement.
* <p>
* This is a service loaded extension for SeLion client mobile driver providers.
*/
public interface MobileDriverProvider {
/**
* @return <code>true</code> If mobile driver provider implementation supports the specified {@link MobileNodeType}.
*/
boolean supports(MobileNodeType nodeType);
/**
* Creates an instance of a RemoteWebDriver using mobile driver implementation
*
* @return An instance of a {@link RemoteWebDriver} for the mobile driver implementation.
*/
RemoteWebDriver createDriver(WebDriverPlatform platform, CommandExecutor commandExecutor, URL url,
Capabilities capabilities);
/**
* Creates an instance of a CapabilitiesBuilder for mobile driver implementation
*
* @return An instance of a {@link DefaultCapabilitiesBuilder} for the mobile driver implementation.
*/
DefaultCapabilitiesBuilder capabilityBuilder();
}
| paypal/SeLion | client/src/main/java/com/paypal/selion/platform/grid/MobileDriverProvider.java | Java | apache-2.0 | 3,209 |
package com.xthena.auth.rs;
public class RoleDTO {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| jianbingfang/xhf | src/main/java/com/xthena/auth/rs/RoleDTO.java | Java | apache-2.0 | 344 |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.screens.projecteditor.client.forms.dependencies;
import java.util.HashSet;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.guvnor.common.services.project.model.Dependency;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.services.shared.dependencies.EnhancedDependency;
import org.kie.workbench.common.services.shared.dependencies.NormalEnhancedDependency;
import org.kie.workbench.common.services.shared.dependencies.TransitiveEnhancedDependency;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith( GwtMockitoTestRunner.class )
public class RemoveColumnTest {
private RemoveColumn removeColumn;
private SafeHtmlBuilder safeHtmlBuilder;
@Before
public void setUp() throws Exception {
removeColumn = new RemoveColumn();
safeHtmlBuilder = new SafeHtmlBuilder();
}
@Test
public void testRenderScopeCompile() throws Exception {
render( new NormalEnhancedDependency( new Dependency(),
new HashSet<String>() ) );
assertFalse( safeHtmlBuilder.toSafeHtml().asString().contains( " disabled=\"disabled\"" ) );
}
@Test
public void testRenderScopeTransitive() throws Exception {
render( new TransitiveEnhancedDependency( new Dependency(),
new HashSet<String>() ) );
assertTrue( safeHtmlBuilder.toSafeHtml().asString().contains( " disabled=\"disabled\"" ) );
}
private void render( final EnhancedDependency dependency ) {
removeColumn.render( mock( Cell.Context.class ),
dependency,
safeHtmlBuilder );
}
} | ederign/kie-wb-common | kie-wb-common-screens/kie-wb-common-project-editor/kie-wb-common-project-editor-client/src/test/java/org/kie/workbench/common/screens/projecteditor/client/forms/dependencies/RemoveColumnTest.java | Java | apache-2.0 | 2,530 |
package nl.tno.stormcv.model.serializer;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.VideoChunk;
public class VideoChunkSerializer extends CVParticleSerializer<VideoChunk> implements Serializable{
private static final long serialVersionUID = 7864791957493203664L;
public static final String VIDEO = "video";
public static final String TIMESTAMP = "timeStamp";
public static final String CONTAINER = "container";
@Override
protected List<String> getTypeFields() {
List<String> fields = new ArrayList<String>();
fields.add(TIMESTAMP);
fields.add(VIDEO);
fields.add(CONTAINER);
return fields;
}
@Override
protected Values getValues(CVParticle object) throws IOException {
VideoChunk video = (VideoChunk)object;
return new Values(video.getDuration(), video.getVideo(), video.getContainer());
}
@Override
protected VideoChunk createObject(Tuple tuple) throws IOException {
return new VideoChunk(tuple, tuple.getLongByField(TIMESTAMP),
tuple.getBinaryByField(VIDEO), tuple.getStringByField(CONTAINER));
}
@Override
protected void writeObject(Kryo kryo, Output output, VideoChunk video) throws Exception {
output.writeLong(video.getDuration());
output.writeInt(video.getVideo().length);
output.writeBytes(video.getVideo());
output.writeString(video.getContainer());
}
@Override
protected VideoChunk readObject(Kryo kryo, Input input, Class<VideoChunk> clas, long requestId, String streamId, long sequenceNr) throws Exception {
long duration = input.readLong();
int length = input.readInt();
byte[] video = input.readBytes(length);
String container = input.readString();
VideoChunk chunk = new VideoChunk(streamId, sequenceNr, duration, video, container);
chunk.setRequestId(requestId);
return chunk;
}
}
| sensorstorm/StormCV | stormcv/src/main/java/nl/tno/stormcv/model/serializer/VideoChunkSerializer.java | Java | apache-2.0 | 2,108 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.apache.camel.component.aws.kinesis.springboot;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.camel.CamelContext;
import org.apache.camel.component.aws.kinesis.KinesisComponent;
import org.apache.camel.spi.ComponentCustomizer;
import org.apache.camel.spi.HasId;
import org.apache.camel.spring.boot.CamelAutoConfiguration;
import org.apache.camel.spring.boot.ComponentConfigurationProperties;
import org.apache.camel.spring.boot.util.CamelPropertiesHelper;
import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans;
import org.apache.camel.spring.boot.util.GroupCondition;
import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator;
import org.apache.camel.support.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
/**
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@Configuration
@Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class,
KinesisComponentAutoConfiguration.GroupConditions.class})
@AutoConfigureAfter(CamelAutoConfiguration.class)
@EnableConfigurationProperties({ComponentConfigurationProperties.class,
KinesisComponentConfiguration.class})
public class KinesisComponentAutoConfiguration {
private static final Logger LOGGER = LoggerFactory
.getLogger(KinesisComponentAutoConfiguration.class);
@Autowired
private ApplicationContext applicationContext;
@Autowired
private CamelContext camelContext;
@Autowired
private KinesisComponentConfiguration configuration;
@Autowired(required = false)
private List<ComponentCustomizer<KinesisComponent>> customizers;
static class GroupConditions extends GroupCondition {
public GroupConditions() {
super("camel.component", "camel.component.aws-kinesis");
}
}
@Lazy
@Bean(name = "aws-kinesis-component")
@ConditionalOnMissingBean(KinesisComponent.class)
public KinesisComponent configureKinesisComponent() throws Exception {
KinesisComponent component = new KinesisComponent();
component.setCamelContext(camelContext);
Map<String, Object> parameters = new HashMap<>();
IntrospectionSupport.getProperties(configuration, parameters, null,
false);
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
Object value = entry.getValue();
Class<?> paramClass = value.getClass();
if (paramClass.getName().endsWith("NestedConfiguration")) {
Class nestedClass = null;
try {
nestedClass = (Class) paramClass.getDeclaredField(
"CAMEL_NESTED_CLASS").get(null);
HashMap<String, Object> nestedParameters = new HashMap<>();
IntrospectionSupport.getProperties(value, nestedParameters,
null, false);
Object nestedProperty = nestedClass.newInstance();
CamelPropertiesHelper.setCamelProperties(camelContext,
nestedProperty, nestedParameters, false);
entry.setValue(nestedProperty);
} catch (NoSuchFieldException e) {
}
}
}
CamelPropertiesHelper.setCamelProperties(camelContext, component,
parameters, false);
if (ObjectHelper.isNotEmpty(customizers)) {
for (ComponentCustomizer<KinesisComponent> customizer : customizers) {
boolean useCustomizer = (customizer instanceof HasId)
? HierarchicalPropertiesEvaluator.evaluate(
applicationContext.getEnvironment(),
"camel.component.customizer",
"camel.component.aws-kinesis.customizer",
((HasId) customizer).getId())
: HierarchicalPropertiesEvaluator.evaluate(
applicationContext.getEnvironment(),
"camel.component.customizer",
"camel.component.aws-kinesis.customizer");
if (useCustomizer) {
LOGGER.debug("Configure component {}, with customizer {}",
component, customizer);
customizer.customize(component);
}
}
}
return component;
}
} | objectiser/camel | platforms/spring-boot/components-starter/camel-aws-kinesis-starter/src/main/java/org/apache/camel/component/aws/kinesis/springboot/KinesisComponentAutoConfiguration.java | Java | apache-2.0 | 6,164 |
/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/
package io.cloudslang.lang.systemtests;
import ch.lambdaj.group.Group;
import com.google.common.collect.Lists;
import io.cloudslang.lang.runtime.RuntimeConstants;
import io.cloudslang.lang.runtime.env.ReturnValues;
import io.cloudslang.lang.runtime.events.LanguageEventData;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static ch.lambdaj.Lambda.*;
/**
* Date: 4/8/2015
*
* @author Bonczidai Levente
*/
public class BranchAggregatorListener extends AbstractAggregatorListener {
public Map<String, List<StepData>> aggregate() {
Map<String, List<StepData>> branchesDataByPath = new HashMap<>();
Group<LanguageEventData> groups = group(getEvents(), by(on(LanguageEventData.class).getPath()));
for (Group<LanguageEventData> subGroup : groups.subgroups()) {
List<StepData> branchesData = buildBranchesData(subGroup.findAll());
branchesDataByPath.put(branchesData.get(0).getPath(), branchesData);
}
return branchesDataByPath;
}
private List<StepData> buildBranchesData(List<LanguageEventData> data) {
List<StepData> branches = Lists.newArrayList();
for (LanguageEventData branchData : data) {
String path = branchData.getPath();
String stepName = branchData.getStepName();
ReturnValues returnValues = (ReturnValues) branchData.get(RuntimeConstants.BRANCH_RETURN_VALUES_KEY);
branches.add(
new StepData(
path,
stepName,
new HashMap<String, Serializable>(),
returnValues.getOutputs(),
null, returnValues.getResult()
)
);
}
return branches;
}
}
| jrosadohp/cloud-slang | cloudslang-tests/src/main/java/io/cloudslang/lang/systemtests/BranchAggregatorListener.java | Java | apache-2.0 | 2,351 |
/*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.examples.examination.domain;
import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
import org.optaplanner.examples.common.domain.AbstractPersistable;
import org.optaplanner.examples.examination.domain.solver.ExamDifficultyWeightFactory;
import org.optaplanner.examples.examination.domain.solver.RoomStrengthWeightFactory;
import com.thoughtworks.xstream.annotations.XStreamInclude;
@PlanningEntity(difficultyWeightFactoryClass = ExamDifficultyWeightFactory.class)
@XStreamInclude({
LeadingExam.class,
FollowingExam.class
})
public abstract class Exam extends AbstractPersistable {
protected Topic topic;
// Planning variables: changes during planning, between score calculations.
protected Room room;
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
@PlanningVariable(valueRangeProviderRefs = { "roomRange" }, strengthWeightFactoryClass = RoomStrengthWeightFactory.class)
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
// ************************************************************************
// Complex methods
// ************************************************************************
public abstract Period getPeriod();
public int getTopicDuration() {
return getTopic().getDuration();
}
public int getTopicStudentSize() {
return getTopic().getStudentSize();
}
public int getDayIndex() {
Period period = getPeriod();
if (period == null) {
return Integer.MIN_VALUE;
}
return period.getDayIndex();
}
public int getPeriodIndex() {
Period period = getPeriod();
if (period == null) {
return Integer.MIN_VALUE;
}
return period.getPeriodIndex();
}
public int getPeriodDuration() {
Period period = getPeriod();
if (period == null) {
return Integer.MIN_VALUE;
}
return period.getDuration();
}
public boolean isTopicFrontLoadLarge() {
return topic.isFrontLoadLarge();
}
public boolean isPeriodFrontLoadLast() {
Period period = getPeriod();
if (period == null) {
return false;
}
return period.isFrontLoadLast();
}
public String getLabel() {
return Long.toString(topic.getId());
}
@Override
public String toString() {
return topic.toString();
}
}
| ge0ffrey/optaplanner | optaplanner-examples/src/main/java/org/optaplanner/examples/examination/domain/Exam.java | Java | apache-2.0 | 3,281 |
/**
* Copyright (C) 2015 the original author or 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 mujava.op.basic;
import openjava.mop.*;
import openjava.ptree.*;
/**
* <p> </p>
* @author Yu-Seung Ma
* @version 1.0
*/
public class Arithmetic_OP extends MethodLevelMutator
{
public Arithmetic_OP(FileEnvironment file_env, CompilationUnit comp_unit)
{
super( file_env, comp_unit );
}
/**
* Determine whether a given expression is of arithmetic type
* @param p
* @return
* @throws ParseTreeException
*/
public boolean isArithmeticType(Expression p) throws ParseTreeException
{
OJClass type = getType(p);
if ( type == OJSystem.INT || type == OJSystem.DOUBLE || type == OJSystem.FLOAT
|| type == OJSystem.LONG || type == OJSystem.SHORT
|| type == OJSystem.CHAR || type == OJSystem.BYTE )
{
return true;
}
return false;
}
/**
* Determine whether a given expression has a binary arithmetic operator
* @param p
* @return
* @throws ParseTreeException
*/
public boolean hasBinaryArithmeticOp( BinaryExpression p ) throws ParseTreeException
{
int op_type = p.getOperator();
if ( (op_type == BinaryExpression.TIMES) || (op_type == BinaryExpression.DIVIDE)
|| (op_type == BinaryExpression.MOD) || (op_type == BinaryExpression.PLUS)
|| (op_type == BinaryExpression.MINUS))
return true;
else
return false;
}
}
| CruorVolt/mu_bbmap | src/mujava/op/basic/Arithmetic_OP.java | Java | apache-2.0 | 2,024 |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.impl.cmd;
import java.util.List;
import org.camunda.bpm.engine.BadUserRequestException;
import org.camunda.bpm.engine.impl.batch.BatchElementConfiguration;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.util.EnsureUtil;
public class SetExternalTasksRetriesCmd extends AbstractSetExternalTaskRetriesCmd<Void> {
public SetExternalTasksRetriesCmd(UpdateExternalTaskRetriesBuilderImpl builder) {
super(builder);
}
@Override
public Void execute(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = collectExternalTaskIds(commandContext);
List<String> collectedIds = elementConfiguration.getIds();
EnsureUtil.ensureNotEmpty(BadUserRequestException.class, "externalTaskIds", collectedIds);
int instanceCount = collectedIds.size();
writeUserOperationLog(commandContext, instanceCount, false);
int retries = builder.getRetries();
for (String externalTaskId : collectedIds) {
new SetExternalTaskRetriesCmd(externalTaskId, retries, false)
.execute(commandContext);
}
return null;
}
}
| langfr/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/cmd/SetExternalTasksRetriesCmd.java | Java | apache-2.0 | 1,967 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.apache.phoenix.end2end;
import static org.apache.phoenix.util.TestUtil.A_VALUE;
import static org.apache.phoenix.util.TestUtil.ROW1;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.util.PropertiesUtil;
import org.junit.Test;
public class UpsertSelectAutoCommitIT extends BaseHBaseManagedTimeTableReuseIT {
public UpsertSelectAutoCommitIT() {
}
@Test
public void testAutoCommitUpsertSelect() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
String atable = generateRandomString();
conn.createStatement().execute("CREATE TABLE " + atable
+ " (ORGANIZATION_ID CHAR(15) NOT NULL, ENTITY_ID CHAR(15) NOT NULL, A_STRING VARCHAR\n"
+
"CONSTRAINT pk PRIMARY KEY (organization_id, entity_id))");
String tenantId = getOrganizationId();
// Insert all rows at ts
PreparedStatement stmt = conn.prepareStatement(
"upsert into " + atable +
"(" +
" ORGANIZATION_ID, " +
" ENTITY_ID, " +
" A_STRING " +
" )" +
"VALUES (?, ?, ?)");
stmt.setString(1, tenantId);
stmt.setString(2, ROW1);
stmt.setString(3, A_VALUE);
stmt.execute();
String query = "SELECT entity_id, a_string FROM " + atable;
PreparedStatement statement = conn.prepareStatement(query);
ResultSet rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(ROW1, rs.getString(1));
assertEquals(A_VALUE, rs.getString(2));
assertFalse(rs.next());
String atable2 = generateRandomString();
conn.createStatement().execute("CREATE TABLE " + atable2
+ " (ORGANIZATION_ID CHAR(15) NOT NULL, ENTITY_ID CHAR(15) NOT NULL, A_STRING VARCHAR\n"
+
"CONSTRAINT pk PRIMARY KEY (organization_id, entity_id DESC))");
conn.createStatement().execute("UPSERT INTO " + atable2 + " SELECT * FROM " + atable);
query = "SELECT entity_id, a_string FROM " + atable2;
statement = conn.prepareStatement(query);
rs = statement.executeQuery();
assertTrue(rs.next());
assertEquals(ROW1, rs.getString(1));
assertEquals(A_VALUE, rs.getString(2));
assertFalse(rs.next());
}
@Test
public void testDynamicUpsertSelect() throws Exception {
Connection conn = DriverManager.getConnection(getUrl());
String tableName = generateRandomString();
String cursorDDL = " CREATE TABLE IF NOT EXISTS " + tableName
+ " (ORGANIZATION_ID VARCHAR(15) NOT NULL, \n"
+ "QUERY_ID VARCHAR(15) NOT NULL, \n"
+ "CURSOR_ORDER UNSIGNED_LONG NOT NULL, \n"
+ "CONSTRAINT API_HBASE_CURSOR_STORAGE_PK PRIMARY KEY (ORGANIZATION_ID, QUERY_ID, CURSOR_ORDER))\n"
+ "SALT_BUCKETS = 4";
conn.createStatement().execute(cursorDDL);
String tableName2 = generateRandomString();
String dataTableDDL = "CREATE TABLE IF NOT EXISTS " + tableName2 +
"(" +
"ORGANIZATION_ID CHAR(15) NOT NULL, " +
"PLINY_ID CHAR(15) NOT NULL, " +
"CREATED_DATE DATE NOT NULL, " +
"TEXT VARCHAR, " +
"CONSTRAINT PK PRIMARY KEY " +
"(" +
"ORGANIZATION_ID, " +
"PLINY_ID, " +
"CREATED_DATE" +
")" +
")";
conn.createStatement().execute(dataTableDDL);
PreparedStatement stmt = null;
String upsert = "UPSERT INTO " + tableName2 + " VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(upsert);
stmt.setString(1, getOrganizationId());
stmt.setString(2, "aaaaaaaaaaaaaaa");
stmt.setDate(3, new Date(System.currentTimeMillis()));
stmt.setString(4, "text");
stmt.executeUpdate();
conn.commit();
String upsertSelect = "UPSERT INTO " + tableName
+
" (ORGANIZATION_ID, QUERY_ID, CURSOR_ORDER, PLINY_ID CHAR(15),CREATED_DATE DATE) SELECT ?, ?, ?, PLINY_ID, CREATED_DATE FROM "
+ tableName2 + " WHERE ORGANIZATION_ID = ?";
stmt = conn.prepareStatement(upsertSelect);
String orgId = getOrganizationId();
stmt.setString(1, orgId);
stmt.setString(2, "queryqueryquery");
stmt.setInt(3, 1);
stmt.setString(4, orgId);
stmt.executeUpdate();
conn.commit();
}
@Test
public void testUpsertSelectDoesntSeeUpsertedData() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
props.setProperty(QueryServices.MUTATE_BATCH_SIZE_ATTRIB, Integer.toString(3));
props.setProperty(QueryServices.SCAN_CACHE_SIZE_ATTRIB, Integer.toString(3));
props.setProperty(QueryServices.SCAN_RESULT_CHUNK_SIZE, Integer.toString(3));
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
conn.createStatement().execute("CREATE SEQUENCE keys");
String tableName = generateRandomString();
conn.createStatement().execute(
"CREATE TABLE " + tableName + " (pk INTEGER PRIMARY KEY, val INTEGER)");
conn.createStatement().execute(
"UPSERT INTO " + tableName + " VALUES (NEXT VALUE FOR keys,1)");
for (int i=0; i<6; i++) {
Statement stmt = conn.createStatement();
int upsertCount = stmt.executeUpdate(
"UPSERT INTO " + tableName + " SELECT NEXT VALUE FOR keys, val FROM " + tableName);
assertEquals((int)Math.pow(2, i), upsertCount);
}
conn.close();
}
}
| RCheungIT/phoenix | phoenix-core/src/it/java/org/apache/phoenix/end2end/UpsertSelectAutoCommitIT.java | Java | apache-2.0 | 7,212 |
/*
* #%L
* SparkCommerce Common Libraries
* %%
* Copyright (C) 2015 Spark Commerce
* %%
*/
package org.sparkcommerce.common.web;
import org.thymeleaf.templatemode.ITemplateModeHandler;
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import java.util.HashSet;
import java.util.Set;
public class SparkThymeleafStandardTemplateModeHandlers {
public static final Set<ITemplateModeHandler> ALL_SC_TEMPLATE_MODE_HANDLERS = new HashSet<ITemplateModeHandler>();
static {
for (ITemplateModeHandler handler : StandardTemplateModeHandlers.ALL_TEMPLATE_MODE_HANDLERS) {
ALL_SC_TEMPLATE_MODE_HANDLERS.add(wrapHandler(handler));
}
}
protected static ITemplateModeHandler wrapHandler(ITemplateModeHandler handler) {
return new SparkThymeleafTemplateModeHandler(handler);
}
public Set<ITemplateModeHandler> getStandardTemplateModeHandlers() {
return ALL_SC_TEMPLATE_MODE_HANDLERS;
}
}
| akdasari/SparkCommon | src/main/java/org/sparkcommerce/common/web/SparkThymeleafStandardTemplateModeHandlers.java | Java | apache-2.0 | 988 |
package mat.client.measure;
import com.google.gwt.user.client.rpc.IsSerializable;
// TODO: Auto-generated Javadoc
/**
* The Class PeriodModel.
*/
public class PeriodModel implements IsSerializable{
/** The uuid. */
private String uuid;
/** The start date. */
private String startDate;
/** The stop date. */
private String stopDate;
/** The start date uuid. */
//private String startDateUuid;
/** The stop date uuid. */
//private String stopDateUuid;
private boolean calenderYear;
/**
* Checks if is calender year.
*
* @return true, if is calender year
*/
public boolean isCalenderYear() {
return calenderYear;
}
/**
* Sets the calender year.
*
* @param isCalenderYear the new calender year
*/
public void setCalenderYear(boolean calenderYear) {
this.calenderYear = calenderYear;
}
/**
* Gets the uuid.
*
* @return the uuid
*/
public String getUuid() {
return uuid;
}
/**
* Sets the uuid.
*
* @param uuid
* the uuid to set
*/
public void setUuid(String uuid) {
this.uuid = uuid;
}
/**
* Gets the start date.
*
* @return the startDate
*/
public String getStartDate() {
return startDate;
}
/**
* Sets the start date.
*
* @param startDate
* the startDate to set
*/
public void setStartDate(String startDate) {
this.startDate = startDate;
}
/**
* Gets the stop date.
*
* @return the stopDate
*/
public String getStopDate() {
return stopDate;
}
/**
* Sets the stop date.
*
* @param stopDate
* the stopDate to set
*/
public void setStopDate(String stopDate) {
this.stopDate = stopDate;
}
/**
* Gets the start date uuid.
*
* @return the startDateUuid
*/
// public String getStartDateUuid() {
// return startDateUuid;
// }
//
// /**
// * Sets the start date uuid.
// *
// * @param startDateUuid
// * the startDateUuid to set
// */
// public void setStartDateUuid(String startDateUuid) {
// this.startDateUuid = startDateUuid;
// }
//
// /**
// * Gets the stop date uuid.
// *
// * @return the stopDateUuid
// */
// public String getStopDateUuid() {
// return stopDateUuid;
// }
//
// /**
// * Sets the stop date uuid.
// *
// * @param stopDateUuid
// * the stopDateUuid to set
// */
// public void setStopDateUuid(String stopDateUuid) {
// this.stopDateUuid = stopDateUuid;
// }
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "PeriodModel [uuid=" + uuid + ", startDate=" + startDate
+ ", stopDate=" + stopDate + "]";
}
}
| JaLandry/MeasureAuthoringTool_LatestSprint | mat/src/mat/client/measure/PeriodModel.java | Java | apache-2.0 | 2,618 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.apache.hadoop.hdfs;
import org.apache.hadoop.conf.Configuration;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class TestDatanodeLayoutUpgrade {
private static final String HADOOP_DATANODE_DIR_TXT =
"hadoop-datanode-dir.txt";
private static final String HADOOP24_DATANODE = "hadoop-24-datanode-dir.tgz";
private static final String HADOOP_56_DN_LAYOUT_TXT =
"hadoop-to-57-dn-layout-dir.txt";
private static final String HADOOP_56_DN_LAYOUT =
"hadoop-56-layout-datanode-dir.tgz";
/**
* Upgrade from LDir-based layout to 32x32 block ID-based layout (-57) --
* change described in HDFS-6482 and HDFS-8791
*/
@Test
public void testUpgradeToIdBasedLayout() throws IOException {
TestDFSUpgradeFromImage upgrade = new TestDFSUpgradeFromImage();
upgrade.unpackStorage(HADOOP24_DATANODE, HADOOP_DATANODE_DIR_TXT);
Configuration conf = new Configuration(TestDFSUpgradeFromImage.upgradeConf);
conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY,
new File(System.getProperty("test.build.data"),
"dfs" + File.separator + "data").toURI().toString());
conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
new File(System.getProperty("test.build.data"),
"dfs" + File.separator + "name").toURI().toString());
upgrade.upgradeAndVerify(new MiniDFSCluster.Builder(conf).numDataNodes(1)
.manageDataDfsDirs(false).manageNameDfsDirs(false), null);
}
/**
* Test upgrade from block ID-based layout 256x256 (-56) to block ID-based
* layout 32x32 (-57)
*/
@Test
public void testUpgradeFrom256To32Layout() throws IOException {
TestDFSUpgradeFromImage upgrade = new TestDFSUpgradeFromImage();
upgrade.unpackStorage(HADOOP_56_DN_LAYOUT, HADOOP_56_DN_LAYOUT_TXT);
Configuration conf = new Configuration(TestDFSUpgradeFromImage.upgradeConf);
conf.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY,
new File(System.getProperty("test.build.data"), "dfs" + File.separator
+ "data").toURI().toString());
conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
new File(System.getProperty("test.build.data"), "dfs" + File.separator
+ "name").toURI().toString());
upgrade.upgradeAndVerify(new MiniDFSCluster.Builder(conf).numDataNodes(1)
.manageDataDfsDirs(false).manageNameDfsDirs(false), null);
}
}
| NJUJYB/disYarn | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDatanodeLayoutUpgrade.java | Java | apache-2.0 | 3,203 |
/**
* Copyright 2010-2014 Axel Fontaine and the many contributors.
*
* 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.flywaydb.core.api.migration.jdbc;
import java.sql.Connection;
/**
* Interface to be implemented by Jdbc Java Migrations. By default the migration version and description will be extracted
* from the class name. This can be overriden by also implementing the MigrationInfoProvider interface, in which
* case it can be specified programmatically. The checksum of this migration (for validation) will also be null, unless
* the migration also implements the MigrationChecksumProvider, in which case it can be returned programmatically.
*/
public interface JdbcMigration {
/**
* Executes this migration. The execution will automatically take place within a transaction, when the underlying
* database supports it.
*
* @param connection The connection to use to execute statements.
* @throws Exception when the migration failed.
*/
void migrate(Connection connection) throws Exception;
}
| lnial/flyway | flyway-core/src/main/java/org/flywaydb/core/api/migration/jdbc/JdbcMigration.java | Java | apache-2.0 | 1,574 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*
*/
/*
* Created on Sep 7, 2004
*/
package org.apache.jmeter.save.converters;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.jmeter.reporters.ResultCollectorHelper;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.save.SaveService;
import org.apache.jmeter.save.TestResultWrapper;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
/**
* XStream Class to convert TestResultWrapper
*
*/
public class TestResultWrapperConverter extends AbstractCollectionConverter {
/**
* Returns the converter version; used to check for possible
* incompatibilities
*/
public static String getVersion() {
return "$Revision$"; //$NON-NLS-1$
}
/**
* @param arg0
*/
public TestResultWrapperConverter(Mapper arg0) {
super(arg0);
}
/** {@inheritDoc} */
@Override
public boolean canConvert(@SuppressWarnings("rawtypes") Class arg0) { // superclass does not use types
return arg0.equals(TestResultWrapper.class);
}
/** {@inheritDoc} */
@Override
public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
// Not used, as the <testResult> element is generated by the
// ResultCollector class
}
/**
* Read test results from JTL files and pass them to the visualiser directly.
* If the ResultCollector helper object is defined, then pass the samples to that
* rather than adding them to the test result wrapper.
*
* @return the test result wrapper (may be empty)
*
* @see com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader,
* com.thoughtworks.xstream.converters.UnmarshallingContext)
*/
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
TestResultWrapper results = new TestResultWrapper();
Collection<SampleResult> samples = new ArrayList<SampleResult>();
String ver = reader.getAttribute("version"); //$NON-NLS-1$
if (ver == null || ver.length() == 0) {
ver = "1.0"; //$NON-NLS-1$
}
results.setVersion(ver);
ConversionHelp.setInVersion(ver);// Make sure decoding follows input file
final ResultCollectorHelper resultCollectorHelper = (ResultCollectorHelper) context.get(SaveService.RESULTCOLLECTOR_HELPER_OBJECT);
while (reader.hasMoreChildren()) {
reader.moveDown();
SampleResult sample = (SampleResult) readItem(reader, context, results);
if (resultCollectorHelper != null) {
resultCollectorHelper.add(sample);
} else {
samples.add(sample);
}
reader.moveUp();
}
results.setSampleResults(samples);
return results;
}
}
| Nachiket90/jmeter-sample | src/core/org/apache/jmeter/save/converters/TestResultWrapperConverter.java | Java | apache-2.0 | 4,028 |
package com.tngtech.jgiven;
import com.tngtech.jgiven.annotation.AfterStage;
import com.tngtech.jgiven.annotation.ExpectedScenarioState;
import com.tngtech.jgiven.annotation.ProvidedScenarioState;
public class WhenTestStep extends Stage<WhenTestStep> {
@ExpectedScenarioState
int someIntValue;
@ExpectedScenarioState
int value1;
@ExpectedScenarioState
int value2;
@ProvidedScenarioState
int intResult;
int afterStageCalled;
public void both_values_are_multiplied_with_each_other() {
intResult = value1 * value2;
}
public void multiply_with_two() {
intResult = someIntValue * 2;
}
public WhenTestStep something_happens() {
return self();
}
public void an_exception_is_thrown() {
throw new RuntimeException();
}
@AfterStage
void someAfterStageMethod() {
afterStageCalled++;
}
public WhenTestStep one_parameter_is_used( String paramA ) {
return self();
}
public WhenTestStep another_parameter_is_used( String paramB ) {
return self();
}
}
| ahus1/JGiven | jgiven-core/src/test/java/com/tngtech/jgiven/WhenTestStep.java | Java | apache-2.0 | 1,102 |
// Copyright (C) 2018 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.google.gerrit.server.cache.mem;
import com.google.gerrit.extensions.config.FactoryModule;
import com.google.gerrit.server.ModuleImpl;
import com.google.gerrit.server.cache.CacheModule;
import com.google.gerrit.server.cache.ForwardingRemovalListener;
import com.google.gerrit.server.cache.MemoryCacheFactory;
@ModuleImpl(name = CacheModule.MEMORY_MODULE)
public class DefaultMemoryCacheModule extends FactoryModule {
@Override
protected void configure() {
factory(ForwardingRemovalListener.Factory.class);
bind(MemoryCacheFactory.class).to(DefaultMemoryCacheFactory.class);
}
}
| WANdisco/gerrit | java/com/google/gerrit/server/cache/mem/DefaultMemoryCacheModule.java | Java | apache-2.0 | 1,214 |
/*
* #%L
* SparkCommerce Open Admin Platform
* %%
* Copyright (C) 2009 - 2013 Spark Commerce
* %%
* 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.
* #L%
*/
package org.sparkcommerce.openadmin.server.security.domain;
import java.io.Serializable;
import java.util.Set;
/**
*
* @author jfischer
*
*/
public interface AdminRole extends Serializable {
public void setId(Long id);
public Long getId();
public String getName();
public void setName(String name);
public String getDescription();
public void setDescription(String description);
public Set<AdminPermission> getAllPermissions();
public AdminRole clone();
}
| akdasari/SparkAdmin | spark-open-admin-platform/src/main/java/org/sparkcommerce/openadmin/server/security/domain/AdminRole.java | Java | apache-2.0 | 1,174 |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.trans.steps.xsdvalidator;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.provider.http.HttpFileObject;
import org.apache.commons.vfs.provider.local.LocalFile;
import java.net.URL;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.xml.sax.SAXException;
/**
* Executes a xsd validator on the values in the input stream.
* New fields were calculated values can then be put on the output stream.
*
* @author Samatar
* @since 14-08-2007
*
*/
public class XsdValidator extends BaseStep implements StepInterface
{
private static Class<?> PKG = XsdValidatorMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private XsdValidatorMeta meta;
private XsdValidatorData data;
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
public XsdValidator(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(XsdValidatorMeta)smi;
data=(XsdValidatorData)sdi;
Object[] row = getRow();
if (row==null) // no more input to be expected...
{
setOutputDone();
return false;
}
if (first)
{
first=false;
data.outputRowMeta = getInputRowMeta().clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
// Check if XML stream is given
if (meta.getXMLStream()!=null)
{
// Try to get XML Field index
data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream());
// Let's check the Field
if (data.xmlindex<0)
{
// The field is unreachable !
logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorFindingField")+ "[" + meta.getXMLStream()+"]"); //$NON-NLS-1$ //$NON-NLS-2$
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.CouldnotFindField",meta.getXMLStream())); //$NON-NLS-1$ //$NON-NLS-2$
}
// Let's check that Result Field is given
if (meta.getResultfieldname() == null )
{
// Result field is missing !
logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
}
// Is XSD file is provided?
if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME))
{
if(meta.getXSDFilename()==null)
{
logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
}
else
{
// Is XSD file exists ?
FileObject xsdfile=null;
try
{
xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename()), getTransMeta());
if(!xsdfile.exists())
{
logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XSDFileNotExists"));
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.XSDFileNotExists"));
}
}
catch (Exception e)
{
logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.GettingXSDFile"));
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.GettingXSDFile"));
}
finally
{
try
{
if ( xsdfile != null ) xsdfile.close();
}
catch ( IOException e ) { }
}
}
}
// Is XSD field is provided?
if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME))
{
if(meta.getXSDDefinedField()==null)
{
logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XSDFieldMissing"));
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.XSDFieldMissing"));
}
else
{
// Let's check if the XSD field exist
// Try to get XML Field index
data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField());
if (data.xsdindex<0)
{
// The field is unreachable !
logError(BaseMessages.getString(PKG, "XsdValidator.Log.ErrorFindingXSDField",meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.ErrorFindingXSDField",meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
else
{
// XML stream field is missing !
logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
try
{
// Get the XML field value
String XMLFieldvalue= getInputRowMeta().getString(row,data.xmlindex);
boolean isvalid =false;
// XSD filename
String xsdfilename= null;
if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME))
{
xsdfilename= environmentSubstitute(meta.getXSDFilename());
}
else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME))
{
// Get the XSD field value
xsdfilename= getInputRowMeta().getString(row,data.xsdindex);
}
// Get XSD filename
FileObject xsdfile = null;
String validationmsg=null;
try
{
SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
xsdfile = KettleVFS.getFileObject(xsdfilename, getTransMeta());
// Get XML stream
Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue));
if(meta.getXMLSourceFile())
{
// We deal with XML file
// Get XML File
File xmlfileValidator = new File(XMLFieldvalue);
if (!xmlfileValidator.exists())
{
logError(BaseMessages.getString(PKG, "XsdValidator.Log.Error.XMLfileMissing",XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.XMLfileMissing",XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
}
sourceXML = new StreamSource(xmlfileValidator);
}
// create the schema
Schema SchematXSD = null;
if (xsdfile instanceof LocalFile) {
SchematXSD = factoryXSDValidator.newSchema(new File(KettleVFS.getFilename(xsdfile)));
}
else if (xsdfile instanceof HttpFileObject) {
SchematXSD = factoryXSDValidator.newSchema(new URL(KettleVFS.getFilename(xsdfile)));
}
else {
// we should not get here as anything entered in that does not look like
// a url should be made a FileObject.
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.Exception.CannotCreateSchema", xsdfile.getClass().getName()));
}
if (meta.getXSDSource().equals(meta.NO_NEED))
{
// ---Some documents specify the schema they expect to be validated against,
// ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes
//---Schema SchematXSD = factoryXSDValidator.newSchema();
SchematXSD = factoryXSDValidator.newSchema();
}
// Create XSDValidator
Validator XSDValidator = SchematXSD.newValidator();
// Validate XML / XSD
XSDValidator.validate(sourceXML);
isvalid=true;
}
catch (SAXException ex)
{
validationmsg=ex.getMessage();
}
catch (IOException ex)
{
validationmsg=ex.getMessage();
}
finally
{
try
{
if ( xsdfile != null ) xsdfile.close();
}
catch ( IOException e ) { }
}
Object[] outputRowData =null;
Object[] outputRowData2=null;
if(meta.getOutputStringField())
{
// Output type=String
if(isvalid)
outputRowData =RowDataUtil.addValueData(row, getInputRowMeta().size(),environmentSubstitute(meta.getIfXmlValid()));
else
outputRowData =RowDataUtil.addValueData(row, getInputRowMeta().size(),environmentSubstitute(meta.getIfXmlInvalid()));
}else{
outputRowData =RowDataUtil.addValueData(row, getInputRowMeta().size(),isvalid);
}
if(meta.useAddValidationMessage())
outputRowData2 =RowDataUtil.addValueData(outputRowData, getInputRowMeta().size()+1,validationmsg);
else
outputRowData2=outputRowData;
if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "XsdValidator.Log.ReadRow") + " " + getInputRowMeta().getString(row));
// add new values to the row.
putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s);
}
catch(KettleException e)
{
boolean sendToErrorRow=false;
String errorMessage = null;
if (getStepMeta().isDoingErrorHandling())
{
sendToErrorRow = true;
errorMessage = e.toString();
}
if (sendToErrorRow)
{
// Simply add this row to the error row
putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001");
}
else
{
logError(BaseMessages.getString(PKG, "XsdValidator.ErrorProcesing" + " : "+ e.getMessage()));
throw new KettleStepException(BaseMessages.getString(PKG, "XsdValidator.ErrorProcesing"), e);
}
}
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(XsdValidatorMeta)smi;
data=(XsdValidatorData)sdi;
if (super.init(smi, sdi))
{
// Add init code here.
return true;
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta = (XsdValidatorMeta) smi;
data = (XsdValidatorData) sdi;
super.dispose(smi, sdi);
}
} | soluvas/pdi-ce | src/org/pentaho/di/trans/steps/xsdvalidator/XsdValidator.java | Java | apache-2.0 | 12,453 |
/*
* Copyright (C) 2007 The Guava 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.google.common.util.concurrent;
import com.google.errorprone.annotations.DoNotMock;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
/**
* A {@link Future} that accepts completion listeners. Each listener has an associated executor, and
* it is invoked using this executor once the future's computation is {@linkplain Future#isDone()
* complete}. If the computation has already completed when the listener is added, the listener will
* execute immediately.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code
* ListenableFuture}</a>.
*
* <p>This class is GWT-compatible.
*
* <h3>Purpose</h3>
*
* <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
* asynchronous operations. You can chain them together manually with calls to methods like {@link
* Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)
* Futures.transform}, but you will often find it easier to use a framework. Frameworks automate the
* process, often adding features like monitoring, debugging, and cancellation. Examples of
* frameworks include:
*
* <ul>
* <li><a href="https://dagger.dev/producers.html">Dagger Producers</a>
* </ul>
*
* <p>The main purpose of {@link #addListener addListener} is to support this chaining. You will
* rarely use it directly, in part because it does not provide direct access to the {@code Future}
* result. (If you want such access, you may prefer {@link Futures#addCallback
* Futures.addCallback}.) Still, direct {@code addListener} calls are occasionally useful:
*
* <pre>{@code
* final String name = ...;
* inFlight.add(name);
* ListenableFuture<Result> future = service.query(name);
* future.addListener(new Runnable() {
* public void run() {
* processedCount.incrementAndGet();
* inFlight.remove(name);
* lastProcessed.set(name);
* logger.info("Done with {0}", name);
* }
* }, executor);
* }</pre>
*
* <h3>How to get an instance</h3>
*
* <p>We encourage you to return {@code ListenableFuture} from your methods so that your users can
* take advantage of the {@linkplain Futures utilities built atop the class}. The way that you will
* create {@code ListenableFuture} instances depends on how you currently create {@code Future}
* instances:
*
* <ul>
* <li>If you receive them from an {@code java.util.concurrent.ExecutorService}, convert that
* service to a {@link ListeningExecutorService}, usually by calling {@link
* MoreExecutors#listeningDecorator(java.util.concurrent.ExecutorService)
* MoreExecutors.listeningDecorator}.
* <li>If you manually call {@link java.util.concurrent.FutureTask#set} or a similar method,
* create a {@link SettableFuture} instead. (If your needs are more complex, you may prefer
* {@link AbstractFuture}.)
* </ul>
*
* <p><b>Test doubles</b>: If you need a {@code ListenableFuture} for your test, try a {@link
* SettableFuture} or one of the methods in the {@link Futures#immediateFuture Futures.immediate*}
* family. <b>Avoid</b> creating a mock or stub {@code Future}. Mock and stub implementations are
* fragile because they assume that only certain methods will be called and because they often
* implement subtleties of the API improperly.
*
* <p><b>Custom implementation</b>: Avoid implementing {@code ListenableFuture} from scratch. If you
* can't get by with the standard implementations, prefer to derive a new {@code Future} instance
* with the methods in {@link Futures} or, if necessary, to extend {@link AbstractFuture}.
*
* <p>Occasionally, an API will return a plain {@code Future} and it will be impossible to change
* the return type. For this case, we provide a more expensive workaround in {@code
* JdkFutureAdapters}. However, when possible, it is more efficient and reliable to create a {@code
* ListenableFuture} directly.
*
* @author Sven Mawson
* @author Nishant Thakkar
* @since 1.0
*/
@DoNotMock("Use the methods in Futures (like immediateFuture) or SettableFuture")
public interface ListenableFuture<V> extends Future<V> {
/**
* Registers a listener to be {@linkplain Executor#execute(Runnable) run} on the given executor.
* The listener will run when the {@code Future}'s computation is {@linkplain Future#isDone()
* complete} or, if the computation is already complete, immediately.
*
* <p>There is no guaranteed ordering of execution of listeners, but any listener added through
* this method is guaranteed to be called once the computation is complete.
*
* <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
* during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
* thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and
* logged.
*
* <p>Note: If your listener is lightweight -- and will not cause stack overflow by completing
* more futures or adding more {@code directExecutor()} listeners inline -- consider {@link
* MoreExecutors#directExecutor}. Otherwise, avoid it: See the warnings on the docs for {@code
* directExecutor}.
*
* <p>This is the most general listener interface. For common operations performed using
* listeners, see {@link Futures}. For a simplified but general listener interface, see {@link
* Futures#addCallback addCallback()}.
*
* <p>Memory consistency effects: Actions in a thread prior to adding a listener <a
* href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5">
* <i>happen-before</i></a> its execution begins, perhaps in another thread.
*
* <p>Guava implementations of {@code ListenableFuture} promptly release references to listeners
* after executing them.
*
* @param listener the listener to run when the computation is complete
* @param executor the executor to run the listener in
* @throws RejectedExecutionException if we tried to execute the listener immediately but the
* executor rejected it.
*/
void addListener(Runnable listener, Executor executor);
}
| typetools/guava | guava/src/com/google/common/util/concurrent/ListenableFuture.java | Java | apache-2.0 | 6,876 |
package twitter4j.internal.org.json;
/*
Copyright (c) 2006 JSON.org
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 shall be used for Good, not Evil.
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.
*/
import java.io.StringWriter;
/**
* JSONStringer provides a quick and convenient way of producing JSON text.
* The texts produced strictly conform to JSON syntax rules. No whitespace is
* added, so the results are ready for transmission or storage. Each instance of
* JSONStringer can produce one JSON text.
* <p>
* A JSONStringer instance provides a <code>value</code> method for appending
* values to the
* text, and a <code>key</code>
* method for adding keys before values in objects. There are <code>array</code>
* and <code>endArray</code> methods that make and bound array values, and
* <code>object</code> and <code>endObject</code> methods which make and bound
* object values. All of these methods return the JSONWriter instance,
* permitting cascade style. For example, <pre>
* myString = new JSONStringer()
* .object()
* .key("JSON")
* .value("Hello, World!")
* .endObject()
* .toString();</pre> which produces the string <pre>
* {"JSON":"Hello, World!"}</pre>
* <p>
* The first method called must be <code>array</code> or <code>object</code>.
* There are no methods for adding commas or colons. JSONStringer adds them for
* you. Objects and arrays can be nested up to 20 levels deep.
* <p>
* This can sometimes be easier than using a JSONObject to build a string.
* @author JSON.org
* @version 2008-09-18
*/
public class JSONStringer extends JSONWriter {
/**
* Make a fresh JSONStringer. It can be used to build one JSON text.
*/
public JSONStringer() {
super(new StringWriter());
}
/**
* Return the JSON text. This method is used to obtain the product of the
* JSONStringer instance. It will return <code>null</code> if there was a
* problem in the construction of the JSON text (such as the calls to
* <code>array</code> were not properly balanced with calls to
* <code>endArray</code>).
* @return The JSON text.
*/
public String toString() {
return this.mode == 'd' ? this.writer.toString() : null;
}
}
| twitter/twitter4j | twitter4j-core/src/main/java/twitter4j/internal/org/json/JSONStringer.java | Java | apache-2.0 | 3,285 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.