repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
uci-sdcl/lighthouse | main/LighthouseCore/src/edu/uci/lighthouse/core/listeners/JavaFileChangedReporter.java | 8397 | /*******************************************************************************
* Copyright (c) {2009,2011} {Software Design and Collaboration Laboratory (SDCL)
* , University of California, Irvine}.
* 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:
* {Software Design and Collaboration Laboratory (SDCL)
* , University of California, Irvine}
* - initial API and implementation and/or initial documentation
*******************************************************************************/
package edu.uci.lighthouse.core.listeners;
import java.util.Collection;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.BundleContext;
/**
* This class listen for changes in java files and notifies listeners whose
* implement <code>IJavaFileStatusListener</code> interface.
*
* @author tproenca
*@see IJavaFileStatusListener
*/
public class JavaFileChangedReporter implements IResourceChangeListener,
IElementChangedListener, IPluginListener {
/** List of listeners. */
Collection<IJavaFileStatusListener> listeners = new LinkedList<IJavaFileStatusListener>();
/** Logger instance. */
private static Logger logger = Logger
.getLogger(JavaFileChangedReporter.class);
@Override
public void start(BundleContext context) throws Exception {
logger.info("Starting JavaFileChangedReporter");
logger.debug("addElementChangedListener()");
JavaCore.addElementChangedListener(this,
ElementChangedEvent.POST_CHANGE);
logger.debug("addPreProcessingResourceChangedListener()");
JavaCore.addPreProcessingResourceChangedListener(this,
IResourceChangeEvent.POST_BUILD);
// FIXME: find a way to load eclipse workbench first to guarantee the
// file will be found
findActiveOpenFileInWorkspace();
}
@Override
public void stop(BundleContext context) throws Exception {
logger.info("Stopping JavaFileChangedReporter");
JavaCore.removePreProcessingResourceChangedListener(this);
JavaCore.removeElementChangedListener(this);
}
@Override
public void elementChanged(ElementChangedEvent event) {
IJavaElementDelta delta = event.getDelta();
logger.debug(delta);
traverseDeltaTree(delta);
}
@Override
public void resourceChanged(IResourceChangeEvent event) {
try {
IResourceDelta delta = event.getDelta();
delta.accept(new JavaFileResourceDeltaVisitor());
} catch (CoreException e) {
logger.error(e,e);
}
}
/** Finds the active open file in the workspace (The one with focus). */
private void findActiveOpenFileInWorkspace() {
logger.info("findActiveOpenFileInWorkspace");
Display.getDefault().asyncExec(new Runnable() {
public void run() {
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
IWorkbenchPage[] pages = window.getPages();
logger.debug("pages length: " + pages.length);
for (IWorkbenchPage page : pages) {
IEditorPart editor = page.getActiveEditor();
logger.debug("editor: " + editor);
if (editor != null) {
IFile file = (IFile) editor.getEditorInput()
.getAdapter(IFile.class);
if (isJavaFile(file)) {
try {
boolean hasErrors = IMarker.SEVERITY_ERROR == file
.findMaxProblemSeverity(
IMarker.PROBLEM, true,
IResource.DEPTH_INFINITE);
fireOpen(file, hasErrors);
} catch (CoreException e) {
logger.error(e,e);
}
}
}
}
}
});
}
/** Verifies if the resource is a java file. */
private boolean isJavaFile(IResource resource) {
return resource.getType() == IResource.FILE
&& resource.getFileExtension().equalsIgnoreCase("java");
}
/**
* Visits all nodes of the java element delta. It fires the events open and
* close.
*/
private void traverseDeltaTree(IJavaElementDelta delta) {
if (delta.getElement().getElementType() == IJavaElement.COMPILATION_UNIT) {
ICompilationUnit icu = (ICompilationUnit) delta.getElement();
IFile iFile = (IFile) icu.getResource();
if (iFile.exists()) {
try {
boolean hasErrors = IMarker.SEVERITY_ERROR == icu
.getResource().findMaxProblemSeverity(
IMarker.PROBLEM, true,
IResource.DEPTH_INFINITE);
if ((delta.getFlags() & IJavaElementDelta.F_PRIMARY_WORKING_COPY) != 0) {
if (icu.isWorkingCopy()) {
fireOpen(iFile, hasErrors);
} else {
fireClose(iFile, hasErrors);
}
}
} catch (Exception e) {
logger.error(e,e);
}
}
} else {
for (IJavaElementDelta child : delta.getAffectedChildren()) {
traverseDeltaTree(child);
}
}
}
/**
* Adds the listener to the list of listeners that will be notified when
* changes happens.
*/
public void addJavaFileStatusListener(IJavaFileStatusListener listener) {
listeners.add(listener);
}
/** Remove the listener from the list of listeners. */
public void removeJavaFileStatusListener(IJavaFileStatusListener listener) {
listeners.remove(listener);
}
/** Fires the open event. */
protected void fireOpen(IFile iFile, boolean hasErrors) {
logger.info("Opening " + iFile.getName() + " (errors:" + hasErrors
+ ")");
for (IJavaFileStatusListener listener : listeners) {
listener.open(iFile, hasErrors);
}
}
/** Fire the close event. */
protected void fireClose(IFile iFile, boolean hasErrors) {
logger.info("Closing " + iFile.getName() + " (errors:" + hasErrors
+ ")");
for (IJavaFileStatusListener listener : listeners) {
listener.close(iFile, hasErrors);
}
}
/** Fire the add event. */
protected void fireAdd(IFile iFile, boolean hasErrors) {
logger.info("Add " + iFile.getName() + " (errors:" + hasErrors + ")");
for (IJavaFileStatusListener listener : listeners) {
listener.add(iFile, hasErrors);
}
}
/** Fire the remove event. */
protected void fireRemove(IFile iFile, boolean hasErrors) {
logger.info("Removed " + iFile.getName() + " (errors:" + hasErrors
+ ")");
for (IJavaFileStatusListener listener : listeners) {
listener.remove(iFile, hasErrors);
}
}
/** Fire the change event. */
protected void fireChange(IFile iFile, boolean hasErrors) {
logger.info("Changing " + iFile.getName() + " (errors:" + hasErrors
+ ")");
for (IJavaFileStatusListener listener : listeners) {
listener.change(iFile, hasErrors);
}
}
/**
* This class uses the Visitor pattern to visit all nodes of the resource
* delta. It fires the events add, remove, and change.
*
*/
class JavaFileResourceDeltaVisitor implements IResourceDeltaVisitor {
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
if (isJavaFile(delta.getResource())) {
IFile iFile = (IFile) resource;
boolean hasErrors = false;
if (resource.exists()) {
hasErrors = IMarker.SEVERITY_ERROR == resource
.findMaxProblemSeverity(IMarker.PROBLEM, true,
IResource.DEPTH_INFINITE);
}
if (delta.getKind() == IResourceDelta.ADDED) {
fireAdd(iFile, hasErrors);
} else if (delta.getKind() == IResourceDelta.CHANGED) {
if ((delta.getFlags() & IResourceDelta.CONTENT) != 0) {
fireChange(iFile, hasErrors);
}
} else if (delta.getKind() == IResourceDelta.REMOVED) {
fireRemove(iFile, false);
}
}
return true;
}
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.homeconnect/src/main/java/org/openhab/binding/homeconnect/internal/client/model/Option.java | 1558 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.homeconnect.internal.client.model;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
/**
* Option model
*
* @author Jonas Brüstel - Initial contribution
*
*/
@NonNullByDefault
public class Option {
private final @Nullable String key;
private final @Nullable String value;
private final @Nullable String unit;
public Option(@Nullable String key, @Nullable String value, @Nullable String unit) {
this.key = key;
this.value = value;
this.unit = unit;
}
public @Nullable String getKey() {
return key;
}
public @Nullable String getValue() {
return value;
}
public boolean getValueAsBoolean() {
return Boolean.parseBoolean(value);
}
public int getValueAsInt() {
@Nullable
String stringValue = value;
return stringValue != null ? Integer.parseInt(stringValue) : 0;
}
public @Nullable String getUnit() {
return unit;
}
@Override
public String toString() {
return "Option [key=" + key + ", value=" + value + ", unit=" + unit + "]";
}
}
| epl-1.0 |
sleshchenko/che | plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/remote/RemotePresenter.java | 6089 | /*
* Copyright (c) 2012-2018 Red Hat, 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
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.ext.git.client.remote;
import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.FLOAT_MODE;
import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import javax.validation.constraints.NotNull;
import org.eclipse.che.api.git.shared.Remote;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.notification.NotificationManager;
import org.eclipse.che.ide.api.resources.Project;
import org.eclipse.che.ide.ext.git.client.GitLocalizationConstant;
import org.eclipse.che.ide.ext.git.client.GitServiceClient;
import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsole;
import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsoleFactory;
import org.eclipse.che.ide.ext.git.client.remote.add.AddRemoteRepositoryPresenter;
import org.eclipse.che.ide.processes.panel.ProcessesPanelPresenter;
/**
* Presenter for working with remote repository list (view, add and delete).
*
* @author Ann Zhuleva
* @author Vlad Zhukovskyi
*/
@Singleton
public class RemotePresenter implements RemoteView.ActionDelegate {
public static final String REMOTE_REPO_COMMAND_NAME = "Git list of remotes";
private final GitOutputConsoleFactory gitOutputConsoleFactory;
private final ProcessesPanelPresenter consolesPanelPresenter;
private final RemoteView view;
private final GitServiceClient service;
private final AppContext appContext;
private final GitLocalizationConstant constant;
private final AddRemoteRepositoryPresenter addRemoteRepositoryPresenter;
private final NotificationManager notificationManager;
private Remote selectedRemote;
private Project project;
@Inject
public RemotePresenter(
RemoteView view,
GitServiceClient service,
AppContext appContext,
GitLocalizationConstant constant,
AddRemoteRepositoryPresenter addRemoteRepositoryPresenter,
NotificationManager notificationManager,
GitOutputConsoleFactory gitOutputConsoleFactory,
ProcessesPanelPresenter processesPanelPresenter) {
this.view = view;
this.gitOutputConsoleFactory = gitOutputConsoleFactory;
this.consolesPanelPresenter = processesPanelPresenter;
this.view.setDelegate(this);
this.service = service;
this.appContext = appContext;
this.constant = constant;
this.addRemoteRepositoryPresenter = addRemoteRepositoryPresenter;
this.notificationManager = notificationManager;
}
/** Show dialog. */
public void showDialog(Project project) {
this.project = project;
getRemotes();
}
/**
* Get the list of remote repositories for local one. If remote repositories are found, then get
* the list of branches (remote and local).
*/
private void getRemotes() {
service
.remoteList(project.getLocation(), null, true)
.then(
remotes -> {
view.setEnableDeleteButton(selectedRemote != null);
view.setRemotes(remotes);
if (!view.isShown()) {
view.showDialog();
}
})
.catchError(
error -> {
String errorMessage =
error.getMessage() != null ? error.getMessage() : constant.remoteListFailed();
handleError(errorMessage);
});
}
/** {@inheritDoc} */
@Override
public void onCloseClicked() {
view.close();
}
/** {@inheritDoc} */
@Override
public void onAddClicked() {
addRemoteRepositoryPresenter.showDialog(
new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
getRemotes();
project.synchronize();
}
@Override
public void onFailure(Throwable caught) {
String errorMessage =
caught.getMessage() != null ? caught.getMessage() : constant.remoteAddFailed();
GitOutputConsole console = gitOutputConsoleFactory.create(REMOTE_REPO_COMMAND_NAME);
console.printError(errorMessage);
consolesPanelPresenter.addCommandOutput(console);
notificationManager.notify(constant.remoteAddFailed(), FAIL, FLOAT_MODE);
}
});
}
/** {@inheritDoc} */
@Override
public void onDeleteClicked() {
if (selectedRemote == null) {
handleError(constant.selectRemoteRepositoryFail());
return;
}
service
.remoteDelete(project.getLocation(), selectedRemote.getName())
.then(
ignored -> {
getRemotes();
project.synchronize();
})
.catchError(
error -> {
String errorMessage =
error.getMessage() != null ? error.getMessage() : constant.remoteDeleteFailed();
GitOutputConsole console = gitOutputConsoleFactory.create(REMOTE_REPO_COMMAND_NAME);
console.printError(errorMessage);
consolesPanelPresenter.addCommandOutput(console);
notificationManager.notify(constant.remoteDeleteFailed(), FAIL, FLOAT_MODE);
});
}
/** {@inheritDoc} */
@Override
public void onRemoteSelected(@NotNull Remote remote) {
selectedRemote = remote;
view.setEnableDeleteButton(selectedRemote != null);
}
private void handleError(@NotNull String errorMessage) {
GitOutputConsole console = gitOutputConsoleFactory.create(REMOTE_REPO_COMMAND_NAME);
console.printError(errorMessage);
consolesPanelPresenter.addCommandOutput(console);
notificationManager.notify(errorMessage);
}
}
| epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/linking/ignoreCaseImportsTest/Model.java | 1332 | /**
* generated by Xtext
*/
package org.eclipse.xtext.linking.ignoreCaseImportsTest;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Model</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.eclipse.xtext.linking.ignoreCaseImportsTest.Model#getImports <em>Imports</em>}</li>
* </ul>
*
* @see org.eclipse.xtext.linking.ignoreCaseImportsTest.IgnoreCaseImportsTestPackage#getModel()
* @model
* @generated
*/
public interface Model extends org.eclipse.xtext.linking.ignoreCaseLinkingTest.Model
{
/**
* Returns the value of the '<em><b>Imports</b></em>' containment reference list.
* The list contents are of type {@link org.eclipse.xtext.linking.ignoreCaseImportsTest.Import}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Imports</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Imports</em>' containment reference list.
* @see org.eclipse.xtext.linking.ignoreCaseImportsTest.IgnoreCaseImportsTestPackage#getModel_Imports()
* @model containment="true"
* @generated
*/
EList<Import> getImports();
} // Model
| epl-1.0 |
opendaylight/opflex | genie/src/main/java/org/opendaylight/opflex/genie/content/model/mnaming/MNamer.java | 4911 | package org.opendaylight.opflex.genie.content.model.mnaming;
import java.util.LinkedList;
import java.util.Map;
import org.opendaylight.opflex.genie.content.model.mclass.MClass;
import org.opendaylight.opflex.genie.engine.model.Cat;
import org.opendaylight.opflex.genie.engine.model.Item;
import org.opendaylight.opflex.modlan.report.Severity;
import org.opendaylight.opflex.modlan.utils.Strings;
/**
* Created by midvorki on 7/10/14.
*
* Specification of the namer rule for a class item. Identifies the naming properties used in
* formation of object LRIs/URIs. For a given class, Namer is a model item that identifies rules
* of how such class is named in a context of its many parents. Namer is identified by the global
* name of the class to which it corresponds. Naming rules within a namer can be asymmetrical/distinct
* amongst different containers. This is important, as managed object can have different naming properties based
* on what context its instantiated under.
*/
public class MNamer extends Item
{
/**
* category identifying all namer rules
*/
public static final Cat MY_CAT = Cat.getCreate("mnamer");
public static synchronized MNamer get(String aInGClassName, boolean aInCreateIfNotFound)
{
MNamer lNamer = (MNamer) MY_CAT.getItem(aInGClassName);
if (null == lNamer && aInCreateIfNotFound)
{
lNamer = new MNamer(aInGClassName);
}
else
{
// NOW, SINCE WE HAVEN'T FOUND THE NAMER, LET'S LOOK IN THE SUPERCLASS
MClass lClass = MClass.get(aInGClassName);
if (null != lClass)
{
for (lClass = lClass.getSuperclass(); null != lClass && null == lNamer; lClass = lClass.getSuperclass())
{
lNamer = (MNamer) MY_CAT.getItem(lClass.getGID().getName());
}
}
}
return lNamer;
}
/**
* Constructor.
* @param aInGClassName global class name corresponding to the class for which this naming rule is created.
*/
private MNamer(String aInGClassName)
{
super(MY_CAT,null,aInGClassName);
}
/**
* target class accessor. retrieves the class item corresponding to this naming rule.
* @return class for which this naming rule exists
*/
public MClass getTargetClass()
{
MClass lRet = MClass.get(getLID().getName());
if (null == lRet)
{
Severity.DEATH.report(
this.toString(),
"retrieval of target class",
"class not found",
"naming rule can't find associated class.");
}
return lRet;
}
public synchronized MNameRule getNameRule(String aInClassOrAny, boolean aInCreateIfNotFound)
{
MNameRule lNr = (MNameRule) getChildItem(MNameRule.MY_CAT,aInClassOrAny);
if (null == lNr && aInCreateIfNotFound)
{
lNr = new MNameRule(this,aInClassOrAny);
}
return lNr;
}
public MNameRule findNameRule(String aInParentClassOrNull)
{
MNameRule lRet = null;
aInParentClassOrNull = (Strings.isWildCard(aInParentClassOrNull)) ?
MClass.ROOT_CLASS_GNAME :
aInParentClassOrNull;
MClass lParentClass = MClass.get(aInParentClassOrNull);
if (null == lParentClass)
{
Severity.DEATH.report(
this.toString(),
"retrieval of name rule",
"class not found",
"parent class not found: " +
aInParentClassOrNull);
}
else
{
for (MClass lThisParentClass = lParentClass;
null == lRet && null != lThisParentClass;
lThisParentClass = lThisParentClass.getSuperclass())
{
lRet = getNameRule(lThisParentClass.getGID().getName(), false);
}
if (null == lRet)
{
lRet = getNameRule(Strings.ASTERISK, false);
}
}
return lRet;
}
public void getNamingRules(Map<String, MNameRule> aOut)
{
LinkedList<Item> lNRs = new LinkedList<>();
getChildItems(MNameRule.MY_CAT, lNRs);
for (Item lIt : lNRs)
{
if (!aOut.containsKey(lIt.getGID().getName()))
{
aOut.put(lIt.getGID().getName(), (MNameRule) lIt);
}
}
}
public MNamer getSuper()
{
MNamer lRet = null;
for (MClass lClass = getTargetClass().getSuperclass();
null == lRet && null != lClass;
lClass = lClass.getSuperclass())
{
lRet = MNamer.get(lClass.getGID().getName(),false);
}
return lRet;
}
}
| epl-1.0 |
SagnickBanerjee/Innovative-Ideas | com.in.innovative.ideas.branding/src/com/in/innovative/ideas/branding/ApplicationPerspectiveAdapter.java | 401 | package com.in.innovative.ideas.branding;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PerspectiveAdapter;
public class ApplicationPerspectiveAdapter extends PerspectiveAdapter {
@Override
public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
super.perspectiveActivated(page, perspective);
}
}
| epl-1.0 |
AriSuutariST/waffle | Source/JNA/waffle-tomcat9/src/test/java/waffle/apache/MixedAuthenticatorTests.java | 13846 | /**
* Waffle (https://github.com/Waffle/waffle)
*
* Copyright (c) 2010-2016 Application Security, 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
* https://www.eclipse.org/legal/epl-v10.html.
*
* Contributors: Application Security, Inc.
*/
package waffle.apache;
import java.util.Base64;
import javax.servlet.ServletException;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.LifecycleException;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.sun.jna.platform.win32.Sspi;
import com.sun.jna.platform.win32.Sspi.SecBufferDesc;
import mockit.Expectations;
import mockit.Mocked;
import waffle.apache.catalina.SimpleHttpRequest;
import waffle.apache.catalina.SimpleHttpResponse;
import waffle.mock.MockWindowsAuthProvider;
import waffle.windows.auth.IWindowsCredentialsHandle;
import waffle.windows.auth.IWindowsIdentity;
import waffle.windows.auth.PrincipalFormat;
import waffle.windows.auth.impl.WindowsAccountImpl;
import waffle.windows.auth.impl.WindowsCredentialsHandleImpl;
import waffle.windows.auth.impl.WindowsSecurityContextImpl;
/**
* Waffle Tomcat Mixed Authenticator Tests.
*
* @author dblock[at]dblock[dot]org
*/
public class MixedAuthenticatorTests {
/** The authenticator. */
MixedAuthenticator authenticator;
/** The context. */
@Mocked
Context context;
/** The engine. */
@Mocked
Engine engine;
/**
* Sets the up.
*
* @throws LifecycleException
* the lifecycle exception
*/
@Before
public void setUp() throws LifecycleException {
this.authenticator = new MixedAuthenticator();
this.authenticator.setContainer(this.context);
Assert.assertNotNull(new Expectations() {
{
MixedAuthenticatorTests.this.context.getParent();
this.result = MixedAuthenticatorTests.this.engine;
MixedAuthenticatorTests.this.context.getParent();
this.result = null;
}
});
this.authenticator.start();
}
/**
* Tear down.
*
* @throws LifecycleException
* the lifecycle exception
*/
@After
public void tearDown() throws LifecycleException {
this.authenticator.stop();
}
/**
* Test challenge get.
*/
@Test
public void testChallengeGET() {
final SimpleHttpRequest request = new SimpleHttpRequest();
request.setMethod("GET");
request.setQueryString("j_negotiate_check");
final SimpleHttpResponse response = new SimpleHttpResponse();
this.authenticator.authenticate(request, response);
final String[] wwwAuthenticates = response.getHeaderValues("WWW-Authenticate");
Assert.assertNotNull(wwwAuthenticates);
Assert.assertEquals(2, wwwAuthenticates.length);
Assert.assertEquals("Negotiate", wwwAuthenticates[0]);
Assert.assertEquals("NTLM", wwwAuthenticates[1]);
Assert.assertEquals("close", response.getHeader("Connection"));
Assert.assertEquals(2, response.getHeaderNames().size());
Assert.assertEquals(401, response.getStatus());
}
/**
* Test challenge post.
*/
@Test
public void testChallengePOST() {
final String securityPackage = "Negotiate";
IWindowsCredentialsHandle clientCredentials = null;
WindowsSecurityContextImpl clientContext = null;
try {
// client credentials handle
clientCredentials = WindowsCredentialsHandleImpl.getCurrent(securityPackage);
clientCredentials.initialize();
// initial client security context
clientContext = new WindowsSecurityContextImpl();
clientContext.setPrincipalName(WindowsAccountImpl.getCurrentUsername());
clientContext.setCredentialsHandle(clientCredentials);
clientContext.setSecurityPackage(securityPackage);
clientContext.initialize(null, null, WindowsAccountImpl.getCurrentUsername());
final SimpleHttpRequest request = new SimpleHttpRequest();
request.setQueryString("j_negotiate_check");
request.setMethod("POST");
request.setContentLength(0);
final String clientToken = Base64.getEncoder().encodeToString(clientContext.getToken());
request.addHeader("Authorization", securityPackage + " " + clientToken);
final SimpleHttpResponse response = new SimpleHttpResponse();
this.authenticator.authenticate(request, response);
Assert.assertTrue(response.getHeader("WWW-Authenticate").startsWith(securityPackage + " "));
Assert.assertEquals("keep-alive", response.getHeader("Connection"));
Assert.assertEquals(2, response.getHeaderNames().size());
Assert.assertEquals(401, response.getStatus());
} finally {
if (clientContext != null) {
clientContext.dispose();
}
if (clientCredentials != null) {
clientCredentials.dispose();
}
}
}
/**
* Test get.
*/
@Test
public void testGet() {
final SimpleHttpRequest request = new SimpleHttpRequest();
final SimpleHttpResponse response = new SimpleHttpResponse();
Assert.assertFalse(this.authenticator.authenticate(request, response));
}
/**
* Test get info.
*/
@Test
public void testGetInfo() {
Assertions.assertThat(this.authenticator.getInfo().length()).isGreaterThan(0);
}
/**
* Test negotiate.
*/
@Test
public void testNegotiate() {
final String securityPackage = "Negotiate";
IWindowsCredentialsHandle clientCredentials = null;
WindowsSecurityContextImpl clientContext = null;
try {
// client credentials handle
clientCredentials = WindowsCredentialsHandleImpl.getCurrent(securityPackage);
clientCredentials.initialize();
// initial client security context
clientContext = new WindowsSecurityContextImpl();
clientContext.setPrincipalName(WindowsAccountImpl.getCurrentUsername());
clientContext.setCredentialsHandle(clientCredentials);
clientContext.setSecurityPackage(securityPackage);
clientContext.initialize(null, null, WindowsAccountImpl.getCurrentUsername());
// negotiate
boolean authenticated = false;
final SimpleHttpRequest request = new SimpleHttpRequest();
request.setQueryString("j_negotiate_check");
String clientToken;
while (true) {
clientToken = Base64.getEncoder().encodeToString(clientContext.getToken());
request.addHeader("Authorization", securityPackage + " " + clientToken);
final SimpleHttpResponse response = new SimpleHttpResponse();
authenticated = this.authenticator.authenticate(request, response);
if (authenticated) {
Assertions.assertThat(response.getHeaderNames().size()).isGreaterThanOrEqualTo(0);
break;
}
Assert.assertTrue(response.getHeader("WWW-Authenticate").startsWith(securityPackage + " "));
Assert.assertEquals("keep-alive", response.getHeader("Connection"));
Assert.assertEquals(2, response.getHeaderNames().size());
Assert.assertEquals(401, response.getStatus());
final String continueToken = response.getHeader("WWW-Authenticate")
.substring(securityPackage.length() + 1);
final byte[] continueTokenBytes = Base64.getDecoder().decode(continueToken);
Assertions.assertThat(continueTokenBytes.length).isGreaterThan(0);
final SecBufferDesc continueTokenBuffer = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, continueTokenBytes);
clientContext.initialize(clientContext.getHandle(), continueTokenBuffer,
WindowsAccountImpl.getCurrentUsername());
}
Assert.assertTrue(authenticated);
} finally {
if (clientContext != null) {
clientContext.dispose();
}
if (clientCredentials != null) {
clientCredentials.dispose();
}
}
}
/**
* Test post security check.
*/
@Test
public void testPostSecurityCheck() {
final SimpleHttpRequest request = new SimpleHttpRequest();
request.setQueryString("j_security_check");
request.addParameter("j_username", "username");
request.addParameter("j_password", "password");
final SimpleHttpResponse response = new SimpleHttpResponse();
Assert.assertFalse(this.authenticator.authenticate(request, response));
}
/**
* Test programmatic security BOTH.
*
* @param identity
* the identity
* @throws ServletException
* the servlet exception
*/
@Test
public void testProgrammaticSecurityBoth(@Mocked final IWindowsIdentity identity) throws ServletException {
this.authenticator.setAuth(new MockWindowsAuthProvider());
final SimpleHttpRequest request = new SimpleHttpRequest();
request.getMappingData().context = (Context) this.authenticator.getContainer();
request.login(WindowsAccountImpl.getCurrentUsername(), "");
Assert.assertNotNull(new Expectations() {
{
identity.getFqn();
this.result = "fqn";
identity.getSidString();
this.result = "S-1234";
}
});
request.setUserPrincipal(new GenericWindowsPrincipal(identity, PrincipalFormat.BOTH, PrincipalFormat.BOTH));
Assert.assertTrue(request.getUserPrincipal() instanceof GenericWindowsPrincipal);
final GenericWindowsPrincipal windowsPrincipal = (GenericWindowsPrincipal) request.getUserPrincipal();
Assert.assertTrue(windowsPrincipal.getSidString().startsWith("S-"));
}
/**
* Test programmatic security SID.
*
* @param identity
* the identity
* @throws ServletException
* the servlet exception
*/
@Test
public void testProgrammaticSecuritySID(@Mocked final IWindowsIdentity identity) throws ServletException {
this.authenticator.setAuth(new MockWindowsAuthProvider());
final SimpleHttpRequest request = new SimpleHttpRequest();
request.getMappingData().context = (Context) this.authenticator.getContainer();
request.login(WindowsAccountImpl.getCurrentUsername(), "");
Assert.assertNotNull(new Expectations() {
{
identity.getSidString();
this.result = "S-1234";
}
});
request.setUserPrincipal(new GenericWindowsPrincipal(identity, PrincipalFormat.SID, PrincipalFormat.SID));
Assert.assertTrue(request.getUserPrincipal() instanceof GenericWindowsPrincipal);
final GenericWindowsPrincipal windowsPrincipal = (GenericWindowsPrincipal) request.getUserPrincipal();
Assert.assertTrue(windowsPrincipal.getSidString().startsWith("S-"));
}
/**
* Test programmatic security NONE.
*
* @param identity
* the identity
* @throws ServletException
* the servlet exception
*/
@Test
public void testProgrammaticSecurityNone(@Mocked final IWindowsIdentity identity) throws ServletException {
this.authenticator.setAuth(new MockWindowsAuthProvider());
final SimpleHttpRequest request = new SimpleHttpRequest();
request.getMappingData().context = (Context) this.authenticator.getContainer();
request.login(WindowsAccountImpl.getCurrentUsername(), "");
request.setUserPrincipal(new GenericWindowsPrincipal(identity, PrincipalFormat.NONE, PrincipalFormat.NONE));
Assert.assertTrue(request.getUserPrincipal() instanceof GenericWindowsPrincipal);
final GenericWindowsPrincipal windowsPrincipal = (GenericWindowsPrincipal) request.getUserPrincipal();
Assert.assertNull(windowsPrincipal.getSidString());
}
/**
* Test security check parameters.
*/
@Test
public void testSecurityCheckParameters() {
this.authenticator.setAuth(new MockWindowsAuthProvider());
final SimpleHttpRequest request = new SimpleHttpRequest();
request.addParameter("j_security_check", "");
request.addParameter("j_username", WindowsAccountImpl.getCurrentUsername());
request.addParameter("j_password", "");
final SimpleHttpResponse response = new SimpleHttpResponse();
Assert.assertTrue(this.authenticator.authenticate(request, response));
}
/**
* Test security check query string.
*/
@Test
public void testSecurityCheckQueryString() {
this.authenticator.setAuth(new MockWindowsAuthProvider());
final SimpleHttpRequest request = new SimpleHttpRequest();
request.setQueryString("j_security_check");
request.addParameter("j_username", WindowsAccountImpl.getCurrentUsername());
request.addParameter("j_password", "");
final SimpleHttpResponse response = new SimpleHttpResponse();
Assert.assertTrue(this.authenticator.authenticate(request, response));
}
}
| epl-1.0 |
rkadle/Tank | web/web_support/src/test/java/com/intuit/tank/config/PagesTest.java | 643 | package com.intuit.tank.config;
/*
* #%L
* JSF Support Beans
* %%
* 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%
*/
import org.junit.*;
import com.intuit.tank.config.Pages;
import static org.junit.Assert.*;
/**
* The class <code>PagesTest</code> contains tests for the class <code>{@link Pages}</code>.
*
* @generatedBy CodePro at 12/15/14 3:52 PM
*/
public class PagesTest {
} | epl-1.0 |
iWantMoneyMore/ykj | ykj-api/src/main/java/com/gnet/app/orderProcess/OrderProcessResource.java | 409 | package com.gnet.app.orderProcess;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
public class OrderProcessResource extends Resource<OrderProcess> {
public OrderProcessResource(OrderProcess content, Iterable<Link> links) {
super(content, links);
}
public OrderProcessResource(OrderProcess content, Link... links) {
super(content, links);
}
} | gpl-2.0 |
BuddhaLabs/DeD-OSX | soot/soot-2.3.0/src/soot/jimple/toolkits/infoflow/SimpleMethodInfoFlowAnalysis.java | 18723 | package soot.jimple.toolkits.infoflow;
import soot.*;
import java.util.*;
import soot.toolkits.graph.*;
import soot.toolkits.scalar.*;
import soot.jimple.internal.*;
import soot.jimple.*;
// SimpleMethodInfoFlowAnalysis written by Richard L. Halpert, 2007-02-25
// Constructs a data flow table for the given method. Ignores indirect flow.
// These tables conservatively approximate how data flows from parameters,
// fields, and globals to parameters, fields, globals, and the return value.
// Note that a ref-type parameter (or field or global) might allow access to a
// large data structure, but that entire structure will be represented only by
// the parameter's one node in the data flow graph.
public class SimpleMethodInfoFlowAnalysis extends ForwardFlowAnalysis
{
SootMethod sm;
Value thisLocal;
InfoFlowAnalysis dfa;
boolean refOnly;
MutableDirectedGraph infoFlowGraph;
Ref returnRef;
FlowSet entrySet;
FlowSet emptySet;
boolean printMessages;
public static int counter = 0;
public SimpleMethodInfoFlowAnalysis(UnitGraph g, InfoFlowAnalysis dfa, boolean ignoreNonRefTypeFlow)
{
this(g, dfa, ignoreNonRefTypeFlow, true);
counter++;
// Add all of the nodes necessary to ensure that this is a complete data flow graph
// Add every parameter of this method
for(int i = 0; i < sm.getParameterCount(); i++)
{
EquivalentValue parameterRefEqVal = InfoFlowAnalysis.getNodeForParameterRef(sm, i);
if(!infoFlowGraph.containsNode(parameterRefEqVal))
infoFlowGraph.addNode(parameterRefEqVal);
}
// Add every field of this class
for(Iterator it = sm.getDeclaringClass().getFields().iterator(); it.hasNext(); )
{
SootField sf = (SootField) it.next();
EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf);
if(!infoFlowGraph.containsNode(fieldRefEqVal))
infoFlowGraph.addNode(fieldRefEqVal);
}
// Add every field of this class's superclasses
SootClass superclass = sm.getDeclaringClass();
if(superclass.hasSuperclass())
superclass = sm.getDeclaringClass().getSuperclass();
while(superclass.hasSuperclass()) // we don't want to process Object
{
Iterator scFieldsIt = superclass.getFields().iterator();
while(scFieldsIt.hasNext())
{
SootField scField = (SootField) scFieldsIt.next();
EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, scField);
if(!infoFlowGraph.containsNode(fieldRefEqVal))
infoFlowGraph.addNode(fieldRefEqVal);
}
superclass = superclass.getSuperclass();
}
// Add thisref of this class
EquivalentValue thisRefEqVal = InfoFlowAnalysis.getNodeForThisRef(sm);
if(!infoFlowGraph.containsNode(thisRefEqVal))
infoFlowGraph.addNode(thisRefEqVal);
// Add returnref of this method
EquivalentValue returnRefEqVal = new CachedEquivalentValue(returnRef);
if(!infoFlowGraph.containsNode(returnRefEqVal))
infoFlowGraph.addNode(returnRefEqVal);
if(printMessages)
G.v().out.println("STARTING ANALYSIS FOR " + g.getBody().getMethod() + " -----");
doFlowInsensitiveAnalysis();
if(printMessages)
G.v().out.println("ENDING ANALYSIS FOR " + g.getBody().getMethod() + " -----");
}
/** A constructor that doesn't run the analysis */
protected SimpleMethodInfoFlowAnalysis(UnitGraph g, InfoFlowAnalysis dfa, boolean ignoreNonRefTypeFlow, boolean dummyDontRunAnalysisYet)
{
super(g);
this.sm = g.getBody().getMethod();
if(sm.isStatic())
this.thisLocal = null;
else
this.thisLocal = g.getBody().getThisLocal();
this.dfa = dfa;
this.refOnly = ignoreNonRefTypeFlow;
this.infoFlowGraph = new MemoryEfficientGraph();
this.returnRef = new ParameterRef(g.getBody().getMethod().getReturnType(), -1); // it's a dummy parameter ref
this.entrySet = new ArraySparseSet();
this.emptySet = new ArraySparseSet();
printMessages = false;
}
public void doFlowInsensitiveAnalysis()
{
FlowSet fs = (FlowSet) newInitialFlow();
boolean flowSetChanged = true;
while(flowSetChanged)
{
int sizebefore = fs.size();
Iterator stmtIt = graph.iterator();
while(stmtIt.hasNext())
{
Stmt s = (Stmt) stmtIt.next();
flowThrough(fs, s, fs);
}
if(fs.size() > sizebefore)
flowSetChanged = true;
else
flowSetChanged = false;
}
}
public MutableDirectedGraph getMethodInfoFlowSummary()
{
return infoFlowGraph;
}
protected void merge(Object in1, Object in2, Object out)
{
FlowSet inSet1 = (FlowSet) in1;
FlowSet inSet2 = (FlowSet) in2;
FlowSet outSet = (FlowSet) out;
inSet1.union(inSet2, outSet);
}
protected boolean isNonRefType(Type type)
{
return !(type instanceof RefLikeType);
}
protected boolean ignoreThisDataType(Type type)
{
return refOnly && isNonRefType(type);
}
// Interesting sources are summarized (and possibly printed)
public boolean isInterestingSource(Value source)
{
return (source instanceof Ref);
}
// Trackable sources are added to the flow set
public boolean isTrackableSource(Value source)
{
return isInterestingSource(source) || (source instanceof Ref);
}
// Interesting sinks are possibly printed
public boolean isInterestingSink(Value sink)
{
return (sink instanceof Ref);
}
// Trackable sinks are added to the flow set
public boolean isTrackableSink(Value sink)
{
return isInterestingSink(sink) || (sink instanceof Ref) || (sink instanceof Local);
}
private ArrayList<Value> getDirectSources(Value v, FlowSet fs)
{
ArrayList<Value> ret = new ArrayList<Value>(); // of "interesting sources"
EquivalentValue vEqVal = new CachedEquivalentValue(v);
Iterator fsIt = fs.iterator();
while(fsIt.hasNext())
{
Pair pair = (Pair) fsIt.next();
if( pair.getO1().equals(vEqVal) )
ret.add( ((EquivalentValue)pair.getO2()).getValue() );
}
return ret;
}
// For when data flows to a local
protected void handleFlowsToValue(Value sink, Value initialSource, FlowSet fs)
{
if(!isTrackableSink(sink))
return;
List<Value> sources = getDirectSources(initialSource, fs); // list of Refs... returns all other sources
if(isTrackableSource(initialSource))
sources.add(initialSource);
Iterator<Value> sourcesIt = sources.iterator();
while(sourcesIt.hasNext())
{
Value source = sourcesIt.next();
EquivalentValue sinkEqVal = new CachedEquivalentValue(sink);
EquivalentValue sourceEqVal = new CachedEquivalentValue(source);
if(sinkEqVal.equals(sourceEqVal))
continue;
Pair pair = new Pair(sinkEqVal, sourceEqVal);
if(!fs.contains(pair))
{
fs.add(pair);
if(isInterestingSource(source) && isInterestingSink(sink))
{
if(!infoFlowGraph.containsNode(sinkEqVal))
infoFlowGraph.addNode(sinkEqVal);
if(!infoFlowGraph.containsNode(sourceEqVal))
infoFlowGraph.addNode(sourceEqVal);
infoFlowGraph.addEdge(sourceEqVal, sinkEqVal);
if(printMessages)
G.v().out.println(" Found " + source + " flows to " + sink);
}
}
}
}
// for when data flows to the data structure pointed to by a local
protected void handleFlowsToDataStructure(Value base, Value initialSource, FlowSet fs)
{
List<Value> sinks = getDirectSources(base, fs);
if(isTrackableSink(base))
sinks.add(base);
List<Value> sources = getDirectSources(initialSource, fs);
if(isTrackableSource(initialSource))
sources.add(initialSource);
Iterator<Value> sourcesIt = sources.iterator();
while(sourcesIt.hasNext())
{
Value source = sourcesIt.next();
EquivalentValue sourceEqVal = new CachedEquivalentValue(source);
Iterator<Value> sinksIt = sinks.iterator();
while(sinksIt.hasNext())
{
Value sink = sinksIt.next();
if(!isTrackableSink(sink))
continue;
EquivalentValue sinkEqVal = new CachedEquivalentValue(sink);
if(sinkEqVal.equals(sourceEqVal))
continue;
Pair pair = new Pair(sinkEqVal, sourceEqVal);
if(!fs.contains(pair))
{
fs.add(pair);
if(isInterestingSource(source) && isInterestingSink(sink))
{
if(!infoFlowGraph.containsNode(sinkEqVal))
infoFlowGraph.addNode(sinkEqVal);
if(!infoFlowGraph.containsNode(sourceEqVal))
infoFlowGraph.addNode(sourceEqVal);
infoFlowGraph.addEdge(sourceEqVal, sinkEqVal);
if(printMessages)
G.v().out.println(" Found " + source + " flows to " + sink);
}
}
}
}
}
// handles the invoke expression AND returns a list of the return value's sources
// for each node
// if the node is a parameter
// source = argument <Immediate>
// if the node is a static field
// source = node <StaticFieldRef>
// if the node is a field
// source = receiver object <Local>
// if the node is the return value
// continue
// for each sink
// if the sink is a parameter
// handleFlowsToDataStructure(sink, source, fs)
// if the sink is a static field
// handleFlowsToValue(sink, source, fs)
// if the sink is a field
// handleFlowsToDataStructure(receiver object, source, fs)
// if the sink is the return value
// add node to list of return value sources
protected List handleInvokeExpr(InvokeExpr ie, FlowSet fs)
{
// get the data flow graph
MutableDirectedGraph dataFlowGraph = dfa.getInvokeInfoFlowSummary(ie, sm); // must return a graph whose nodes are Refs!!!
// if( ie.getMethodRef().resolve().getSubSignature().equals(new String("boolean remove(java.lang.Object)")) )
// {
// G.v().out.println("*!*!*!*!*!<boolean remove(java.lang.Object)> has FLOW SENSITIVE infoFlowGraph: ");
// ClassInfoFlowAnalysis.printDataFlowGraph(infoFlowGraph);
// }
List returnValueSources = new ArrayList();
Iterator<Object> nodeIt = dataFlowGraph.getNodes().iterator();
while(nodeIt.hasNext())
{
EquivalentValue nodeEqVal = (EquivalentValue) nodeIt.next();
if(!(nodeEqVal.getValue() instanceof Ref))
throw new RuntimeException("Illegal node type in data flow graph:" + nodeEqVal.getValue() + " should be an object of type Ref.");
Ref node = (Ref) nodeEqVal.getValue();
Value source = null;
if(node instanceof ParameterRef)
{
ParameterRef param = (ParameterRef) node;
if(param.getIndex() == -1)
continue;
source = ie.getArg(param.getIndex()); // Immediate
}
else if(node instanceof StaticFieldRef)
{
source = node; // StaticFieldRef
}
else if(ie instanceof InstanceInvokeExpr && node instanceof InstanceFieldRef)
{
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
source = iie.getBase(); // Local
}
Iterator sinksIt = dataFlowGraph.getSuccsOf(nodeEqVal).iterator();
while(sinksIt.hasNext())
{
EquivalentValue sinkEqVal = (EquivalentValue) sinksIt.next();
Ref sink = (Ref) sinkEqVal.getValue();
if(sink instanceof ParameterRef)
{
ParameterRef param = (ParameterRef) sink;
if(param.getIndex() == -1)
{
returnValueSources.add(source);
}
else
{
handleFlowsToDataStructure(ie.getArg(param.getIndex()), source, fs);
}
}
else if(sink instanceof StaticFieldRef)
{
handleFlowsToValue(sink, source, fs);
}
else if(ie instanceof InstanceInvokeExpr && sink instanceof InstanceFieldRef)
{
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
handleFlowsToDataStructure(iie.getBase(), source, fs);
}
}
}
// return the list of return value sources
return returnValueSources;
}
protected void flowThrough(Object inValue, Object unit,
Object outValue)
{
FlowSet in = (FlowSet) inValue;
FlowSet out = (FlowSet) outValue;
Stmt stmt = (Stmt) unit;
if(in != out) // this method is reused for flow insensitive analysis, which uses the same FlowSet for in and out
in.copy(out);
FlowSet changedFlow = out;
// Calculate the minimum subset of the flow set that we need to consider - OBSELETE optimization
// FlowSet changedFlow = new ArraySparseSet();
// FlowSet oldFlow = new ArraySparseSet();
// out.copy(oldFlow);
// in.union(out, out);
// out.difference(oldFlow, changedFlow);
/*
Iterator changedFlowIt = changedFlow.iterator();
while(changedFlowIt.hasNext())
{
Pair pair = (Pair) changedFlowIt.next();
EquivalentValue defEqVal = (EquivalentValue) pair.getO1();
Value def = defEqVal.getValue();
boolean defIsUsed = false;
Iterator usesIt = stmt.getUseBoxes().iterator();
while(usesIt.hasNext())
{
Value use = ((ValueBox) usesIt.next()).getValue();
if(use.equivTo(def))
defIsUsed = true;
}
if(!defIsUsed)
changedFlow.remove(pair);
}
*/
// Bail out if there's nothing to consider, unless this might be the first run
// if(changedFlow.isEmpty() && !oldFlow.equals(emptySet))
// return;
if(stmt instanceof IdentityStmt) // assigns an IdentityRef to a Local
{
IdentityStmt is = (IdentityStmt) stmt;
IdentityRef ir = (IdentityRef) is.getRightOp();
if(ir instanceof JCaughtExceptionRef)
{
// TODO: What the heck do we do with this???
}
else if(ir instanceof ParameterRef)
{
if( !ignoreThisDataType(ir.getType()) )
{
// <Local, ParameterRef and sources>
handleFlowsToValue(is.getLeftOp(), ir, changedFlow);
}
}
else if(ir instanceof ThisRef)
{
if( !ignoreThisDataType(ir.getType()) )
{
// <Local, ThisRef and sources>
handleFlowsToValue(is.getLeftOp(), ir, changedFlow);
}
}
}
else if(stmt instanceof ReturnStmt) // assigns an Immediate to the "returnRef"
{
ReturnStmt rs = (ReturnStmt) stmt;
Value rv = rs.getOp();
if(rv instanceof Constant)
{
// No (interesting) data flow
}
else if(rv instanceof Local)
{
if( !ignoreThisDataType(rv.getType()) )
{
// <ReturnRef, sources of Local>
handleFlowsToValue(returnRef, rv, changedFlow);
}
}
}
else if(stmt instanceof AssignStmt) // assigns a Value to a Variable
{
AssignStmt as = (AssignStmt) stmt;
Value lv = as.getLeftOp();
Value rv = as.getRightOp();
Value sink = null;
boolean flowsToDataStructure = false;
if(lv instanceof Local) // data flows into the Local
{
sink = lv;
}
else if(lv instanceof ArrayRef) // data flows into the base's data structure
{
ArrayRef ar = (ArrayRef) lv;
sink = ar.getBase();
flowsToDataStructure = true;
}
else if(lv instanceof StaticFieldRef) // data flows into the field ref
{
sink = lv;
}
else if(lv instanceof InstanceFieldRef)
{
InstanceFieldRef ifr = (InstanceFieldRef) lv;
if( ifr.getBase() == thisLocal ) // data flows into the field ref
{
sink = lv;
}
else // data flows into the base's data structure
{
sink = ifr.getBase();
flowsToDataStructure = true;
}
}
List sources = new ArrayList();
boolean interestingFlow = true;
if(rv instanceof Local)
{
sources.add(rv);
interestingFlow = !ignoreThisDataType(rv.getType());
}
else if(rv instanceof Constant)
{
sources.add(rv);
interestingFlow = !ignoreThisDataType(rv.getType());
}
else if(rv instanceof ArrayRef) // data flows from the base's data structure
{
ArrayRef ar = (ArrayRef) rv;
sources.add(ar.getBase());
interestingFlow = !ignoreThisDataType(ar.getType());
}
else if(rv instanceof StaticFieldRef)
{
sources.add(rv);
interestingFlow = !ignoreThisDataType(rv.getType());
}
else if(rv instanceof InstanceFieldRef)
{
InstanceFieldRef ifr = (InstanceFieldRef) rv;
if( ifr.getBase() == thisLocal ) // data flows from the field ref
{
sources.add(rv);
interestingFlow = !ignoreThisDataType(rv.getType());
}
else // data flows from the base's data structure
{
sources.add(ifr.getBase());
interestingFlow = !ignoreThisDataType(ifr.getType());
}
}
else if(rv instanceof AnyNewExpr)
{
sources.add(rv);
interestingFlow = !ignoreThisDataType(rv.getType());
}
else if(rv instanceof BinopExpr)
{
BinopExpr be = (BinopExpr) rv;
sources.add(be.getOp1());
sources.add(be.getOp2());
interestingFlow = !ignoreThisDataType(be.getType());
}
else if(rv instanceof CastExpr)
{
CastExpr ce = (CastExpr) rv;
sources.add(ce.getOp());
interestingFlow = !ignoreThisDataType(ce.getType());
}
else if(rv instanceof InstanceOfExpr)
{
InstanceOfExpr ioe = (InstanceOfExpr) rv;
sources.add(ioe.getOp());
interestingFlow = !ignoreThisDataType(ioe.getType());
}
else if(rv instanceof UnopExpr)
{
UnopExpr ue = (UnopExpr) rv;
sources.add(ue.getOp());
interestingFlow = !ignoreThisDataType(ue.getType());
}
else if(rv instanceof InvokeExpr)
{
InvokeExpr ie = (InvokeExpr) rv;
sources.addAll(handleInvokeExpr(ie, changedFlow));
interestingFlow = !ignoreThisDataType(ie.getType());
}
if(interestingFlow)
{
if(flowsToDataStructure)
{
Iterator sourcesIt = sources.iterator();
while(sourcesIt.hasNext())
{
Value source = (Value) sourcesIt.next();
handleFlowsToDataStructure(sink, source, changedFlow);
}
}
else
{
Iterator sourcesIt = sources.iterator();
while(sourcesIt.hasNext())
{
Value source = (Value) sourcesIt.next();
handleFlowsToValue(sink, source, changedFlow);
}
}
}
}
else if(stmt.containsInvokeExpr()) // flows data between receiver object, parameters, globals, and return value
{
handleInvokeExpr(stmt.getInvokeExpr(), changedFlow);
}
// changedFlow.union(out, out); - OBSELETE optimization
}
protected void copy(Object source, Object dest)
{
FlowSet sourceSet = (FlowSet) source;
FlowSet destSet = (FlowSet) dest;
sourceSet.copy(destSet);
}
protected Object entryInitialFlow()
{
return entrySet.clone();
}
protected Object newInitialFlow()
{
return emptySet.clone();
}
public void addToEntryInitialFlow(Value source, Value sink)
{
EquivalentValue sinkEqVal = new CachedEquivalentValue(sink);
EquivalentValue sourceEqVal = new CachedEquivalentValue(source);
if(sinkEqVal.equals(sourceEqVal))
return;
Pair pair = new Pair(sinkEqVal, sourceEqVal);
if(!entrySet.contains(pair))
{
entrySet.add(pair);
}
}
public void addToNewInitialFlow(Value source, Value sink)
{
EquivalentValue sinkEqVal = new CachedEquivalentValue(sink);
EquivalentValue sourceEqVal = new CachedEquivalentValue(source);
if(sinkEqVal.equals(sourceEqVal))
return;
Pair pair = new Pair(sinkEqVal, sourceEqVal);
if(!emptySet.contains(pair))
{
emptySet.add(pair);
}
}
public Value getThisLocal()
{
return thisLocal;
}
}
| gpl-2.0 |
ccaleman/MDConverter | MDConverterAPI/src/main/java/org/mdconverter/api/topologystructure/model/api/ValueHolder.java | 3088 | package org.mdconverter.api.topologystructure.model.api;
import org.mdconverter.api.topologystructure.ModelVersion;
import java.math.BigDecimal;
/**
* Created by miso on 07.01.2016. <br>
* {@link ValueHolder} holds the convertible values of the Implementation
* An implementation of {@link ValueHolder} may holds at least one convertible value and max. up to six convertible values
*/
public abstract class ValueHolder {
/**
* @param c1 a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public void setC1(BigDecimal c1) {
throw new UnsupportedOperationException();
}
/**
* @param c2 a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public void setC2(BigDecimal c2) {
throw new UnsupportedOperationException();
}
/**
* @param c3 a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public void setC3(BigDecimal c3) {
throw new UnsupportedOperationException();
}
/**
* @param c4 a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public void setC4(BigDecimal c4) {
throw new UnsupportedOperationException();
}
/**
* @param c5 a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public void setC5(BigDecimal c5) {
throw new UnsupportedOperationException();
}
/**
* @param c6 a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public void setC6(BigDecimal c6) {
throw new UnsupportedOperationException();
}
/**
* @return a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public BigDecimal getC1() {
throw new UnsupportedOperationException();
}
/**
* @return a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public BigDecimal getC2() {
throw new UnsupportedOperationException();
}
/**
* @return a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public BigDecimal getC3() {
throw new UnsupportedOperationException();
}
/**
* @return a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public BigDecimal getC4() {
throw new UnsupportedOperationException();
}
/**
* @return a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public BigDecimal getC5() {
throw new UnsupportedOperationException();
}
/**
* @return a BigDecimal
* @throws UnsupportedOperationException
* @since {@link ModelVersion#V1}
*/
public BigDecimal getC6() {
throw new UnsupportedOperationException();
}
}
| gpl-2.0 |
liyue80/GmailAssistant20 | src/org/freeshell/zs/gmailassistant/ProfileLoader.java | 25425 | /**
* GmailAssistant 2.0 (2008-09-07)
* Copyright 2008 Zach Scrivena
* zachscrivena@gmail.com
* http://gmailassistant.sourceforge.net/
*
* Notifier for multiple Gmail and Google Apps email accounts.
*
* TERMS AND CONDITIONS:
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.freeshell.zs.gmailassistant;
import org.freeshell.zs.common.Encryptor;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.freeshell.zs.common.Debug;
import org.freeshell.zs.common.FileIO;
import org.freeshell.zs.common.SimpleProperties;
import org.freeshell.zs.common.StringManipulator;
import org.freeshell.zs.common.SwingManipulator;
import org.freeshell.zs.common.TerminatingException;
/**
* "Load Profile" form.
*/
class ProfileLoader
extends JFrame
{
/** refresh interval in milliseconds */
private static final long REFRESH_INTERVAL_MILLISECONDS = 200L;
/** empty password for decrypting */
private static final char[] EMPTY_PASSWORD = new char[0];
/** parent GmailAssistant object */
private final GmailAssistant parent;
/** selected profile files to be loaded */
private final Deque<File> files = new ArrayDeque<File>();
/** user has responded to the prompt by clicking a button */
private volatile boolean promptResponded;
/** profile password to be used for decrypting */
private volatile char[] promptPassword;
/** file chooser for selecting profile files */
private JFileChooser fileChooser = null;
/**
* Constructor.
*
* @param parent
* parent GmailAssistant object
*/
ProfileLoader(
final GmailAssistant parent)
{
/*********************
* INITIALIZE FIELDS *
*********************/
this.parent = parent;
/******************************
* INITIALIZE FORM COMPONENTS *
******************************/
initComponents();
/***************************
* CONFIGURE FORM SETTINGS *
***************************/
setTitle(String.format("Load Profiles - %s", parent.name));
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
cancelButton.doClick();
}
});
/* inherit "always on top" behavior of parent */
try
{
setAlwaysOnTop(parent.isAlwaysOnTop());
}
catch (Exception e)
{
/* ignore */
}
/* inherit program icon of parent */
final List<Image> icons = parent.getIconImages();
if (!icons.isEmpty())
{
setIconImage(icons.get(0));
}
/* field: "Profile Password" */
passwordField.setText("");
/* image: "lock" */
lockImage.setToolTipText(String.format("%s encrypts your profile using AES-128 encryption", parent.name));
/* button: "OK" */
okButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
okButton.setEnabled(false);
cancelButton.setEnabled(false);
promptPassword = SwingManipulator.getPasswordJPasswordField(passwordField);
promptResponded = true;
}
});
/* button: "Cancel" */
cancelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
cancelButton.setEnabled(false);
okButton.setEnabled(false);
promptPassword = null;
promptResponded = true;
}
});
/* add standard editing popup menu to text fields */
SwingManipulator.addStandardEditingPopupMenu(new JTextField[]
{
passwordField,
});
/* key binding: ENTER key */
scrollPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ENTER_OK_BUTTON");
scrollPane.getActionMap().put("ENTER_OK_BUTTON", new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
okButton.doClick();
}
});
/* key binding: ESCAPE key */
scrollPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "ESCAPE_CANCEL_BUTTON");
scrollPane.getActionMap().put("ESCAPE_CANCEL_BUTTON", new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
cancelButton.doClick();
}
});
/* center form on the parent form */
setLocationRelativeTo(parent);
/**********************************
* INITIATE PROFILE LOADER THREAD *
**********************************/
new Thread(new Runnable()
{
public void run()
{
NextProfile:
while (true)
{
final File f;
synchronized (files)
{
f = files.pollFirst();
}
if (f == null)
{
Debug.sleep(REFRESH_INTERVAL_MILLISECONDS);
continue NextProfile;
}
final int firstByteMarker;
byte[] salt = null;
byte[] ciphertextBytes = null;
final int lastByteMarker;
char[] password = null;
byte[] cleartextBytes = null;
try
{
/****************
* DISPLAY FORM *
****************/
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
loadFilename.setText(f.getPath());
loadError.setText(" ");
passwordField.setEnabled(false);
okButton.setEnabled(false);
cancelButton.setEnabled(false);
setVisible(true);
setExtendedState(JFrame.NORMAL);
toFront();
}
});
/**********************
* READ FILE CONTENTS *
**********************/
SwingManipulator.updateLabel(loadError, "<html><font color='blue'>Reading file contents...</font></html>");
try
{
final FileInputStream fis = new FileInputStream(f);
final int length = (int) f.length();
/* read first byte marker */
firstByteMarker = fis.read();
if (firstByteMarker == -1)
{
throw new IOException("Encountered premature EOF.");
}
/* read salt */
final int saltLength = parent.properties.getInt("encryption.salt.length");
salt = new byte[saltLength];
FileIO.blockingRead(fis, salt, 0, saltLength);
/* read ciphertext */
final int ciphertextLength = length - 2 - saltLength;
ciphertextBytes = new byte[ciphertextLength];
FileIO.blockingRead(fis, ciphertextBytes, 0, ciphertextLength);
/* read first byte marker */
lastByteMarker = fis.read();
if (lastByteMarker == -1)
{
throw new IOException("Encountered premature EOF.");
}
try
{
fis.close();
}
catch (Exception e)
{
/* ignore */
}
}
catch (Exception e)
{
throw new TerminatingException(String.format(
"Failed to read file contents of profile \"%s\" (%s).\nPlease check that the file exists and can be read.",
f.getPath(), e.toString()));
}
/******************
* CHECK VALIDITY *
******************/
SwingManipulator.updateLabel(loadError, "<html><font color='blue'>Checking validity...</font></html>");
final int withPasswordByteMarker = parent.properties.getInt("profile.with.password.byte.marker");
final int withoutPasswordByteMarker = parent.properties.getInt("profile.without.password.byte.marker");
if ((firstByteMarker != lastByteMarker) ||
((firstByteMarker != withPasswordByteMarker) &&
(firstByteMarker != withoutPasswordByteMarker)))
{
throw new TerminatingException(String.format("Malformed profile \"%s\".", f.getPath()));
}
/******************************************
* PROMPT USER FOR PASSWORD, IF NECESSARY *
******************************************/
if (firstByteMarker == withPasswordByteMarker)
{
promptResponded = false;
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
passwordField.setEnabled(true);
okButton.setEnabled(true);
cancelButton.setEnabled(true);
setVisible(true);
setExtendedState(JFrame.NORMAL);
toFront();
passwordField.selectAll();
passwordField.requestFocus();
}
});
/* wait for user to respond */
SwingManipulator.updateLabel(loadError, "<html><font color='blue'>Waiting for profile password...</font></html>");
while (!promptResponded)
{
Debug.sleep(REFRESH_INTERVAL_MILLISECONDS);
}
password = promptPassword;
if (password == null)
{
continue NextProfile;
}
}
else
{
password = EMPTY_PASSWORD;
}
/*******************
* DECRYPT PROFILE *
*******************/
SwingManipulator.updateLabel(loadError, "<html><font color='blue'>Decrypting profile...</font></html>");
final int iterations = parent.properties.getInt("encryption.salt.iterations");
try
{
cleartextBytes = Encryptor.decrypt(salt, iterations, String.valueOf(password), ciphertextBytes);
}
catch (Exception e)
{
synchronized (files)
{
files.addFirst(f);
}
throw new TerminatingException(String.format(
"Failed to decrypt profile \"%s\".\nPlease check that the provided password is correct.",
f.getPath()));
}
final String charset = parent.properties.getString("profile.charset");
String[] cleartext = new String(cleartextBytes, charset).split("[\n\r\u0085\u2028\u2028]++");
/***************************************
* LOAD PROGRAM AND ACCOUNT PROPERTIES *
***************************************/
SwingManipulator.updateLabel(loadError, "<html><font color='blue'>Parsing profile...</font></html>");
/* convert profile from an older program version, if necessary */
final String version = parent.properties.getString("version");
String profileVersion = version; /* assume current version first */
for (String s : cleartext)
{
if (s.startsWith("<") && s.endsWith(">"))
{
profileVersion = s.substring(1, s.length() - 1);
}
}
if (!profileVersion.equals(version))
{
updateProfile(cleartext, profileVersion);
}
/* parse each line in the profile file */
final List<SimpleProperties> accounts = new ArrayList<SimpleProperties>();
SimpleProperties current = null;
final List<String> errors = new ArrayList<String>();
for (String s : cleartext)
{
if (s.isEmpty() || s.startsWith("#"))
{
/* ignore empty lines and comments */
}
else if (s.startsWith("<") && s.endsWith(">"))
{
/* ignore program version */
}
else if (s.startsWith("[") && s.endsWith("]"))
{
/* start recording properties for a new account */
final String username = s.substring(1, s.length() - 1);
current = new SimpleProperties(parent.defaultAccountProperties);
current.setString("username", username);
accounts.add(current);
}
else if (s.contains(":"))
{
/* process "key:value" pair */
final String[] kv = StringManipulator.parseKeyValueString(s);
if (current == null)
{
/* program property */
if (parent.savedProgramProperties.get(kv[0]) == null)
{
if (parent.properties.get(kv[0]) == null)
{
errors.add(String.format("\"%s\" is not a valid program property.", kv[0]));
}
else
{
errors.add(String.format("\"%s\" is not a valid saved program property.", kv[0]));
}
}
else
{
parent.properties.set(kv[0], kv[1]);
}
}
else
{
/* account property */
if ("password".equals(kv[0]))
{
current.set(kv[0], kv[1]);
}
else
{
if (parent.savedAccountProperties.get(kv[0]) == null)
{
if (current.get(kv[0]) == null)
{
errors.add(String.format("\"%s\" is not a valid account property.", kv[0]));
}
else
{
errors.add(String.format("\"%s\" is not a valid saved account property.", kv[0]));
}
}
else
{
current.set(kv[0], kv[1]);
}
}
}
}
}
SwingManipulator.updateLabel(loadError, "<html><font color='blue'>Profile loaded</font></html>");
/* report any errors */
if (!errors.isEmpty())
{
SwingManipulator.updateLabel(loadError, "<html><font color='blue'>Profile loaded (errors encountered)</font></html>");
final StringBuilder sb = new StringBuilder();
for (String s : errors)
{
sb.append("\n\n");
sb.append(s);
}
SwingManipulator.showWarningDialog(
ProfileLoader.this,
String.format("Load Profiles - %s", parent.name),
String.format("The following %s were encountered when loading profile \"%s\" :%s",
(errors.size() == 1) ? "error" : "errors", f.getPath(), sb.toString()));
}
/* add new accounts loaded from the file */
for (SimpleProperties p : accounts)
{
parent.addNewAccount(p);
}
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
/* repopulate "Options" form */
if (parent.options != null)
{
parent.options.repopulateForm();
}
/* refresh program modes */
parent.refreshAlwaysOnTopMode();
parent.refreshProxyMode();
}
});
}
catch (TerminatingException e)
{
SwingManipulator.showErrorDialog(
ProfileLoader.this,
String.format("Load Profiles - %s", parent.name),
String.format("%s\nNote that profiles created by %s 1.1 or earlier are not compatible with this version of the program.",
e.getMessage(), parent.name));
}
catch (Exception e)
{
SwingManipulator.showErrorDialog(
ProfileLoader.this,
String.format("Load Profiles - %s", parent.name),
String.format("Failed to load profile \"%s\" because of an unexpected error:\n%s" +
"\nNote that profiles created by %s 1.1 or earlier are not compatible with this version of the program." +
"\nPlease file a bug report to help improve %s.\n\n%s\n\n%s",
f.getPath(), e.toString(), parent.name, parent.name, Debug.getSystemInformationString(), Debug.getStackTraceString(e)));
}
finally
{
if (password != null)
{
Arrays.fill(password, '\0');
}
for (byte[] b : new byte[][] {salt, ciphertextBytes, cleartextBytes})
{
if (b != null)
{
Arrays.fill(b, (byte) 0x00);
}
}
SwingManipulator.setVisibleWindow(ProfileLoader.this, false);
}
}
}
}).start();
}
/**
* Present a file chooser for the user to select the profile files for loading.
* This method must run on the EDT.
*/
void showForm()
{
if (fileChooser == null)
{
try
{
fileChooser = new JFileChooser(new File(".").getCanonicalFile());
}
catch (Exception e)
{
fileChooser = new JFileChooser();
}
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(true);
final String ext = parent.properties.getString("profile.default.extension");
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter(
String.format("%s Profile (*.%s)", parent.name, ext),
ext));
}
final int val = fileChooser.showOpenDialog(parent);
if (val == JFileChooser.APPROVE_OPTION)
{
synchronized (files)
{
for (File f : fileChooser.getSelectedFiles())
{
files.offerLast(f);
}
}
}
}
/**
* Load the specified profile files.
* This method must run on the EDT.
*
* @param files
* profile files to be loaded
*/
void loadProfiles(
final List<File> fs)
{
synchronized (files)
{
for (File f : fs)
{
files.offerLast(f);
}
}
}
/**
* Update the specified profile data to the current program version.
*
* @param profile
* profile data to be updated
* @param version
* program version associated with the given profile data
*/
private void updateProfile(
final String[] profile,
final String version)
{
/* nothing to do */
}
/***************************
* NETBEANS-GENERATED CODE *
***************************/
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonsPanel = new javax.swing.JPanel();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
loadTitle = new javax.swing.JLabel();
loadFilename = new javax.swing.JLabel();
scrollPane = new javax.swing.JScrollPane();
panel = new javax.swing.JPanel();
loadPanel = new javax.swing.JPanel();
passwordLabel = new javax.swing.JLabel();
passwordField = new javax.swing.JPasswordField();
lockImage = new javax.swing.JLabel();
loadError = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
buttonsPanel.setLayout(new java.awt.GridLayout(1, 2));
okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/freeshell/zs/gmailassistant/resources/tick.png"))); // NOI18N
okButton.setMnemonic('O');
okButton.setText("OK");
okButton.setToolTipText("Load profile from the specified file");
buttonsPanel.add(okButton);
cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/freeshell/zs/gmailassistant/resources/cross.png"))); // NOI18N
cancelButton.setMnemonic('C');
cancelButton.setText("Cancel");
cancelButton.setToolTipText("Cancel loading of profile");
buttonsPanel.add(cancelButton);
loadTitle.setText("Loading profile");
loadTitle.setVerticalAlignment(javax.swing.SwingConstants.TOP);
loadFilename.setFont(new java.awt.Font("Tahoma", 1, 11));
loadFilename.setText("C:\\Path\\To\\File");
loadFilename.setVerticalAlignment(javax.swing.SwingConstants.TOP);
scrollPane.setBorder(null);
panel.setLayout(new javax.swing.BoxLayout(panel, javax.swing.BoxLayout.Y_AXIS));
loadPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
passwordLabel.setDisplayedMnemonic('p');
passwordLabel.setLabelFor(passwordField);
passwordLabel.setText("Profile password:");
passwordLabel.setToolTipText("Password to be used for decrypting the profile");
passwordField.setToolTipText("Password to be used for decrypting the profile");
lockImage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lockImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/freeshell/zs/gmailassistant/resources/lock.png"))); // NOI18N
loadError.setText("<html><font color='red'>load error</font></html>");
loadError.setVerticalAlignment(javax.swing.SwingConstants.TOP);
javax.swing.GroupLayout loadPanelLayout = new javax.swing.GroupLayout(loadPanel);
loadPanel.setLayout(loadPanelLayout);
loadPanelLayout.setHorizontalGroup(
loadPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loadPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(loadPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(loadError, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
.addGroup(loadPanelLayout.createSequentialGroup()
.addComponent(passwordLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lockImage)))
.addContainerGap())
);
loadPanelLayout.setVerticalGroup(
loadPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(loadPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(loadPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(loadPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordLabel)
.addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lockImage))
.addGap(18, 18, 18)
.addComponent(loadError)
.addContainerGap(13, Short.MAX_VALUE))
);
panel.add(loadPanel);
scrollPane.setViewportView(panel);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(scrollPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
.addComponent(buttonsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
.addComponent(loadTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
.addComponent(loadFilename, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(loadTitle)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(loadFilename)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(buttonsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonsPanel;
private javax.swing.JButton cancelButton;
private javax.swing.JLabel loadError;
private javax.swing.JLabel loadFilename;
private javax.swing.JPanel loadPanel;
private javax.swing.JLabel loadTitle;
private javax.swing.JLabel lockImage;
private javax.swing.JButton okButton;
private javax.swing.JPanel panel;
private javax.swing.JPasswordField passwordField;
private javax.swing.JLabel passwordLabel;
private javax.swing.JScrollPane scrollPane;
// End of variables declaration//GEN-END:variables
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/javax/imageio/spi/PartiallyOrderedSet.java | 6980 | /*
* Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.imageio.spi;
import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
/**
* A set of <code>Object</code>s with pairwise orderings between them.
* The <code>iterator</code> method provides the elements in
* topologically sorted order. Elements participating in a cycle
* are not returned.
*
* Unlike the <code>SortedSet</code> and <code>SortedMap</code>
* interfaces, which require their elements to implement the
* <code>Comparable</code> interface, this class receives ordering
* information via its <code>setOrdering</code> and
* <code>unsetPreference</code> methods. This difference is due to
* the fact that the relevant ordering between elements is unlikely to
* be inherent in the elements themselves; rather, it is set
* dynamically accoring to application policy. For example, in a
* service provider registry situation, an application might allow the
* user to set a preference order for service provider objects
* supplied by a trusted vendor over those supplied by another.
*
*/
class PartiallyOrderedSet extends AbstractSet {
// The topological sort (roughly) follows the algorithm described in
// Horowitz and Sahni, _Fundamentals of Data Structures_ (1976),
// p. 315.
// Maps Objects to DigraphNodes that contain them
private Map poNodes = new HashMap();
// The set of Objects
private Set nodes = poNodes.keySet();
/**
* Constructs a <code>PartiallyOrderedSet</code>.
*/
public PartiallyOrderedSet() {}
public int size() {
return nodes.size();
}
public boolean contains(Object o) {
return nodes.contains(o);
}
/**
* Returns an iterator over the elements contained in this
* collection, with an ordering that respects the orderings set
* by the <code>setOrdering</code> method.
*/
public Iterator iterator() {
return new PartialOrderIterator(poNodes.values().iterator());
}
/**
* Adds an <code>Object</code> to this
* <code>PartiallyOrderedSet</code>.
*/
public boolean add(Object o) {
if (nodes.contains(o)) {
return false;
}
DigraphNode node = new DigraphNode(o);
poNodes.put(o, node);
return true;
}
/**
* Removes an <code>Object</code> from this
* <code>PartiallyOrderedSet</code>.
*/
public boolean remove(Object o) {
DigraphNode node = (DigraphNode)poNodes.get(o);
if (node == null) {
return false;
}
poNodes.remove(o);
node.dispose();
return true;
}
public void clear() {
poNodes.clear();
}
/**
* Sets an ordering between two nodes. When an iterator is
* requested, the first node will appear earlier in the
* sequence than the second node. If a prior ordering existed
* between the nodes in the opposite order, it is removed.
*
* @return <code>true</code> if no prior ordering existed
* between the nodes, <code>false</code>otherwise.
*/
public boolean setOrdering(Object first, Object second) {
DigraphNode firstPONode =
(DigraphNode)poNodes.get(first);
DigraphNode secondPONode =
(DigraphNode)poNodes.get(second);
secondPONode.removeEdge(firstPONode);
return firstPONode.addEdge(secondPONode);
}
/**
* Removes any ordering between two nodes.
*
* @return true if a prior prefence existed between the nodes.
*/
public boolean unsetOrdering(Object first, Object second) {
DigraphNode firstPONode =
(DigraphNode)poNodes.get(first);
DigraphNode secondPONode =
(DigraphNode)poNodes.get(second);
return firstPONode.removeEdge(secondPONode) ||
secondPONode.removeEdge(firstPONode);
}
/**
* Returns <code>true</code> if an ordering exists between two
* nodes.
*/
public boolean hasOrdering(Object preferred, Object other) {
DigraphNode preferredPONode =
(DigraphNode)poNodes.get(preferred);
DigraphNode otherPONode =
(DigraphNode)poNodes.get(other);
return preferredPONode.hasEdge(otherPONode);
}
}
class PartialOrderIterator implements Iterator {
LinkedList zeroList = new LinkedList();
Map inDegrees = new HashMap(); // DigraphNode -> Integer
public PartialOrderIterator(Iterator iter) {
// Initialize scratch in-degree values, zero list
while (iter.hasNext()) {
DigraphNode node = (DigraphNode)iter.next();
int inDegree = node.getInDegree();
inDegrees.put(node, new Integer(inDegree));
// Add nodes with zero in-degree to the zero list
if (inDegree == 0) {
zeroList.add(node);
}
}
}
public boolean hasNext() {
return !zeroList.isEmpty();
}
public Object next() {
DigraphNode first = (DigraphNode)zeroList.removeFirst();
// For each out node of the output node, decrement its in-degree
Iterator outNodes = first.getOutNodes();
while (outNodes.hasNext()) {
DigraphNode node = (DigraphNode)outNodes.next();
int inDegree = ((Integer)inDegrees.get(node)).intValue() - 1;
inDegrees.put(node, new Integer(inDegree));
// If the in-degree has fallen to 0, place the node on the list
if (inDegree == 0) {
zeroList.add(node);
}
}
return first.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
| gpl-2.0 |
abednego4609/eventmanager | src/test/java/com/halusinogen/eventmanager/manager/impl/kejadian/Ledakan.java | 203 | package com.halusinogen.eventmanager.manager.impl.kejadian;
import com.halusinogen.eventmanager.event.intf.Event;
/**
* Created by marchell on 2/13/2015.
*/
public class Ledakan implements Event {
}
| gpl-2.0 |
CumpsD/calimero | src/tuwien/auto/calimero/knxnetip/servicetype/ServiceRequest.java | 6886 | /*
Calimero 2 - A library for KNX network access
Copyright (c) 2006, 2011 B. Malinowsky
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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 tuwien.auto.calimero.knxnetip.servicetype;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import tuwien.auto.calimero.cemi.CEMI;
import tuwien.auto.calimero.cemi.CEMIDevMgmt;
import tuwien.auto.calimero.cemi.CEMIFactory;
import tuwien.auto.calimero.exception.KNXFormatException;
import tuwien.auto.calimero.exception.KNXIllegalArgumentException;
/**
* Common service request structure, used to send requests over established KNXnet/IP
* communication channels.
* <p>
* Such a service request is used for tunnel or device management connections. It carries
* a cEMI frame containing the actual KNX frame data.<br>
* A service request is contained in the body of a KNXnet/IP frame.
*
* @see tuwien.auto.calimero.knxnetip.servicetype.ServiceAck
*/
public class ServiceRequest extends ServiceType
{
private static final int CONN_HEADER_SIZE = 4;
private final int channelid;
private final int seq;
private CEMI cemi;
/**
* Creates a new service request out of a byte array.
* <p>
*
* @param serviceType service request type identifier describing the request in
* <code>data</code>, 0 <= type <= 0xFFFF
* @param data byte array containing a service request structure
* @param offset start offset in bytes of request in <code>data</code>
* @param length the length in bytes of the whole request contained in
* <code>data</code>
* @throws KNXFormatException if buffer is too short for request, on unsupported
* service type or connection header structure
*/
public ServiceRequest(final int serviceType, final byte[] data, final int offset,
final int length) throws KNXFormatException
{
this(serviceType, data, offset, length, null);
if (svcType == KNXnetIPHeader.TUNNELING_REQ)
cemi = CEMIFactory.create(data, offset + CONN_HEADER_SIZE, length - CONN_HEADER_SIZE);
else if (svcType == KNXnetIPHeader.DEVICE_CONFIGURATION_REQ)
cemi = new CEMIDevMgmt(data, offset + CONN_HEADER_SIZE, length - CONN_HEADER_SIZE);
else
throw new KNXIllegalArgumentException("unsupported service request type");
}
/**
* Creates a new service request.
* <p>
*
* @param serviceType service request type identifier, 0 <= type <= 0xFFFF
* @param channelID channel ID of communication this request belongs to, 0 <= id
* <= 255
* @param seqNumber the sending sequence number of the communication channel, 0 <=
* number <= 255
* @param frame cEMI frame carried with the request
*/
public ServiceRequest(final int serviceType, final int channelID, final int seqNumber,
final CEMI frame)
{
super(serviceType);
if (serviceType < 0 || serviceType > 0xffff)
throw new KNXIllegalArgumentException("service request out of range [0..0xffff]");
if (channelID < 0 || channelID > 0xff)
throw new KNXIllegalArgumentException("channel ID out of range [0..0xff]");
if (seqNumber < 0 || seqNumber > 0xff)
throw new KNXIllegalArgumentException("sequence number out of range [0..0xff]");
channelid = channelID;
seq = seqNumber;
cemi = CEMIFactory.copy(frame);
}
// frame might be null, toByteArray will throw NPE then
ServiceRequest(final int serviceType, final byte[] data, final int offset, final int length,
final CEMI frame) throws KNXFormatException
{
super(serviceType);
if (length < CONN_HEADER_SIZE)
throw new KNXFormatException("buffer too short for service request");
final ByteArrayInputStream is = new ByteArrayInputStream(data, offset, length);
if (is.read() != CONN_HEADER_SIZE)
throw new KNXFormatException("unsupported connection header");
channelid = is.read();
seq = is.read();
/* final int reserved = */is.read();
cemi = frame;
}
/**
* Returns the service type identifier of the request.
* <p>
*
* @return service type as unsigned 16 bit value
*/
public final int getServiceType()
{
return svcType;
}
/**
* Returns the communication channel identifier associated with the request.
* <p>
*
* @return communication channel ID as unsigned byte
*/
public final int getChannelID()
{
return channelid;
}
/**
* Returns the sequence number of the sending endpoint.
* <p>
*
* @return sequence number as unsigned byte
*/
public final int getSequenceNumber()
{
return seq;
}
/**
* Returns the cEMI frame carried by the request.
* <p>
*
* @return a cEMI type
*/
public final CEMI getCEMI()
{
return CEMIFactory.copy(cemi);
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#getStructLength()
*/
int getStructLength()
{
return CONN_HEADER_SIZE + (cemi != null ? cemi.getStructLength() : 0);
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#toByteArray
* (java.io.ByteArrayOutputStream)
*/
byte[] toByteArray(final ByteArrayOutputStream os)
{
os.write(CONN_HEADER_SIZE);
os.write(channelid);
os.write(seq);
os.write(0);
final byte[] buf = cemi.toByteArray();
os.write(buf, 0, buf.length);
return os.toByteArray();
}
}
| gpl-2.0 |
NSIS-Dev/nsl-assembler | src/nsl/statement/StatementList.java | 2628 | /*
* StatementList.java
*/
package nsl.statement;
import java.io.IOException;
import java.util.ArrayList;
/**
* Describes a list of statements.
* @author Stuart
*/
public class StatementList extends Statement
{
private final ArrayList<Statement> statementList;
private final ArrayList<Statement> queuedStatementList;
private static StatementList current;
/**
* Gets the current statement list.
* @return the current statement list
*/
public static StatementList getCurrent()
{
return current;
}
/**
* Class constructor.
*/
private StatementList()
{
this.statementList = new ArrayList<Statement>();
this.queuedStatementList = new ArrayList<Statement>();
}
/**
* Matches a list of statements.
* @return a list of statements
*/
public static StatementList match()
{
StatementList statementListParent = current;
StatementList statementList = new StatementList();
current = statementList;
Statement statement;
while ((statement = Statement.match()) != null)
{
// Add the current statement.
statementList.statementList.add(statement);
// Add any queued statements (i.e. contents of a macro) and then dequeue
// them.
if (!statementList.queuedStatementList.isEmpty())
{
statementList.statementList.addAll(statementList.queuedStatementList);
statementList.queuedStatementList.clear();
}
}
current = statementListParent;
return statementList;
}
/**
* Adds a statement to the list.
* @param statement the statement to add
*/
public void add(Statement statement)
{
this.statementList.add(statement);
}
/**
* Adds a statement to the queued statements list. These statements will be
* added after the current statement.
* @param statement the statement to add
*/
public void addQueued(Statement statement)
{
this.queuedStatementList.add(statement);
}
/**
* Determines if the statement list is empty.
* @return <code>true</code> if the statement list is empty
*/
public boolean isEmpty()
{
return this.statementList.isEmpty();
}
/**
* Gets the last statement in the statement list.
* @return the last statement in the statement list
*/
public Statement getLast()
{
if (this.statementList.isEmpty())
return null;
return this.statementList.get(this.statementList.size() - 1);
}
/**
* Assembles the source code.
*/
@Override
public void assemble() throws IOException
{
for (Statement statement : this.statementList)
statement.assemble();
}
}
| gpl-2.0 |
intfloat/CoreNLP | src/edu/stanford/nlp/coref/neural/NeuralCorefProperties.java | 1093 | package edu.stanford.nlp.coref.neural;
import java.util.Locale;
import java.util.Properties;
import edu.stanford.nlp.coref.CorefProperties;
import edu.stanford.nlp.util.PropertiesUtils;
public class NeuralCorefProperties {
public static double greedyness(Properties props) {
return PropertiesUtils.getDouble(props, "coref.neural.greedyness", 0);
}
public static String modelPath(Properties props) {
String defaultPath = "edu/stanford/nlp/models/coref/neural/" +
(CorefProperties.getLanguage(props) == Locale.CHINESE ? "chinese" : "english") +
(CorefProperties.conll(props) ? "-model-conll" : "-model-conll") + ".ser.gz";
return PropertiesUtils.getString(props, "coref.neural.modelPath", defaultPath);
}
public static String pretrainedEmbeddingsPath(Properties props) {
String defaultPath = "edu/stanford/nlp/models/coref/neural/" +
(CorefProperties.getLanguage(props) == Locale.CHINESE ? "chinese" : "english") +
"-embeddings.ser.gz";
return PropertiesUtils.getString(props, "coref.neural.embeddingsPath", defaultPath);
}
}
| gpl-2.0 |
teamfx/openjfx-10-dev-rt | modules/javafx.controls/src/main/java/javafx/scene/control/MenuButton.java | 16823 | /*
* Copyright (c) 2010, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.scene.control;
import javafx.css.PseudoClass;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ObjectPropertyBase;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Side;
import javafx.scene.AccessibleAction;
import javafx.scene.AccessibleRole;
import javafx.scene.Node;
import javafx.scene.control.skin.MenuButtonSkin;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.property.ReadOnlyBooleanWrapper;
/**
* MenuButton is a button which, when clicked or pressed, will show a
* {@link ContextMenu}. A MenuButton shares a very similar API to the {@link Menu}
* control, insofar that you set the items that should be shown in the
* {@link #getItems() items} ObservableList, and there is a {@link #textProperty() text} property to specify the
* label shown within the MenuButton.
* <p>
* As mentioned, like the Menu API itself, you'll find an {@link #getItems() items} ObservableList
* within which you can provide anything that extends from {@link MenuItem}.
* There are several useful subclasses of {@link MenuItem} including
* {@link RadioMenuItem}, {@link CheckMenuItem}, {@link Menu},
* {@link SeparatorMenuItem} and {@link CustomMenuItem}.
* <p>
* A MenuButton can be set to show its menu on any side of the button. This is
* specified using the {@link #popupSideProperty() popupSide} property. By default
* the menu appears below the button. However, regardless of the popupSide specified,
* if there is not enough room, the {@link ContextMenu} will be
* smartly repositioned, most probably to be on the opposite side of the
* MenuButton.
*
* <p>Example:</p>
* <pre>
* MenuButton m = new MenuButton("Eats");
* m.getItems().addAll(new MenuItem("Burger"), new MenuItem("Hot Dog"));
* </pre>
*
* <p>
* MnemonicParsing is enabled by default for MenuButton.
* </p>
*
* @see MenuItem
* @see Menu
* @see SplitMenuButton
* @since JavaFX 2.0
*/
public class MenuButton extends ButtonBase {
/***************************************************************************
* *
* Static properties and methods *
* *
**************************************************************************/
/**
* Called prior to the MenuButton showing its popup after the user
* has clicked or otherwise interacted with the MenuButton.
* @since JavaFX 8u60
*/
public static final EventType<Event> ON_SHOWING =
new EventType<Event>(Event.ANY, "MENU_BUTTON_ON_SHOWING");
/**
* Called after the MenuButton has shown its popup.
* @since JavaFX 8u60
*/
public static final EventType<Event> ON_SHOWN =
new EventType<Event>(Event.ANY, "MENU_BUTTON_ON_SHOWN");
/**
* Called when the MenuButton popup <b>will</b> be hidden.
* @since JavaFX 8u60
*/
public static final EventType<Event> ON_HIDING =
new EventType<Event>(Event.ANY, "MENU_BUTTON_ON_HIDING");
/**
* Called when the MenuButton popup has been hidden.
* @since JavaFX 8u60
*/
public static final EventType<Event> ON_HIDDEN =
new EventType<Event>(Event.ANY, "MENU_BUTTON_ON_HIDDEN");
/***************************************************************************
* *
* Constructors *
* *
**************************************************************************/
/**
* Creates a new empty menu button. Use {@link #setText(String)},
* {@link #setGraphic(Node)} and {@link #getItems()} to set the content.
*/
public MenuButton() {
this(null, null);
}
/**
* Creates a new empty menu button with the given text to display on the
* button. Use {@link #setGraphic(Node)} and {@link #getItems()} to set the
* content.
*
* @param text the text to display on the menu button
*/
public MenuButton(String text) {
this(text, null);
}
/**
* Creates a new empty menu button with the given text and graphic to
* display on the button. Use {@link #getItems()} to set the content.
*
* @param text the text to display on the menu button
* @param graphic the graphic to display on the menu button
*/
public MenuButton(String text, Node graphic) {
this(text, graphic, (MenuItem[])null);
}
/**
* Creates a new menu button with the given text and graphic to
* display on the button, and inserts the given items
* into the {@link #getItems() items} list.
*
* @param text the text to display on the menu button
* @param graphic the graphic to display on the menu button
* @param items The items to display in the popup menu.
* @since JavaFX 8u40
*/
public MenuButton(String text, Node graphic, MenuItem... items) {
if (text != null) {
setText(text);
}
if (graphic != null) {
setGraphic(graphic);
}
if (items != null) {
getItems().addAll(items);
}
getStyleClass().setAll(DEFAULT_STYLE_CLASS);
setAccessibleRole(AccessibleRole.MENU_BUTTON);
setMnemonicParsing(true); // enable mnemonic auto-parsing by default
// the default value for popupSide = Side.BOTTOM therefor
// PSEUDO_CLASS_OPENVERTICALLY should be set from the start.
pseudoClassStateChanged(PSEUDO_CLASS_OPENVERTICALLY, true);
}
/***************************************************************************
* *
* Properties *
* *
**************************************************************************/
private final ObservableList<MenuItem> items = FXCollections.<MenuItem>observableArrayList();
/**
* The items to show within this buttons menu. If this ObservableList is modified
* at runtime, the Menu will update as expected.
* <p>
* Commonly used controls include including {@code MenuItem},
* {@code CheckMenuItem}, {@code RadioMenuItem},
* and of course {@code Menu}, which if added to a menu, will become a sub
* menu. {@link SeparatorMenuItem} is another commonly used Node in the Menu's items
* ObservableList.
* @return the list of menu items within this buttons menu
*/
public final ObservableList<MenuItem> getItems() {
return items;
}
// --- Showing
/**
* Indicates whether the {@link ContextMenu} is currently visible.
*/
private ReadOnlyBooleanWrapper showing = new ReadOnlyBooleanWrapper(this, "showing", false) {
@Override protected void invalidated() {
pseudoClassStateChanged(PSEUDO_CLASS_SHOWING, get());
super.invalidated();
}
};
private void setShowing(boolean value) {
// these events will not fire if the showing property is bound
Event.fireEvent(this, value ? new Event(ON_SHOWING) :
new Event(ON_HIDING));
showing.set(value);
Event.fireEvent(this, value ? new Event(ON_SHOWN) :
new Event(ON_HIDDEN));
}
public final boolean isShowing() { return showing.get(); }
public final ReadOnlyBooleanProperty showingProperty() { return showing.getReadOnlyProperty(); }
/**
* Indicates on which side the {@link ContextMenu} should open in
* relation to the MenuButton. Menu items are generally laid
* out vertically in either case.
* For example, if the menu button were in a vertical toolbar on the left
* edge of the application, you might change {@link #popupSideProperty() popupSide}
* to {@code Side.RIGHT} so that the popup will appear to the right of the MenuButton.
*
* @defaultValue {@code Side.BOTTOM}
*/
// TODO expose via CSS
private ObjectProperty<Side> popupSide;
public final void setPopupSide(Side value) {
popupSideProperty().set(value);
}
public final Side getPopupSide() {
return popupSide == null ? Side.BOTTOM : popupSide.get();
}
public final ObjectProperty<Side> popupSideProperty() {
if (popupSide == null) {
popupSide = new ObjectPropertyBase<Side>(Side.BOTTOM) {
@Override protected void invalidated() {
final Side side = get();
final boolean active = (side == Side.TOP) || (side == Side.BOTTOM);
pseudoClassStateChanged(PSEUDO_CLASS_OPENVERTICALLY, active);
}
@Override
public Object getBean() {
return MenuButton.this;
}
@Override
public String getName() {
return "popupSide";
}
};
}
return popupSide;
}
/**
* Called just prior to the {@code ContextMenu} being shown.
* @return the on showing property
* @since 10
*/
public final ObjectProperty<EventHandler<Event>> onShowingProperty() { return onShowing; }
public final void setOnShowing(EventHandler<Event> value) { onShowingProperty().set(value); }
public final EventHandler<Event> getOnShowing() { return onShowingProperty().get(); }
private ObjectProperty<EventHandler<Event>> onShowing = new ObjectPropertyBase<EventHandler<Event>>() {
@Override protected void invalidated() {
setEventHandler(ON_SHOWING, get());
}
@Override public Object getBean() {
return MenuButton.this;
}
@Override public String getName() {
return "onShowing";
}
};
/**
* Called just after the {@code ContextMenu} is shown.
* @return the on shown property
* @since 10
*/
public final ObjectProperty<EventHandler<Event>> onShownProperty() { return onShown; }
public final void setOnShown(EventHandler<Event> value) { onShownProperty().set(value); }
public final EventHandler<Event> getOnShown() { return onShownProperty().get(); }
private ObjectProperty<EventHandler<Event>> onShown = new ObjectPropertyBase<EventHandler<Event>>() {
@Override protected void invalidated() {
setEventHandler(ON_SHOWN, get());
}
@Override public Object getBean() {
return MenuButton.this;
}
@Override public String getName() {
return "onShown";
}
};
/**
* Called just prior to the {@code ContextMenu} being hidden.
* @return the on hiding property
* @since 10
*/
public final ObjectProperty<EventHandler<Event>> onHidingProperty() { return onHiding; }
public final void setOnHiding(EventHandler<Event> value) { onHidingProperty().set(value); }
public final EventHandler<Event> getOnHiding() { return onHidingProperty().get(); }
private ObjectProperty<EventHandler<Event>> onHiding = new ObjectPropertyBase<EventHandler<Event>>() {
@Override protected void invalidated() {
setEventHandler(ON_HIDING, get());
}
@Override public Object getBean() {
return MenuButton.this;
}
@Override public String getName() {
return "onHiding";
}
};
/**
* Called just after the {@code ContextMenu} has been hidden.
* @return the on hidden property
* @since 10
*/
public final ObjectProperty<EventHandler<Event>> onHiddenProperty() { return onHidden; }
public final void setOnHidden(EventHandler<Event> value) { onHiddenProperty().set(value); }
public final EventHandler<Event> getOnHidden() { return onHiddenProperty().get(); }
private ObjectProperty<EventHandler<Event>> onHidden = new ObjectPropertyBase<EventHandler<Event>>() {
@Override protected void invalidated() {
setEventHandler(ON_HIDDEN, get());
}
@Override public Object getBean() {
return MenuButton.this;
}
@Override public String getName() {
return "onHidden";
}
};
/***************************************************************************
* *
* Control methods *
* *
**************************************************************************/
/**
* Shows the {@link ContextMenu}, assuming this MenuButton is not disabled.
*
* @see #isDisabled()
* @see #isShowing()
*/
public void show() {
// TODO: isBound check is probably unnecessary here
if (!isDisabled() && !showing.isBound()) {
setShowing(true);
}
}
/**
* Hides the {@link ContextMenu}.
*
* @see #isShowing()
*/
public void hide() {
// TODO: isBound check is probably unnecessary here
if (!showing.isBound()) {
setShowing(false);
}
}
/**
* This has no impact.
*/
@Override
public void fire() {
if (!isDisabled()) {
fireEvent(new ActionEvent());
}
}
/** {@inheritDoc} */
@Override protected Skin<?> createDefaultSkin() {
return new MenuButtonSkin(this);
}
/***************************************************************************
* *
* Stylesheet Handling *
* *
**************************************************************************/
private static final String DEFAULT_STYLE_CLASS = "menu-button";
private static final PseudoClass PSEUDO_CLASS_OPENVERTICALLY =
PseudoClass.getPseudoClass("openvertically");
private static final PseudoClass PSEUDO_CLASS_SHOWING =
PseudoClass.getPseudoClass("showing");
/***************************************************************************
* *
* Accessibility handling *
* *
**************************************************************************/
/** {@inheritDoc} */
@Override
public void executeAccessibleAction(AccessibleAction action, Object... parameters) {
switch (action) {
case FIRE:
if (isShowing()) {
hide();
} else {
show();
}
break;
default: super.executeAccessibleAction(action);
}
}
}
| gpl-2.0 |
Creativa3d/box3d | paquetes/src/ListDatos/IListDatosGest.java | 649 | /*
* IListDatosGest.java
*
* Created on 16 de julio de 2002, 20:14
*/
package ListDatos;
import java.util.EventListener;
interface IListDatosGest extends EventListener {
/**
* Notificacion de que se ha anadido una fila a JList
* por lo que se anade el puntero a esa fila a la lista de punteros
*/
void addFilaDatos(int plIndex, IFilaDatos poFila) throws Exception ;
/**
* Notificacion de que se ha borrado una fila de JList desde otro JListDatos
* y se rehace el orden y el filtro pq todos los punteros a partir de ese han cambiado
*/
void removeFilaDatos(int plIndex, IFilaDatos poFila) throws Exception ;
}
| gpl-2.0 |
FauxFaux/jdk9-jaxp | test/javax/xml/jaxp/functional/catalog/NextCatalogTest.java | 7324 | /*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package catalog;
import static catalog.CatalogTestUtils.catalogResolver;
import static catalog.CatalogTestUtils.catalogUriResolver;
import static catalog.ResolutionChecker.checkPubIdResolution;
import static catalog.ResolutionChecker.checkSysIdResolution;
import static catalog.ResolutionChecker.checkUriResolution;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogUriResolver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/*
* @test
* @bug 8077931
* @library /javax/xml/jaxp/libs
* @run testng/othervm -DrunSecMngr=true catalog.NextCatalogTest
* @run testng/othervm catalog.NextCatalogTest
* @summary Get matched URIs from system, public and uri entries respectively,
* but some of the entries are defined in none-current catalog files.
*/
@Listeners({jaxp.library.FilePolicy.class})
public class NextCatalogTest {
private static final String CATALOG_NEXTCATALOGLEFT
= "nextCatalog-left.xml";
private static final String CATALOG_NEXTCATALOGRIGHT
= "nextCatalog-right.xml";
@Test(dataProvider = "systemId-matchedUri")
public void testNextCatalogOnSysId(String sytemId, String matchedUri) {
checkSysIdResolution(createEntityResolver(), sytemId, matchedUri);
}
@DataProvider(name = "systemId-matchedUri")
public Object[][] dataOnSysId() {
return new Object[][] {
// This matched URI of the specified system id is defined in a
// next catalog file.
{ "http://remote/dtd/sys/docAlice.dtd",
"http://local/base/dtd/docAliceNextLeftSys.dtd" },
// There are two matches of the specified system id. One is in
// the current catalog file, and the other is in a next catalog
// file. But finally, the returned matched URI is the one in the
// current catalog file.
{ "http://remote/dtd/sys/docBob.dtd",
"http://local/base/dtd/docBobLeftSys.dtd" },
// The matched URI of the specified system id is defined in a
// two-level next catalog file.
{ "http://remote/dtd/sys/docCarl.dtd",
"http://local/base/dtd/docCarlSys.dtd" },
// Multiple catalog files, which are defined as next catalog,
// have the matched system entries of the specified system id.
// But finally, the returned matched URI is the first found.
{ "http://remote/dtd/sys/docDuplicate.dtd",
"http://local/base/dtd/docDuplicateLeftSys.dtd" } };
}
@Test(dataProvider = "publicId-matchedUri")
public void testNextCatalogOnPubId(String publicId, String matchedUri) {
checkPubIdResolution(createEntityResolver(), publicId, matchedUri);
}
@DataProvider(name = "publicId-matchedUri")
public Object[][] dataOnPubId() {
return new Object[][] {
// This matched URI of the specified public id is defined in a
// next catalog file.
{ "-//REMOTE//DTD ALICE DOCALICE XML//EN",
"http://local/base/dtd/docAliceNextLeftPub.dtd" },
// There are two matches of the specified public id. One is in
// the current catalog file, and the other is in a next catalog
// file. But finally, the returned matched URI is the one in the
// current catalog file.
{ "-//REMOTE//DTD BOB DOCBOB XML//EN",
"http://local/base/dtd/docBobLeftPub.dtd" },
// The matched URI of the specified public id is defined in a
// two-level next catalog file.
{ "-//REMOTE//DTD CARL DOCCARL XML//EN",
"http://local/base/dtd/docCarlPub.dtd" },
// Multiple catalog files, which are defined as next catalog,
// have the matched public entries of the specified public id.
// But finally, the returned matched URI is the first found.
{ "-//REMOTE//DTD DUPLICATE DOCDUPLICATE XML//EN",
"http://local/base/dtd/docDuplicateLeftPub.dtd" } };
}
@Test(dataProvider = "uri-matchedUri")
public void testNextCatalogOnUri(String uri, String matchedUri) {
checkUriResolution(createUriResolver(), uri, matchedUri);
}
@DataProvider(name = "uri-matchedUri")
public Object[][] dataOnUri() {
return new Object[][] {
// This matched URI of the specified URI reference is defined in
// a next catalog file.
{ "http://remote/dtd/uri/docAlice.dtd",
"http://local/base/dtd/docAliceNextLeftURI.dtd" },
// There are two matches of the specified URI reference. One is
// in the current catalog file, and the other is in a next
// catalog file. But finally, the returned matched URI is the
// one in the current catalog file.
{ "http://remote/dtd/uri/docBob.dtd",
"http://local/base/dtd/docBobLeftURI.dtd" },
// The matched URI of the specified URI reference is defined in
// a two-level next catalog file.
{ "http://remote/dtd/uri/docCarl.dtd",
"http://local/base/dtd/docCarlURI.dtd" },
// Multiple catalog files, which are defined as next catalog,
// have the matched uri entries of the specified URI reference.
// But finally, the returned matched URI is the first found.
{ "http://remote/dtd/uri/docDuplicate.dtd",
"http://local/base/dtd/docDuplicateLeftURI.dtd" } };
}
private CatalogResolver createEntityResolver() {
return catalogResolver(CATALOG_NEXTCATALOGLEFT,
CATALOG_NEXTCATALOGRIGHT);
}
private CatalogUriResolver createUriResolver() {
return catalogUriResolver(CATALOG_NEXTCATALOGLEFT,
CATALOG_NEXTCATALOGRIGHT);
}
}
| gpl-2.0 |
captainsoft/terminal-angel-disease | src/com/captainsoft/TADr/model/fight/attack/party/MetzelAttack.java | 3087 | /*
* Copyright Captainsoft 2010 - 2015.
* All rights reserved.
*/
package com.captainsoft.TADr.model.fight.attack.party;
import com.captainsoft.TADr.model.fight.*;
import com.captainsoft.TADr.model.fight.attack.*;
import com.captainsoft.TADr.model.item.Item;
import com.captainsoft.spark.i18n.*;
import com.captainsoft.spark.utils.*;
/**
* A party attack with the current weapon, that affects more monsters.
* Used only by "King Ole Ozelot".
*
* @author mathias fringes
*/
public final class MetzelAttack implements PartyAttack {
// fields
private final MonsterParty monsterParty;
private final PartyFighter fighter;
// constructors
public MetzelAttack(PartyFighter fighter, MonsterParty monsterParty) {
super();
this.fighter = fighter;
this.monsterParty = monsterParty;
}
// PartyAttack
public Attack attack() {
Attack attack = new Attack();
attack.sound = 8;
if (fighter.weapon == null) {
attack.text = new TrKey("fight.attack.metzel.noWeapon", fighter.name());
return attack;
}
for (Monster monster : this.monsterParty) {
AttackBash attackBash = new AttackBash();
int points = calcAttackPoints(monster);
attackBash.monster = monster;
attackBash.hit = (points >= 0);
attackBash.points = points;
attackBash.image = Utils.rndPlus(14, 2);
attack.add(attackBash);
}
if (attack.hitCount() == 0) {
attack.text = new TrKey("fight.attack.metzel.fail", fighter.name());
} else {
attack.text = new TrKey("fight.attack.metzel.hit", fighter.name(), attack.hitCount());
}
// resting time
int restingTime = PartyAttackUtils.calcRestingTime(fighter, 48, 5);
attack.restingTime(restingTime);
// learning
attack.hasLearned = PartyAttackUtils.learnSpecial3(fighter.member);
if (attack.hasLearned) {
attack.learnText = new TrKey("fight.learn.special", fighter.member.specialAttackSkill.value()).variant(fighter.member.nr());
}
return attack;
}
// private
private int calcAttackPoints(Monster monster) {
float malus = 1.2f;
if (fighter.member.isOverweight()) {
malus *= 2;
}
Item weapon = fighter.weapon;
double funlost = (float) (Math.random() * fighter.member.getPtsFox() / 4 + Math.random() * fighter.curFitPoints() / 2);
funlost += fighter.member.specialAttackSkill.value() / 5;
double mMal = Math.random() * monster.speed * malus;
if ((Math.random() * funlost) < mMal) {
funlost = -1;
} else {
int itmVal = weapon.value();
funlost += itmVal + Math.random() * itmVal / 3;
if ((monster.resist & 1) == 1) {
funlost /= 6;
}
}
if (funlost >= 0 && funlost < 1) {
return 0;
} else {
return (int) funlost;
}
}
} | gpl-2.0 |
KLamkiewicz/Projekt-Zespolowy | Game/src/pl/studia/gra/WorldController.java | 11605 | package pl.studia.gra;
import pl.studia.objects.GameObject;
import pl.studia.objects.Level;
import pl.studia.objects.ingame.Character;
import pl.studia.objects.ingame.Character.JUMP_STATE;
import pl.studia.objects.ingame.Platform;
import pl.studia.screens.DirectedGame;
import pl.studia.util.CameraHelper;
import pl.studia.util.Constants;
import pl.studia.objects.ingame.*;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
public class WorldController extends InputAdapter{
private static final String TAG = WorldController.class.getName();
private DirectedGame game;
public CameraHelper cameraHelper;
public Sprite[] testSprites;
public int selectedSprite;
public Texture texture;
public Level level;
public Music music, collectedSound, jumpSound, hitSound;
//public int score;
public WorldController(DirectedGame game){
this.game=game;
music = Gdx.audio.newMusic(Gdx.files.internal("sound/game.mp3"));
collectedSound = Gdx.audio.newMusic(Gdx.files.internal("sound/coinSound.mp3"));
hitSound = Gdx.audio.newMusic(Gdx.files.internal("sound/hitSound.wav"));
jumpSound = Gdx.audio.newMusic(Gdx.files.internal("sound/hitSound.wav"));
music.setLooping(true);
init();
}
/*Initialization in separate method instead of in constructor,
* this approach can greatly reduce
* the interruptions by the Garbage Collector
* */
private void init(){
Gdx.input.setInputProcessor(this);
cameraHelper = new CameraHelper();
//initTestObjects();
initLevel();
//cameraHelper.setCharacter(testSprites[0]);
cameraHelper.setCharacter(level.character);
if(!music.isPlaying())
music.play();
}
private void initLevel() {
level = new Level(Constants.LEVEL_01);
}
/*This method contain the game logic and will
* be called several hundred times per second.
* It requires delta time so that it can apply
* updates to the game world according to the
* fraction of time */
public void update (float deltaTime){
//updateTestObjects(deltaTime);
handleInput(deltaTime);
level.update(deltaTime);
checkForCollision();
cameraHelper.shakeCam(deltaTime);
gameResult();
}
@Override
public boolean keyUp(int keycode) {
// Reset game world
if (keycode == Keys.R) {
init();
Gdx.app.debug(TAG, "Game world resetted");
}
// Select next sprite
// else if (keycode == Keys.SPACE) {
// selectedSprite = (selectedSprite + 1) % testSprites.length;
// Gdx.app.debug(TAG, "Sprite #" + selectedSprite + " selected");
// //cameraHelper.setCharacter(testSprites[selectedSprite]);
// }
else if (keycode==Keys.ESCAPE){
Gdx.app.log("Exit", Gdx.graphics.getWidth() + " " + Gdx.graphics.getHeight());
Gdx.app.exit();
}
else if (keycode==Keys.ENTER){
cameraHelper.setCharacter(cameraHelper.hasCharacter() ? null : level.character);
Gdx.app.debug(TAG, "Camera follow enabled: " + cameraHelper.hasCharacter());
}
else if(keycode==Keys.Q){
cameraHelper.evokeShakeCam(10);
Gdx.app.debug(TAG, "Shake enabled");
}
else if(keycode==Keys.RIGHT && level.character.animation!=null){
level.character.setAnimation(null);
}
else if(keycode==Keys.LEFT && level.character.animation!=null){
level.character.setAnimation(null);
}
return false;
}
// private void initTestObjects(){
//
// //Create new array for 5 sprites
// testSprites = new Sprite[5];
// texture = new Texture(Gdx.files.internal("data/test.png"));
// texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
// // Create new sprites using a random texture region
// for (int i = 0; i < testSprites.length; i++) {
// Sprite spr = new Sprite(texture);
// // Define sprite size to be 1m x 1m in game world
// spr.setSize(1.52f, 1.52f);
// // Set origin to spriteÕs center
// spr.setOrigin(spr.getWidth() / 2.0f, spr.getHeight() / 2.0f);
// // Calculate random position for sprite
// float randomX = MathUtils.random(0f, 1.0f);
// float randomY = MathUtils.random(0f, 1.0f);
// spr.setPosition(randomX, randomY);
// // Put new sprite into array
// testSprites[i] = spr;
// }
// // Set first sprite as selected one
// selectedSprite = 0;
// }
//
// private void updateTestObjects(float deltaTime){
//
// // Get current rotation from selected sprite
// float rotation = testSprites[selectedSprite].getRotation();
// //Rotate sprite by 90 degrees per second
// rotation+=90*deltaTime;
// rotation%=360;
// testSprites[selectedSprite].setRotation(rotation);
// }
//
// private void moveSelectedSprite(float x, float y){
// testSprites[selectedSprite].translate(x, y);
//
// }
private void moveCamera(float x, float y){
x+=cameraHelper.getPosition().x;
y+=cameraHelper.getPosition().y;
cameraHelper.setPosition(x,y);
}
@Override
public boolean keyDown(int keycode){
if (keycode == Keys.RIGHT && level.character.animation!=level.character.animJump) {
level.character.setAnimation(level.character.animWalk);
}
if (keycode == Keys.LEFT && level.character.animation!=level.character.animJump) {
level.character.setAnimation(level.character.animWalk);
}
return false;
}
//test method ONLY
private void handleInput(float deltaTime){
// Selected Sprite Controls - TEMPORARY
if (Gdx.input.isKeyPressed(Keys.LEFT)){
level.character.velocity.x = -level.character.terminalVelocity.x;
if(level.character.animation==null)
level.character.setAnimation(level.character.animWalk);
}
if (Gdx.input.isKeyPressed(Keys.RIGHT)){
level.character.velocity.x = level.character.terminalVelocity.x;
if(level.character.animation==null)
level.character.setAnimation(level.character.animWalk);
}
if(Gdx.input.isKeyPressed(Keys.SPACE)){
level.character.setJumping(true);
}
// if (Gdx.input.isKeyPressed(Keys.UP))
// moveSelectedSprite(0f, 0.2f);
// if (Gdx.input.isKeyPressed(Keys.DOWN))
// moveSelectedSprite(0f, -0.2f);
// Camera Controls Move
if (Gdx.input.isKeyPressed(Keys.A)){
moveCamera(-0.2f, 0f);
}
if (Gdx.input.isKeyPressed(Keys.D))
moveCamera(0.2f, 0f);
if (Gdx.input.isKeyPressed(Keys.W))
moveCamera(0f, 0.2f);
if (Gdx.input.isKeyPressed(Keys.S))
moveCamera(0f, -0.2f);
}
/*
* Creating rectangle which will be used for collisions
* First rectangle will contain the character
* Second rectangle will contain whichever object our character might come in contact with
* We will check if the boundaries of r1(character) overlap with the boundaries of r2(object)
*/
private Rectangle r1 = new Rectangle();
private Rectangle r2 = new Rectangle();
/*
* Our method which will check whether there is an overlap or not
*/
public void checkForCollision(){
for (GoldCoin goldcoin : level.goldCoins) {
if (goldcoin.collected) continue;
r2.set(goldcoin.position.x, goldcoin.position.y, goldcoin.bounds.width, goldcoin.bounds.height);
if (!r1.overlaps(r2)) continue;
onCollisionCharacterWithGoldCoin(goldcoin);
break;
}
/*
* Because our first rectangle will always be our character we can just set it now
* To define a rectangle we need the its bottom left corner position and its width and height
*/
r1.set(level.character.position.x, level.character.position.y, level.character.bounds.width, level.character.bounds.height);
/*
* In here we will loop through all of our objects, setting the r2
*/
for(GameObject platform : level.platforms){
r2.set(platform.position.x, platform.position.y, platform.bounds.width, platform.bounds.height);
/*
* Here we check the overlapping, if there is none we loop to the other object
* if we come across an rectangle overlap we execute the characterCollisionWithPlatform method
* which will make the character react to the collision
*/
if(!r1.overlaps(r2))
continue;
characterCollisionWithPlatform(platform);
}
}
/*
* This method is called where we detect the character collision with Platform
*/
public void characterCollisionWithPlatform(GameObject platform){
//Create reference to character so we can call character instead of level.character
Character character = level.character;
/*
* Here we check how big is the vertical overlap
* We get an absolute value from the character vertical position minus the sum of platform vertical position
* and platform bounds height
* This gives us a value how much has the character vertically overlapped with the platform
* If the overlap is greater than certain value we check the side collisions, otherwise we check the jumpState
*/
float overlap = Math.abs(character.position.y - (platform.position.y + platform.bounds.height));
if (overlap > 0.25f) {
/*
* Here we check which edge has been hit, checking if character horizontal position is greater than
* platform horizontal position plus half of platform width, meaning we can state which side has been hit
* if character horizontal position is greater that means left edge has been hit and the leftEdge equals true,
* otherwise leftEdge is false and the right edge of the platform has been hit
*/
boolean leftEdge = character.position.x > (platform.position.x + platform.bounds.width / 2.0f);
if (leftEdge) {
character.position.x = platform.position.x + platform.bounds.width;
} else {
character.position.x = platform.position.x - character.bounds.width;
}
return;
}
/*
* Here we check our character jumpState, only when the overlap is lesser than given value
* If the character is in the JUMP_FALLING state its vertical position will equal to platform vertical position
* plus its height, positioning our character right on top of it, then we change character state to GROUNDED
* If the character is in the JUMP_RISING state (meaning it can hit a platform from the bottom), we change its
* vertical position to platform vertical position plus character bounds height and its vertical origin, then we change
* the character state to JUMP_FALLING, because it can neither rise or be grounded
*/
switch (character.jumpState) {
case GROUNDED:
break;
case FALLING:
case JUMP_FALLING:
//character.position.y = platform.position.y + character.bounds.height + character.origin.y;
character.position.y = platform.position.y + platform.bounds.height;
character.jumpState = JUMP_STATE.GROUNDED;
break;
case JUMP_RISING:
character.position.y = platform.position.y + character.bounds.height;
hitSound.play();
//This removes the ping-pong effect
character.jumpState = JUMP_STATE.JUMP_FALLING;
break;
}
}
private void onCollisionCharacterWithGoldCoin (GoldCoin goldcoin) {
goldcoin.collected = true;
//score += goldcoin.getScore();
level.character.score += goldcoin.getScore();
collectedSound.play();
Gdx.app.log(TAG, "Gold coin collected");
}
private void gameResult(){
if(level.character.timeLeft<=0){
float delay = 0.05f; // seconds
Timer.schedule(new Task(){
@Override
public void run() {
init();
}
}, delay);
}
}
}
| gpl-2.0 |
ArnaudDemarcq/PocketWorlds | PocketWorlds/webapps/PwFrontend/src/main/java/org/krohm/pocketworlds/frontend/pages/MainPage/HomePage.java | 740 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.krohm.pocketworlds.frontend.pages.MainPage;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.krohm.pocketworlds.frontend.util.GetStringModel;
/**
*
* @author Arnaud
*/
public class HomePage extends BasePage {
public HomePage(PageParameters params) {
super(params);
}
@Override
protected IModel<String> getTitle() {
return new GetStringModel(this, "daa.basepage.label.home");
}
@Override
protected IModel<String> getSlogan() {
return new GetStringModel(this, "daa.basepage.label.slogan.home");
}
}
| gpl-2.0 |
SoWhoYou/breakcraft | client/menus/Menu.java | 4877 | package com.sowhoyou.breakcraft.client.menus;
import java.util.Set;
import java.util.TreeSet;
import org.lwjgl.input.Mouse;
import com.sowhoyou.breakcraft.BreakCraft;
import com.sowhoyou.breakcraft.client.mods.Mod;
public class Menu extends MenuBase {
public Menu(String title, int pos) {
this.setTitle(title);
this.setX1(BreakCraft.getMc().displayWidth);
this.setY1(0 + (25 * pos));
super.setFocused(this);
}
public void onUpdate() {
if (this.getX1() < 0) this.setX1(this.getPaddingX());
if ((this.getY1() - this.getLineSpacing()) < 0) this.setY1(this.getLineSpacing() + 1);
if ((this.getX1() + (this.getPaddingX() * 2) + this.getWidth()) > this.getScreen().width) this.setX1(this.getScreen().width - ((this.getPaddingX()) + this.getWidth()));
if ((this.getY1() + this.getHeight() > this.getScreen().height)) this.setY1(this.getScreen().height - this.getHeight() - this.getPaddingY());
this.setWindowFrameColor(super.getFocused().equals(this) ? 0xFF3399FF : 0x443399FF);
if (this.getDragging() && Mouse.isButtonDown(0)) {
this.setX1(this.getMouseX() - this.getFixX());
this.setY1(this.getMouseY() - this.getFixY());
} else {
this.setDragging(false);
}
this.setWidth((this.getContentWidth() > super.getFr().getStringWidth(this.getTitle()) ? this.getContentWidth() : super.getFr().getStringWidth(this.getTitle())) + (this.getPaddingX() * 2));
this.setX2(this.getX1() + this.getWidth());
this.setHeight(this.getCollapsed() ? (0) : (this.getContentSize() * this.getLineSpacing()));
this.setY2(this.getY1() + this.getHeight());
}
public void onMouseClick(int x, int y, int button) {
boolean inTitle = (x >= this.getX1() && x <= this.getX2() && y >= (this.getY1() - (this.getLineSpacing() + (this.getPaddingY() * 2))) && y <= this.getY1());
boolean inWindow = (x >= this.getX1() && x <= this.getX2() && y >= this.getY1() && y <= this.getY2());
if (super.getFocused().equals(this) && inTitle && !this.getDragging()) {
if (button == 0) {
this.setFixX(this.getMouseX() - this.getX1());
this.setFixY(this.getMouseY() - this.getY1());
this.setDragging(true);
super.setCanceled(true);
return;
} else
if (button == 1) {
this.setCollapsed(!this.getCollapsed());
super.setCanceled(true);
return;
}
}
int lineCount = 0;
if (super.getFocused().equals(this) && inWindow) {
Set<Mod> s = new TreeSet(this.getContent());
for (Mod m : s) {
boolean mouseOver = (x >= this.getX1() && x <= this.getX2() && y >= (this.getY1() + (this.getLineSpacing() * lineCount)) && y <= ((this.getY1() + (this.getLineSpacing()) + (this.getLineSpacing() * lineCount))));
if (button == 0 && mouseOver) {
if (this.getSelected() == m) {
m.keyPressed();
super.setCanceled(true);
break;
} else {
this.setSelected(m);
m.keyPressed();
super.setCanceled(true);
break;
}
}
lineCount++;
}
}
if (!super.getFocused().equals(this)) {
if (inTitle) {
if (button == 0) {
this.setFocused(this);
this.setFixX(this.getMouseX() - this.getX1());
this.setFixY(this.getMouseY() - this.getY1());
this.setDragging(true);
super.setCanceled(true);
return;
} else
if (button == 1) {
this.setFocused(this);
this.setCollapsed(!this.getCollapsed());
super.setCanceled(true);
return;
}
}
if (inWindow) {
this.setFocused(this);
super.setCanceled(true);
return;
}
}
}
public void onRender() {
int lineCount = 0;
int lineWidth = 0;
this.drawWindow(this.getX1(), this.getY1(), this.getX2() - 1, this.getY1() - this.getLineSpacing(), this.getWindowColor(), this.getWindowFrameColor());
this.drawCenteredString(this.getTitle(), this.getX1() + (this.getWidth() / 2), this.getY1() - this.getLineSpacing() + this.getPaddingY(), this.getTitleColor());
if (!this.getCollapsed()) {
this.drawWindow(this.getX1(), this.getY1(), this.getX2() - 1, this.getY2(), this.getWindowColor(), this.getWindowFrameColor());
Set<Mod> s = new TreeSet(this.getContent());
for (Mod m : s) {
String tempName = m.getEnabled() ? ("+ " + m.getName()) : ("- " + m.getName());
if ((super.getFr().getStringWidth(tempName) + (this.getPaddingX() * 2)) > lineWidth) lineWidth = (super.getFr().getStringWidth(tempName) + (this.getPaddingX() * 2));
this.drawString(tempName, this.getX1() + (this.getPaddingX() * 2), this.getY1() + (this.getLineSpacing() * lineCount) + this.getPaddingY(),
(this.getSelected() != null ? (this.getSelected().equals(m) ? this.getTextSelectedColor() : this.getTextColor()) : this.getTextColor()));
lineCount++;
}
}
this.setContentSize(lineCount);
this.setContentWidth(lineWidth);
}
}
| gpl-2.0 |
freenet/Thingamablog-Freenet | src/net/sf/thingamablog/gui/app/TBTableCellRenderer.java | 4628 | /*
* Created on May 1, 2004
*
* This file is part of Thingamablog. ( http://thingamablog.sf.net )
*
* Copyright (c) 2004, Bob Tantlinger All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*
*/
package net.sf.thingamablog.gui.app;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import net.atlanticbb.tantlinger.ui.UIUtils;
import net.sf.thingamablog.feed.FeedItem;
/**
* @author Bob Tantlinger
*
*
*
*/
public class TBTableCellRenderer extends JLabel implements TableCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 1L;
private DateFormat df =
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
private Date expireDate = null;
private Font plainFont = new Font("Dialog", Font.PLAIN, 12);
private Font boldFont = new Font("Dialog", Font.BOLD, 12);
private ImageIcon unreadItemIcon = UIUtils.getIcon(UIUtils.MISC, "unread_item.gif");
private ImageIcon readItemIcon = UIUtils.getIcon(UIUtils.MISC, "read_item.gif");
private ImageIcon postIcon = UIUtils.getIcon(UIUtils.X16, "post.png");
private ImageIcon uPostIcon = UIUtils.getIcon(UIUtils.X16, "update_post.png");
public void setExpireDate(Date d)
{
expireDate = d;
}
public Date getExpireDate()
{
return expireDate;
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
setOpaque(true);
setFont(plainFont);
//setBorder(new EmptyBorder(10, 10, 10, 6));
if(isSelected)
{
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
}
else
{
setForeground(table.getForeground());
setBackground(table.getBackground());
}
if(table.getModel() instanceof FeedTableModel)
{
FeedTableModel rsstm = (FeedTableModel)table.getModel();
TableColumn col = table.getColumnModel().getColumn(column);
if(!rsstm.isItemAtRowRead(row))
setFont(boldFont);
if(col.getHeaderValue() == FeedTableModel.READ)
{
if(rsstm.isItemAtRowRead(row))
setIcon(readItemIcon);
else
setIcon(unreadItemIcon);
}
else
setIcon(null);
}
else if(table.getModel() instanceof WeblogTableModel)
{
WeblogTableModel btm = (WeblogTableModel)table.getModel();
if(column == 0)
{
//is the modified column on the TableModel null?
if(btm.getValueAt(row, WeblogTableModel.MODIFIED_COL) == null)
setIcon(postIcon);
else
setIcon(uPostIcon);
}
else
setIcon(null);
}
if(value instanceof FeedItem)
{
setText(((FeedItem)value).getTitle());
return this;
}
else if(value instanceof Boolean)
{
setText("");
setHorizontalAlignment(SwingConstants.CENTER);
return this;
}
else if(value instanceof Integer)
{
Integer val = (Integer)value;
setHorizontalAlignment(SwingConstants.CENTER);
setText(val.intValue() + "");
return this;
}
else if(value instanceof Date)
{
Date d = (Date)value;
setText(df.format(d));
if((table.getModel() instanceof WeblogTableModel) &&
(column == WeblogTableModel.DATE_COL))
{
if(expireDate != null && d.before(expireDate))
setForeground(Color.red);
}
return this;
}
setHorizontalAlignment(SwingConstants.LEFT);
//setToolTipText(value.toString());
if(value == null)
setText("");
else
setText(value.toString());
return this;
}
}
| gpl-2.0 |
jklepp-tgm/BigPicture | src/main/java/kehd/bigpicture/model/Notification.java | 1734 | package kehd.bigpicture.model;
import javax.persistence.*;
import java.util.Collection;
import java.util.Date;
@Entity //Gibt an, dass diese Klasse als Tabelle in die DB gespeichert werden soll
public class Notification {
@Id //Definiert das Attribut als Primaerschluessel
@GeneratedValue(strategy = GenerationType.IDENTITY) //Gibt an, dass & wie der Wert des Primaerschluessels automatisch erzeugt wird (IDENTITY verwendet fuer die ID eine Spalte in der Tabelle)
private long id;
@Column //ueber @Column koennen Eigenschaften der Spalte angegeben werden wie z.B. der Name, ob sie unique ist oder ob sie den Wert null haben darf
private String message;
@Column
private Date timestamp;
@Enumerated(value = EnumType.STRING)
NotificationType type;
@ManyToOne // Ein Event kann mehrere Notifications haben
private Event event;
@ManyToMany
private Collection<User> recipients;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public NotificationType getType() {
return type;
}
public void setType(NotificationType type) {
this.type = type;
}
public Collection<User> getRecipients() {
return recipients;
}
public void setRecipients(Collection<User> recipients) {
this.recipients = recipients;
}
}
| gpl-2.0 |
Repeid/repeid | model/infinispan/src/main/java/org/repeid/models/cache/infinispan/stream/InOrganizationPredicate.java | 877 | package org.repeid.models.cache.infinispan.stream;
import java.io.Serializable;
import java.util.Map;
import java.util.function.Predicate;
import org.repeid.models.cache.infinispan.entities.InOrganization;
import org.repeid.models.cache.infinispan.entities.Revisioned;
public class InOrganizationPredicate implements Predicate<Map.Entry<String, Revisioned>>, Serializable {
private String organization;
public static InOrganizationPredicate create() {
return new InOrganizationPredicate();
}
public InOrganizationPredicate realm(String id) {
organization = id;
return this;
}
@Override
public boolean test(Map.Entry<String, Revisioned> entry) {
Object value = entry.getValue();
if (value == null)
return false;
if (!(value instanceof InOrganization))
return false;
return organization.equals(((InOrganization) value).getOrganization());
}
}
| gpl-2.0 |
psteinb/SPIM_Registration | src/main/java/mpicbg/spim/fusion/PreDeconvolutionFusion.java | 18318 | package mpicbg.spim.fusion;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.scijava.vecmath.Point3d;
import mpicbg.imglib.cursor.LocalizableByDimCursor;
import mpicbg.imglib.cursor.LocalizableCursor;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.image.ImageFactory;
import mpicbg.imglib.interpolation.Interpolator;
import mpicbg.imglib.multithreading.SimpleMultiThreading;
import mpicbg.imglib.type.numeric.real.FloatType;
import mpicbg.imglib.util.Util;
import mpicbg.models.AbstractAffineModel3D;
import mpicbg.models.NoninvertibleModelException;
import mpicbg.spim.io.IOFunctions;
import mpicbg.spim.postprocessing.deconvolution.ExtractPSF;
import mpicbg.spim.registration.ViewDataBeads;
import mpicbg.spim.registration.ViewStructure;
import fiji.plugin.Multi_View_Deconvolution;
public class PreDeconvolutionFusion extends SPIMImageFusion implements PreDeconvolutionFusionInterface
{
final Image<FloatType> images[], weights[], overlap;
final int numViews;
final boolean normalize;
final ExtractPSF extractPSF;
public PreDeconvolutionFusion( final ViewStructure viewStructure, final ViewStructure referenceViewStructure,
final ArrayList<IsolatedPixelWeightenerFactory<?>> isolatedWeightenerFactories,
final ArrayList<CombinedPixelWeightenerFactory<?>> combinedWeightenerFactories )
{
super( viewStructure, referenceViewStructure, isolatedWeightenerFactories, combinedWeightenerFactories );
// normalize the weights so the the sum for each pixel over all views is 1?
this.normalize = true;
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN )
IOFunctions.println("(" + new Date(System.currentTimeMillis()) + "): Reserving memory for fused image.");
final ImageFactory<FloatType> imageFactory = new ImageFactory<FloatType>( new FloatType(), conf.processImageFactory );
numViews = viewStructure.getNumViews();
if ( conf.deconvolutionJustShowOverlap )
{
overlap = imageFactory.createImage( new int[]{ imgW, imgH, imgD }, "overlap" );
images = null;
weights = null;
extractPSF = null;
}
else
{
overlap = null;
if ( conf.extractPSF )
extractPSF = new ExtractPSF( viewStructure );
else
extractPSF = ExtractPSF.loadAndTransformPSF( conf.psfFiles, conf.transformPSFs, viewStructure );
images = new Image[ numViews ];
weights = new Image[ numViews ];
if ( extractPSF == null )
return;
for ( int view = 0; view < numViews; view++ )
{
weights[ view ] = imageFactory.createImage( new int[]{ imgW, imgH, imgD }, "weights_" + view );
images[ view ] = imageFactory.createImage( new int[]{ imgW, imgH, imgD }, "view_" + view );
if ( images[ view ] == null || weights[ view ] == null )
{
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_ERRORONLY )
IOFunctions.println("PreDeconvolutionFusion.constructor: Cannot create output image: " + conf.processImageFactory.getErrorMessage() );
return;
}
}
}
}
public static void subtractBackground( final Image< FloatType > img, final float value )
{
for ( final FloatType t : img )
t.set( Math.max( 0, t.get() - value ) );
}
@Override
public void fuseSPIMImages( final int channelIndex )
{
//
// update views so that only the current channel is being fused
//
final ArrayList<ViewDataBeads> views = new ArrayList<ViewDataBeads>();
for ( final ViewDataBeads view : viewStructure.getViews() )
if ( view.getChannelIndex() == channelIndex )
views.add( view );
final int numViews = views.size();
if ( conf.deconvolutionJustShowOverlap )
{
PreDeconvolutionFusionSequential.computeOverlap( overlap, views, viewStructure,cropOffsetX, cropOffsetY, cropOffsetZ, scale, min );
return;
}
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN )
IOFunctions.println("Loading source images (Channel " + channelIndex + ").");
// this is only single channel for noew
if ( channelIndex > 0 )
return;
// load images
for ( final ViewDataBeads view : views )
{
view.getImage();
if ( Multi_View_Deconvolution.subtractBackground != 0 )
{
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_ERRORONLY )
IOFunctions.println( "PreDeconvolutionFusionSequential(): Subtracting background of " + Multi_View_Deconvolution.subtractBackground + " from " + view.getName() );
subtractBackground( view.getImage( false ), Multi_View_Deconvolution.subtractBackground );
view.getImage( true );
}
}
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN && isolatedWeightenerFactories.size() > 0 )
{
String methods = "(" + isolatedWeightenerFactories.get(0).getDescriptiveName();
for ( int i = 1; i < isolatedWeightenerFactories.size(); ++i )
methods += ", " + isolatedWeightenerFactories.get(i).getDescriptiveName();
methods += ")";
IOFunctions.println( "(" + new Date(System.currentTimeMillis()) + "): Init isolated weighteners for all views " + methods );
}
// init isolated pixel weighteners
final AtomicInteger ai = new AtomicInteger(0);
Thread[] threads = SimpleMultiThreading.newThreads(conf.numberOfThreads);
final int numThreads = threads.length;
// compute them all in paralell ( computation done while opening )
IsolatedPixelWeightener<?>[][] isoWinit = new IsolatedPixelWeightener<?>[ isolatedWeightenerFactories.size() ][ numViews ];
for (int j = 0; j < isoWinit.length; j++)
{
final int i = j;
final IsolatedPixelWeightener<?>[][] isoW = isoWinit;
for (int ithread = 0; ithread < threads.length; ++ithread)
threads[ithread] = new Thread(new Runnable()
{
public void run()
{
final int myNumber = ai.getAndIncrement();
for (int view = 0; view < numViews; view++)
if ( view % numThreads == myNumber)
{
IOFunctions.println( "Computing " + isolatedWeightenerFactories.get( i ).getDescriptiveName() + " for " + views.get( view ) );
isoW[i][view] = isolatedWeightenerFactories.get(i).createInstance( views.get(view) );
}
}
});
SimpleMultiThreading.startAndJoin( threads );
}
// test if the isolated weighteners were successfull...
try
{
boolean successful = true;
for ( IsolatedPixelWeightener[] iso : isoWinit )
for ( IsolatedPixelWeightener i : iso )
if ( i == null )
successful = false;
if ( !successful )
{
IOFunctions.println( "Not enough memory for computing the weights for the multi-view deconvolution." );
isoWinit = new IsolatedPixelWeightener[ 0 ][ 0 ];
}
}
catch (Exception e)
{
IOFunctions.println( "Not enough memory for computing the weights for the multi-view deconvolution." );
isoWinit = new IsolatedPixelWeightener[ 0 ][ 0 ];
}
final IsolatedPixelWeightener<?>[][] isoW = isoWinit;
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN )
IOFunctions.println( "(" + new Date(System.currentTimeMillis()) + "): Computing output image (Channel " + channelIndex + ").");
// cache the views, imageSizes and models that we use
final boolean useView[] = new boolean[ numViews ];
final AbstractAffineModel3D<?> models[] = new AbstractAffineModel3D[ numViews ];
for ( int i = 0; i < numViews; ++i )
{
useView[ i ] = Math.max( views.get( i ).getViewErrorStatistics().getNumConnectedViews(), views.get( i ).getTile().getConnectedTiles().size() ) > 0 || views.get( i ).getViewStructure().getNumViews() == 1;
// if a corresponding view that was used for registration is valid, this one is too
if ( views.get( i ).getUseForRegistration() == false )
{
final int angle = views.get( i ).getAcqusitionAngle();
final int timepoint = views.get( i ).getViewStructure().getTimePoint();
for ( final ViewDataBeads view2 : viewStructure.getViews() )
if ( view2.getAcqusitionAngle() == angle && timepoint == view2.getViewStructure().getTimePoint() && view2.getUseForRegistration() == true )
useView[ i ] = true;
}
models[ i ] = (AbstractAffineModel3D<?>)views.get( i ).getTile().getModel();
}
final int[][] imageSizes = new int[numViews][];
for ( int i = 0; i < numViews; ++i )
imageSizes[ i ] = views.get( i ).getImageSize();
ai.set( 0 );
threads = SimpleMultiThreading.newThreads( numThreads );
for (int ithread = 0; ithread < threads.length; ++ithread)
threads[ithread] = new Thread(new Runnable()
{
public void run()
{
try
{
final int myNumber = ai.getAndIncrement();
// temporary float array
final double[] tmp = new double[ 3 ];
// init combined pixel weighteners
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN && combinedWeightenerFactories.size() > 0 )
{
String methods = "(" + combinedWeightenerFactories.get(0).getDescriptiveName();
for ( int i = 1; i < combinedWeightenerFactories.size(); ++i )
methods += ", " + combinedWeightenerFactories.get(i).getDescriptiveName();
methods += ")";
if ( myNumber == 0 )
IOFunctions.println("Initialize combined weighteners for all views " + methods );
}
final CombinedPixelWeightener<?>[] combW = new CombinedPixelWeightener<?>[combinedWeightenerFactories.size()];
for (int i = 0; i < combW.length; i++)
combW[i] = combinedWeightenerFactories.get(i).createInstance( views );
// get iterators for isolated weights
final LocalizableByDimCursor<FloatType> isoIterators[][] = new LocalizableByDimCursor[ isoW.length ][ numViews ];
for (int i = 0; i < isoW.length; i++)
for (int view = 0; view < isoW[i].length; view++)
isoIterators[i][view] = isoW[i][view].getResultIterator();
final Point3d[] tmpCoordinates = new Point3d[ numViews ];
final int[][] loc = new int[ numViews ][ 3 ];
final double[][] locd = new double[ numViews ][ 3 ];
final boolean[] use = new boolean[ numViews ];
for ( int i = 0; i < numViews; ++i )
tmpCoordinates[ i ] = new Point3d();
final LocalizableCursor<FloatType> outIntensity[] = new LocalizableCursor[ numViews ];
final LocalizableCursor<FloatType> outWeights[] = new LocalizableCursor[ numViews ];
final float[] tmpWeights = new float[ numViews ];
for ( int i = 0; i < numViews; ++i )
{
outIntensity[ i ] = images[ i ].createLocalizableCursor();
outWeights[ i ] = weights[ i ].createLocalizableCursor();
}
final LocalizableCursor<FloatType> firstCursor = outIntensity[ 0 ];
// create Interpolated Iterators for the input images (every thread need own ones!)
final Interpolator<FloatType>[] interpolators = new Interpolator[ numViews ];
for (int view = 0; view < numViews ; view++)
interpolators[ view ] = views.get( view ).getImage().createInterpolator( conf.interpolatorFactorOutput );
while ( firstCursor.hasNext() )
{
for ( int i = 0; i < numViews; ++i )
{
outIntensity[ i ].fwd();
outWeights[ i ].fwd();
}
if ( firstCursor.getPosition(2) % numThreads == myNumber )
{
// get the coordinates if cropped (all coordinates are the same, so we only use the first cursor)
final int x = firstCursor.getPosition( 0 ) + cropOffsetX;
final int y = firstCursor.getPosition( 1 ) + cropOffsetY;
final int z = firstCursor.getPosition( 2 ) + cropOffsetZ;
// how many view contribute at this position
int num = 0;
for ( int i = 0; i < numViews; ++i )
{
if ( useView[ i ] )
{
tmpCoordinates[ i ].x = x * scale + min.x;
tmpCoordinates[ i ].y = y * scale + min.y;
tmpCoordinates[ i ].z = z * scale + min.z;
mpicbg.spim.mpicbg.Java3d.applyInverseInPlace( models[i], tmpCoordinates[i], tmp );
loc[i][0] = (int)Util.round( tmpCoordinates[i].x );
loc[i][1] = (int)Util.round( tmpCoordinates[i].y );
loc[i][2] = (int)Util.round( tmpCoordinates[i].z );
locd[i][0] = tmpCoordinates[i].x;
locd[i][1] = tmpCoordinates[i].y;
locd[i][2] = tmpCoordinates[i].z;
// do we hit the source image?
if ( loc[ i ][ 0 ] >= 0 && loc[ i ][ 1 ] >= 0 && loc[ i ][ 2 ] >= 0 &&
loc[ i ][ 0 ] < imageSizes[ i ][ 0 ] &&
loc[ i ][ 1 ] < imageSizes[ i ][ 1 ] &&
loc[ i ][ 2 ] < imageSizes[ i ][ 2 ] )
{
use[ i ] = true;
++num;
}
else
{
use[ i ] = false;
}
}
}
if ( num > 0 )
{
// update combined weighteners
if ( combW.length > 0 )
for ( final CombinedPixelWeightener<?> w : combW )
w.updateWeights(locd, use);
float sumWeights = 0;
//float value = 0;
for ( int view = 0; view < numViews; ++view )
{
if ( use[view] )
{
float weight = 1;
// multiplicate combined weights
if (combW.length > 0)
for (final CombinedPixelWeightener<?> w : combW)
weight *= w.getWeight(view);
// multiplicate isolated weights
for (int i = 0; i < isoW.length; i++)
{
isoIterators[ i ][ view ].setPosition( loc[ view ] );
weight *= isoIterators[ i ][ view ].getType().get();
}
tmp[ 0 ] = tmpCoordinates[view].x;
tmp[ 1 ] = tmpCoordinates[view].y;
tmp[ 2 ] = tmpCoordinates[view].z;
interpolators[view].moveTo( tmp );
if ( normalize )
{
sumWeights += weight;
// set the intensity, remember the weight
tmpWeights[ view ] = weight;
}
else
{
outWeights[ view ].getType().set( weight );
}
outIntensity[ view ].getType().set( interpolators[view].getType().get() );
}
}
// set the normalized weights
if ( normalize && sumWeights > 0 )
{
for ( int view = 0; view < numViews; ++view )
{
if ( use[view] )
{
if ( sumWeights > 1 )
outWeights[ view ].getType().set( tmpWeights[ view ]/sumWeights );
else
outWeights[ view ].getType().set( tmpWeights[ view ] );
}
}
}
}
} // myThread loop
} // iterator loop
for ( int i = 0; i < numViews; ++i )
{
outIntensity[ i ].close();
outWeights[ i ].close();
interpolators[ i ].close();
}
// close combined pixel weighteners
for (int i = 0; i < combW.length; i++)
combW[i].close();
// close isolated iterators
for (int i = 0; i < isoW.length; i++)
for (int view = 0; view < isoW[i].length; view++)
isoIterators[i][view].close();
}
catch (NoninvertibleModelException e)
{
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_ERRORONLY )
IOFunctions.println( "MappingFusionParalell(): Model not invertible for " + viewStructure );
}
}// Thread.run loop
});
SimpleMultiThreading.startAndJoin(threads);
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN )
IOFunctions.println("(" + new Date(System.currentTimeMillis()) + "): Closing all input images (Channel " + channelIndex + ").");
if ( conf.extractPSF )
{
// extract all PSF's
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN )
IOFunctions.println( "Extracting all PSF's" );
extractPSF.extract();
}
// unload images
for ( final ViewDataBeads view : views )
view.closeImage();
// close weighteners
// close isolated pixel weighteners
try
{
for (int i = 0; i < isoW.length; i++)
for (int view = 0; view < numViews; view++)
isoW[i][view].close();
}
catch (Exception e )
{
// this will fail if there was not enough memory...
}
if ( viewStructure.getDebugLevel() <= ViewStructure.DEBUG_MAIN )
IOFunctions.println("(" + new Date(System.currentTimeMillis()) + "): Done computing output image (Channel " + channelIndex + ").");
}
@Override
public Image<FloatType> getFusedImage() { return null; }
@Override
public Image<FloatType> getFusedImage( final int index ) { return images[ index ]; }
@Override
public Image<FloatType> getWeightImage( final int index ) { return weights[ index ]; }
@Override
public void closeImages()
{
for ( final ViewDataBeads view : viewStructure.getViews() )
view.closeImage();
}
@Override
public ArrayList<Image<FloatType>> getPointSpreadFunctions() { return extractPSF.getPSFs(); }
@Override
public ExtractPSF getExtractPSFInstance() { return this.extractPSF; }
@Override
public Image<FloatType> getOverlapImage() { return overlap; }
}
| gpl-2.0 |
gauravagerwala/VIT-StudentHandbook | app/src/main/java/vit/vithandbook/helperClass/XmlParseHandler.java | 9646 | package vit.vithandbook.helperClass;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import vit.vithandbook.R;
/**
* Created by pulkit on 15/06/2015.
*/
public class XmlParseHandler {
public Context context;
public LinearLayout container;
List<Pair<Integer, String>> images;
public String final_content;
//ImageSaver saver ;
public XmlParseHandler(Context context, LinearLayout container) {
this.context = context;
this.container = container;
}
public void parseXml(String xmlData) {
images = new ArrayList<Pair<Integer, String>>();
int position = 0;
try {
XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
//sample xml data
// xmlData = "<p>Lorem <font color = '#FF0000'>ipsum dolor</font> sit amet, consectetur adipiscing elit, sed do eiusmod tempor <b>incididunt</b> ut labore <i>et</i><br/><br/> dolore magna aliqua. Ut enim ad minim veniam, quis eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis ostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>" +
// "<img src = 'name.png'/><img src = 'name2.png'/>" +
// "<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. " +
// " labore et dolore magna aliqua. Ut enim</p><img src = 'name.png'/><p> ad minim veniam, quis eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim labore et dolore magna aliqua. Ut enim ad minim veniam, quis eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis n eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim </p>";
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setInput(new StringReader(xmlData));
int event = myparser.getEventType();
StringBuilder text = new StringBuilder("");
while (event != XmlPullParser.END_DOCUMENT) {
String name = myparser.getName();
switch (event) {
case XmlPullParser.START_TAG:
if ("img".equals(name)) {
String imagename = myparser.getAttributeValue(null, "src");
images.add(new Pair<Integer, String>(position, imagename));
position++;
} else if (!"p".equals(name)) {
text.append("<" + name);
if (myparser.getAttributeCount() == 0) {
text.append(">");
} else {
text.append(" ");
for (int i = 0; i < myparser.getAttributeCount(); i++) {
text.append(myparser.getAttributeName(i) + "='" + myparser.getAttributeValue(i) + "' ");
}
text.append(">");
}
}
break;
case XmlPullParser.TEXT:
text.append(myparser.getText());
break;
case XmlPullParser.END_TAG:
if ("p".equals(name)) {
AddTextView(text.toString());
text.setLength(0);
position++;
} else if (!"p".equals(name)) {
text.append("</" + name + ">");
}
break;
}
event = myparser.next();
}
for (Pair<Integer, String> p : images) {
AddImageView(p.second, p.first);
}
} catch (Exception e) {
e.printStackTrace();
}
}
void AddTextView(String content) {
final TextView view = new TextView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(params);
view.setTextColor(Color.rgb(45,45,45));
view.setTextSize(17);
view.setGravity(Gravity.LEFT);
view.setText(Html.fromHtml(content));
final_content = view.getText().toString();
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
container.addView(view);
}
});
}
public void AddImageView(String filename, final int pos) {
final ImageView view = new ImageView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
view.setLayoutParams(params);
File file = new File(context.getExternalFilesDir(null) + "/Images");
// saver.setParameters(new File(context.getExternalFilesDir(null)+"/Images"),view,filename);
if (!file.exists()) {
file.mkdir();
}
if (file.exists()) {
File image = new File(file, filename);
if (image.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(image.getAbsolutePath());
view.setImageBitmap(bmp);
} else {
LoadImageFromNet(filename, true, view);
}
} else {
LoadImageFromNet(filename, false, view);
}
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
container.addView(view, pos);
}
});
}
public void LoadImageFromNet(String name, boolean std, ImageView view) {
InputStream input = null;
Bitmap myBitmap = null;
try {
URL url = new URL("http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/3d-transparent-glass-icons-arrows/006764-3d-transparent-glass-icon-arrows-arrowhead-solid-right.png");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setConnectTimeout(2000);
connection.setReadTimeout(5000);
connection.connect();
input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
view.setImageBitmap(myBitmap);
} catch (Exception e) {
view.setImageResource(R.mipmap.ic_launcher);
return;
}
if (std) {
try {
File file = new File(context.getExternalFilesDir(null), "/Images/" + name);
FileOutputStream fout = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.PNG, 85, fout);
fout.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// picasso target class
class ImageSaver implements Target {
Context context;
ImageView view;
String imagename;
File storepath;
boolean savetodisk;
public ImageSaver(Context context) {
this.context = context;
}
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File image = new File(storepath, imagename);
FileOutputStream fOut = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
view.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
Log.d("store error", e.getMessage());
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
view.setImageResource(R.mipmap.ic_launcher);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {
}
}
public void setParameters(File file, ImageView view, String name) {
storepath = file;
this.view = view;
imagename = name;
}
}
| gpl-2.0 |
Bysmyyr/cpabe | jpbc/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/PolyField.java | 995 | package it.unisa.dia.gas.plaf.jpbc.field.poly;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
/**
* @author Angelo De Caro (angelo.decaro@gmail.com)
*/
public class PolyField<F extends Field> extends AbstractFieldOver<F, PolyElement> {
public PolyField(Random random, Field targetField) {
super(random, (F) targetField);
}
public PolyField(F targetField) {
super(new SecureRandom(), targetField);
}
public PolyElement newElement() {
return new PolyElement(this);
}
public BigInteger getOrder() {
throw new IllegalStateException("Not Implemented yet!!!");
}
public PolyElement getNqr() {
throw new IllegalStateException("Not Implemented yet!!!");
}
public int getLengthInBytes() {
throw new IllegalStateException("Not Implemented yet!!!");
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/vm/xchg_Ew_Gw.java | 2065 | /*
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 com.github.smeny.jpc.emulator.execution.opcodes.vm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class xchg_Ew_Gw extends Executable
{
final int op1Index;
final int op2Index;
public xchg_Ew_Gw(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
op1Index = Modrm.Ew(modrm);
op2Index = Modrm.Gw(modrm);
}
public Branch execute(Processor cpu)
{
Reg op1 = cpu.regs[op1Index];
Reg op2 = cpu.regs[op2Index];
int tmp2 = op2.get16();
int tmp1 = op1.get16();
op1.set16((short)tmp2);
op2.set16(tmp1);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
dlitz/resin | modules/resin/src/com/caucho/amber/gen/LoadGroupGenerator.java | 12544 | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.amber.gen;
import com.caucho.amber.table.LinkColumns;
import com.caucho.amber.table.AmberTable;
import com.caucho.amber.type.*;
import com.caucho.java.JavaWriter;
import com.caucho.java.gen.ClassComponent;
import com.caucho.util.L10N;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* Generates the Java code for the wrapped object.
*/
public class LoadGroupGenerator extends ClassComponent {
private static final L10N L = new L10N(LoadGroupGenerator.class);
private String _extClassName;
private EntityType _entityType;
private int _index;
public LoadGroupGenerator(String extClassName,
EntityType entityType,
int index)
{
_extClassName = extClassName;
_entityType = entityType;
_index = index;
}
/**
* Generates the load group.
*/
@Override
public void generate(JavaWriter out)
throws IOException
{
out.println();
out.println("protected void __caucho_load_" + _index + "(com.caucho.amber.manager.AmberConnection aConn)");
out.println("{");
out.pushDepth();
int group = _index / 64;
long mask = (1L << (_index % 64));
out.println("boolean isLoaded = (__caucho_loadMask_" + group
+ " & " + mask + "L) != 0;");
// jpa/0ge2: MappedSuperclassType
if (_entityType.getTable() != null) {
int min = 0;
if (_entityType.getParentType() == null)
min = _index;
// XXX: need to do another check for a long hierarchy and/or many-to-one
// if ((_entityType.getParentType() != null) &&
// (_index = _entityType.getParentType().getLoadGroupIndex() + 1)) {
// min = _entityType.getParentType().getLoadGroupIndex();
// }
int max = _index;
generateTransactionChecks(out, group, mask, min, max);
if (min <= max) {
out.println("else {");
out.pushDepth();
}
for (int i = min; i <= max; i++) {
// jpa/0l48: inheritance optimization.
out.println("if ((__caucho_loadMask_" + group + " & " + (1L << (i % 64)) + "L) == 0)");
out.println(" __caucho_load_select_" + i + "(aConn);");
}
if (min <= max) {
out.popDepth();
out.println("}");
}
out.println();
_entityType.generatePostLoadSelect(out, 1, _index);
// jpa/0o09
// needs to be after load to prevent loop if toString() expects data
out.println();
out.println("if (__caucho_log.isLoggable(java.util.logging.Level.FINER))");
out.println(" __caucho_log.finer(getClass().getSimpleName() + \"[\" + __caucho_getPrimaryKey() + \"] amber load-" + _index + "\");");
out.println();
out.println("if (! isLoaded) {");
out.pushDepth();
// ejb/06j2, ejb/0690
if (_entityType.getHasLoadCallback() && _index == 0) {
out.println();
out.println("__caucho_load_callback();");
}
// ejb/069a, jpa/0r00 vs. jpa/0r01
out.println();
out.println("if (__caucho_home != null)");
out.println(" __caucho_home.postLoad(this);");
// jpa/0r01: @PostLoad, with transaction.
// Within a transaction the entity is not copied
// directly from cache, so we need to invoke the
// callbacks after load. For jpa/0r00, see AmberMappedComponent.
generateCallbacks(out, _entityType.getPostLoadCallbacks());
out.popDepth();
out.println("}");
}
out.popDepth();
out.println("}");
if (_index == 0 && _entityType.getHasLoadCallback()) {
out.println();
out.println("protected void __caucho_load_callback() {}");
}
generateLoadSelect(out, group, mask);
if (_index == 0)
generateLoadNative(out);
}
private void generateLoadNative(JavaWriter out)
throws IOException
{
out.println();
out.println("public void __caucho_load_native(java.sql.ResultSet rs, String []columnNames)");
out.println(" throws java.sql.SQLException");
out.println("{");
out.pushDepth();
_entityType.generateLoadNative(out);
out.println("__caucho_loadMask_0 |= 1L;");
out.popDepth();
out.println("}");
}
private void generateTransactionChecks(JavaWriter out,
int group, long mask,
int min, int max)
throws IOException
{
// non-read-only entities must be reread in a transaction
if (! _entityType.isReadOnly()) {
// jpa/1800
out.println("if (aConn.isInTransaction()) {");
out.pushDepth();
// deleted objects are not reloaded
out.println("if (__caucho_state.isDeleting()) {");
out.println(" return;");
out.println("}");
// from non-transactional to transactional
out.println("else if (__caucho_state.isNonTransactional()) {");
out.pushDepth();
out.println("__caucho_state = com.caucho.amber.entity.EntityState.P_TRANSACTIONAL;");
// XXX: ejb/0d01 (create issue?)
// jpa/0g0k: see __caucho_load_select
// out.println(" aConn.makeTransactional(this);");
// out.println(" if ((state > 0) && ((__caucho_loadMask_" + group + " & " + mask + "L) != 0))");
// out.println(" return;");
out.println();
/* XXX: jpa/0o09
int loadCount = _entityType.getLoadGroupIndex();
for (int i = 0; i <= loadCount / 64; i++) {
out.println(" __caucho_loadMask_" + i + " = 0;");
}
*/
int dirtyCount = _entityType.getDirtyIndex();
for (int i = 0; i <= dirtyCount / 64; i++) {
out.println("__caucho_dirtyMask_" + i + " = 0;");
}
out.popDepth();
out.println("}");
// ejb/0d01 - already loaded in the transaction
/*
out.println("else if ((__caucho_loadMask_" + group + " & " + mask + "L) != 0)");
out.println(" return;");
*/
for (int i = min; i <= max; i++) {
// jpa/0l48: inheritance optimization.
out.println();
out.println("if ((__caucho_loadMask_" + group + " & " + (1L << (i % 64)) + "L) == 0)");
out.println(" __caucho_load_select_" + i + "(aConn);");
}
out.popDepth();
out.println("}");
out.print("else ");
}
out.println("if ((__caucho_loadMask_" + group + " & " + mask + "L) != 0) {");
out.println("}");
// XXX: the load doesn't cover other load groups
out.println("else if (__caucho_cacheItem != null) {");
out.pushDepth();
out.println(_extClassName + " item = (" + _extClassName + ") __caucho_cacheItem.getEntity();");
out.println("item.__caucho_load_select_" + _index + "(aConn);");
// ejb/06--, ejb/0a-- and jpa/0o04
_entityType.generateCopyLoadObject(out, "super", "item", _index);
// out.println("__caucho_loadMask_" + group + " |= " + mask + "L;");
//out.println("__caucho_loadMask_" + group + " |= item.__caucho_loadMask_" + group + ";"); // mask + "L;");
out.println("__caucho_loadMask_" + group + " |= item.__caucho_loadMask_" + group + " & " + mask + "L;"); // mask + "L;");
out.popDepth();
out.println("}");
}
private void generateLoadSelect(JavaWriter out, int group, long mask)
throws IOException
{
// jpa/0l40
if ((_index == 0) && (_entityType.getDiscriminator() != null)) {
out.println();
out.println("String __caucho_discriminator;");
}
out.println();
out.println("protected void __caucho_load_select_" + _index + "(com.caucho.amber.manager.AmberConnection aConn)");
out.println("{");
out.pushDepth();
if (_entityType.getTable() == null) {
out.popDepth();
out.println("}");
return;
}
out.println("if ((__caucho_loadMask_" + group + " & " + mask + "L) != 0)");
out.println(" return;");
AmberTable table = _entityType.getTable();
String from = null;
String select = null;
String where = null;
String subSelect = null;
AmberTable mainTable = null;
String tableName = null;
select = _entityType.generateLoadSelect(table, "o", _index);
if (select != null) {
from = table.getName() + " o";
where = _entityType.getId().generateMatchArgWhere("o");
mainTable = table;
tableName = "o";
}
ArrayList<AmberTable> subTables = _entityType.getSecondaryTables();
for (int i = 0; i < subTables.size(); i++) {
AmberTable subTable = subTables.get(i);
subSelect = _entityType.generateLoadSelect(subTable, "o" + i, _index);
if (subSelect == null)
continue;
if (select != null)
select = select + ", " + subSelect;
else
select = subSelect;
if (from != null)
from = from + ", " + subTable.getName() + " o" + i;
else
from = subTable.getName() + " o" + i;
if (where != null) {
LinkColumns link = subTable.getDependentIdLink();
where = where + " and " + link.generateJoin("o" + i, "o");
}
else
throw new IllegalStateException();
}
if (select == null) {
if (_index > 0) {
// XXX: jpa/0o00
out.println("return;");
out.popDepth();
out.println("}");
return;
}
select = "1";
}
if (where == null) {
from = table.getName() + " o";
where = _entityType.getId().generateMatchArgWhere("o");
}
String sql = "select " + select + " from " + from + " where " + where;
out.println();
out.println("java.sql.ResultSet rs = null;");
out.println();
out.println("try {");
out.pushDepth();
// jpa/0o05
//out.println("com.caucho.amber.entity.Entity contextEntity = aConn.getEntity(this);");
out.println();
out.print("String sql = \"");
out.printJavaString(sql);
out.println("\";");
out.println();
out.println("java.sql.PreparedStatement pstmt = aConn.prepareStatement(sql);");
out.println("int index = 1;");
_entityType.getId().generateSet(out, "pstmt", "index", "super");
out.println();
out.println("rs = pstmt.executeQuery();");
out.println("if (rs.next()) {");
out.pushDepth();
// jpa/0l40
if ((_index == 0) && (_entityType.getDiscriminator() != null)) {
out.println();
out.println("__caucho_discriminator = rs.getString(1);");
}
// jpa/0gg3
_entityType.generateLoad(out, "rs", "", 1, _index);
out.println("__caucho_loadMask_" + group + " |= " + mask + "L;");
out.popDepth();
out.println("}");
out.println("else {");
String errorString = ("(\"amber load: no matching object " +
_entityType.getName() + "[\" + __caucho_getPrimaryKey() + \"]\")");
out.println(" throw new com.caucho.amber.AmberObjectNotFoundException(" + errorString + ");");
out.println("}");
out.popDepth();
out.println("} catch (RuntimeException e) {");
out.println(" throw e;");
out.println("} catch (Exception e) {");
out.println(" throw new com.caucho.amber.AmberRuntimeException(e);");
out.println("} finally {");
out.println(" aConn.close(rs);");
out.println("}");
out.popDepth();
out.println("}");
}
private void generateCallbacks(JavaWriter out, ArrayList<Method> callbacks)
throws IOException
{
if (callbacks.size() == 0)
return;
out.println();
for (Method method : callbacks) {
out.println(method.getName() + "();");
}
}
}
| gpl-2.0 |
martints/gpsmid | src/de/ueller/gpsmid/routing/RouteLineProducer.java | 14880 | /*
* GpsMid - Copyright (c) 2009 sk750 at users dot sourceforge dot net
* See Copying
*/
package de.ueller.gpsmid.routing;
import java.util.Vector;
import de.ueller.gps.Node;
import de.ueller.gpsmid.data.Configuration;
import de.ueller.gpsmid.data.Legend;
import de.ueller.gpsmid.data.PaintContext;
import de.ueller.gpsmid.graphics.Proj2D;
import de.ueller.gpsmid.mapdata.WayDescription;
import de.ueller.gpsmid.tile.Tile;
import de.ueller.gpsmid.ui.Trace;
import de.ueller.util.IntTree;
import de.ueller.util.Logger;
import de.ueller.util.ProjMath;
import de.enough.polish.util.Locale;
public class RouteLineProducer implements Runnable {
private final static Logger logger = Logger.getInstance(RouteLineProducer.class,Logger.DEBUG);
private static volatile boolean abort = false;
/** the index of the route element until which the route line is produced and thus we can determine route instructions for */
public static volatile int maxRouteElementDone;
private static Trace trace;
public static Vector route;
public static IntTree routeLineTree;
public final static Boolean trueObject = new Boolean(true);
private static int connsFound = 0;
public static volatile int notifyWhenAtElement = Integer.MAX_VALUE;
private static volatile Thread producerThread = null;
public void determineRoutePath(Trace trace, Vector route) throws Exception {
// terminate any previous RouteLineProducers
abort();
RouteLineProducer.maxRouteElementDone = 0;
routeLineTree = new IntTree();
RouteLineProducer.trace = trace;
RouteLineProducer.route = route;
producerThread = new Thread(this, "RouteLineProducer");
producerThread.setPriority(Thread.MIN_PRIORITY);
producerThread.start();
}
public void run() {
try {
PaintContext pc = new PaintContext(trace, null);
connsFound=0;
float routeLen=0f;
long startTime = System.currentTimeMillis();
pc.searchConPrevWayRouteFlags = 0;
if (route != null && route.size() > 1){
// LayoutElement e = trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
for (int i=0; i<route.size()-1 && !RouteLineProducer.abort; i++){
//#debug debug
logger.debug("determineRoutePath " + i + "/" + (route.size() - 2) );
routeLen += searchConnection2Ways(pc, i);
RouteLineProducer.maxRouteElementDone = i;
// when route line is produced until notifyWhenAtElement, wake up getRouteElement()
if (i >= notifyWhenAtElement) {
synchronized (this) {
//#debug debug
logger.debug("notifying " + i );
notifyWhenAtElement = Integer.MAX_VALUE;
notify();
}
}
}
if (!RouteLineProducer.abort) {
maxRouteElementDone = route.size();
//#debug debug
logger.debug("Connection2Ways found: " + connsFound + "/" + (route.size()-1) + " in " + (long)(System.currentTimeMillis() - startTime) + " ms");
trace.receiveMessage (Locale.get("routelineproducer.Route")/*Route: */ + Trace.showDistance((int) routeLen, Trace.DISTANCE_ROAD) + (connsFound==(route.size()-1)?"":" (" + connsFound + "/" + (route.size()-1) + ")"));
ConnectionWithNode c;
boolean hasMotorways = false;
boolean hasTollRoads = false;
for (int i=0; i < route.size() - 1; i++){
c = (ConnectionWithNode) route.elementAt(i);
if ((c.wayRouteFlags & Legend.ROUTE_FLAG_TOLLROAD) != 0) {
hasTollRoads = true;
}
if ((c.wayRouteFlags & (Legend.ROUTE_FLAG_MOTORWAY | Legend.ROUTE_FLAG_MOTORWAY_LINK)) != 0) {
hasMotorways = true;
}
}
String routeWarning = "";
if (hasTollRoads) {
routeWarning += Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_USE_TOLLROADS)? Locale.get("routing.RouteContainsTollroads") : Locale.get("routing.RouteContainsUnavoidableTollroads");
}
if (hasMotorways && !Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_USE_MOTORWAYS)) {
if (routeWarning.length() != 0) {
routeWarning += ", ";
}
routeWarning += Locale.get("routing.RouteContainsUnavoidableMotorways");
}
if (routeWarning.length() != 0) {
trace.alert(Locale.get("routing.RouteContainsTitle"), routeWarning, 5000);
}
} else {
//#debug debug
logger.debug("RouteLineProducer aborted at " + connsFound + "/" + (route.size()-1));
maxRouteElementDone = 0;
}
}
} catch (Exception e) {
//#debug error
logger.error(Locale.get("routelineproducer.RouteLineProducerCrashed")/*RouteLineProducer crashed with */ + e.getMessage());
e.printStackTrace();
}
producerThread = null;
synchronized (this) {
notifyAll();
}
}
public static float searchConnection2Ways(PaintContext pc, int iConnFrom) throws Exception {
ConnectionWithNode cFrom;
ConnectionWithNode cTo;
cFrom = (ConnectionWithNode) route.elementAt(iConnFrom);
// take a bigger angle for lon because of positions near to the pols.
Node nld=new Node(cFrom.to.lat - 0.0001f, cFrom.to.lon - 0.0005f,true);
Node nru=new Node(cFrom.to.lat + 0.0001f,cFrom.to.lon + 0.0005f,true);
pc.searchCon1Lat = cFrom.to.lat;
pc.searchCon1Lon = cFrom.to.lon;
cTo = (ConnectionWithNode) route.elementAt(iConnFrom+1);
pc.searchCon2Lat = cTo.to.lat;
pc.searchCon2Lon = cTo.to.lon;
pc.searchLD=nld;
pc.searchRU=nru;
pc.conWayDistanceToNext = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
pc.conWayNumToRoutableWays = 0;
pc.conWayNumMotorways = 0;
// clear stored nameidxs
pc.conWayNumNameIdxs = 0;
pc.conWayNameIdxs.removeAll();
pc.conWayBearingsCount = 0;
pc.setP(new Proj2D(new Node(pc.searchCon1Lat,pc.searchCon1Lon, true),5000,100,100));
for (int i = 0; i < 4; i++) {
if (Legend.tileScaleLevelContainsRoutableWays[i]) {
trace.tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_CONNECTIONS2WAY);
}
}
if (pc.conWayDistanceToNext != Float.MAX_VALUE ) {
cFrom = (ConnectionWithNode) route.elementAt(iConnFrom);
cFrom.wayFromConAt = pc.conWayFromAt;
cFrom.wayToConAt = pc.conWayToAt;
cFrom.wayNameIdx = pc.conWayNameIdx;
//#if polish.bigstyles
cFrom.wayType = pc.conWayType;
//#else
cFrom.wayType = (byte) (pc.conWayType & 0xff);
//#endif
cFrom.wayDistanceToNext = pc.conWayDistanceToNext;
// at the final route seg reduce the distance to be only until the closest point on the destination way
if (iConnFrom == route.size() - 2) {
cFrom.wayDistanceToNext = ProjMath.getDistance(cFrom.to.lat, cFrom.to.lon, RouteInstructions.getClosestPointOnDestWay().radlat, RouteInstructions.getClosestPointOnDestWay().radlon);
}
// if there is a max speed on the way (also a winter maxspeed)
if (pc.conWayMaxSpeed != 0) {
// calculate the duration for the connection in 1/5s from the distance in meters and the maxSpeed in km/h
short calculatedDurationFSecs = (short) ( (cFrom.wayDistanceToNext * 5 * 3.6f) / pc.conWayMaxSpeed - 1);
// if the duration from the maxSpeed is lower than the duration from the duration for the max speed, use this as connection duration
if (calculatedDurationFSecs > cFrom.durationFSecsToNext) {
System.out.println("Using increased connection duration in 1/5s from max(winter)speed: " + calculatedDurationFSecs + " instead of " + cFrom.durationFSecsToNext + " maxSpeed km/h:" + pc.conWayMaxSpeed );
cFrom.durationFSecsToNext = calculatedDurationFSecs;
}
}
cFrom.wayRouteFlags = pc.conWayRouteFlags;
cFrom.numToRoutableWays = pc.conWayNumToRoutableWays;
if ( (pc.searchConPrevWayRouteFlags & Legend.ROUTE_FLAG_ONEDIRECTION_ONLY) == 0) {
/* if we are NOT coming from a oneway substract the way we are coming from as a way we can route to
* (for oneways the way we are coming from has not been counted anyway)
*/
cFrom.numToRoutableWays--;
}
cTo.wayConStartBearing = pc.conWayStartBearing;
cTo.wayConEndBearing = pc.conWayEndBearing;
if (Math.abs(cTo.wayConEndBearing - cTo.endBearing) > 3) {
cFrom.wayRouteFlags |= Legend.ROUTE_FLAG_INCONSISTENT_BEARING;
}
if (Math.abs(cTo.wayConStartBearing - cTo.startBearing) > 3) {
cTo.wayRouteFlags |= Legend.ROUTE_FLAG_INCONSISTENT_BEARING;
}
int countSameBearings = 0;
for (int b = 0; b < pc.conWayBearingsCount; b++) {
short bearingAlternative = pc.conWayBearings[b];
if (cTo.wayConStartBearing == bearingAlternative) {
countSameBearings++;
}
}
if (countSameBearings>1) {
System.out.println("!!! " + countSameBearings + " same bearings at conn " + iConnFrom);
}
// System.out.println(iConnFrom + ": " + cTo.wayConStartBearing);
// check if we need a bearing instruction at this connection
for (int b = 0; b < pc.conWayBearingsCount; b++) {
short bearingAlternative = pc.conWayBearings[b];
// System.out.println(bearing);
if (cTo.wayConStartBearing != bearingAlternative) {
byte riRoute = RouteInstructions.convertTurnToRouteInstruction( (cTo.wayConStartBearing - cFrom.wayConEndBearing) * 2 );
byte riCheck = RouteInstructions.convertTurnToRouteInstruction( (bearingAlternative - cFrom.wayConEndBearing) * 2 );
// if we got a second straight-on way at the connection, we need to check if we must tell the bearing
if (riRoute == RouteInstructions.RI_STRAIGHT_ON && riCheck == RouteInstructions.RI_STRAIGHT_ON) {
WayDescription wdRoute = Legend.getWayDescription(cFrom.wayType);
WayDescription wdCheck = Legend.getWayDescription(pc.conWayBearingWayType[b]);
// but not if there's exactly one alternative to leave/enter the motorway don't add the bearing
if ( pc.conWayNumMotorways != 1
&& (
// when the way on the route is a highway link
wdRoute.isHighwayLink()
||
/* when the route way is smaller or same width like the alternative way or both route and alternative way are mainstreet net roads
* (don't give bearing instruction when passing e.g. besides service ways but if both route and alternative way are mainstreet net roads)
* and neither the way on the route nor the alternative way is a highway link
* TODO: should we really check for wayWidth or use some other criteria?
*/
(
(wdRoute.wayWidth <= wdCheck.wayWidth || (wdRoute.isMainstreetNet() && wdCheck.isMainstreetNet()) )
&&
!(wdRoute.isHighwayLink() || wdCheck.isHighwayLink())
)
||
// when both alternatives are motorways (or motorway links) always give the bear instruction
wdRoute.isMotorway() && wdCheck.isMotorway()
)
) {
int iBearingAlternative = (int) (bearingAlternative) * 2;
if (iBearingAlternative < 0) iBearingAlternative += 360;
int iBearingRoute = (int) (cTo.wayConStartBearing) * 2;
if (iBearingRoute < 0) iBearingRoute += 360;
// System.out.println(b + ":" + iBearingRoute + " " + iBearingAlternative);
// if the bearing difference is more than 180 degrees, the angle in the other direction is smaller,
// so simply swap signs of the bearings to make the later comparison give the opposite result
if (Math.abs(iBearingRoute - iBearingAlternative) > 180) {
iBearingAlternative = -iBearingAlternative;
iBearingRoute = -iBearingRoute;
//System.out.println("changed signs: " + iBearingRoute + " " + iBearingAlternative);
}
if (iBearingRoute < iBearingAlternative) {
cFrom.wayRouteFlags |= Legend.ROUTE_FLAG_BEAR_LEFT;
} else {
cFrom.wayRouteFlags |= Legend.ROUTE_FLAG_BEAR_RIGHT;
}
cFrom.wayTypeOfAlternativeBearingWay = pc.conWayBearingWayType[b];
}
}
}
}
// get ways with same names leading away from the connection
int iNumWaysWithThisNameConnected = 99;
if (pc.conWayNameIdx >= 0) { // only valid name idxs
Integer oNum = (Integer) (pc.conWayNameIdxs.get(pc.conWayNameIdx));
if (oNum != null) {
iNumWaysWithThisNameConnected = oNum.intValue();
}
}
if (iNumWaysWithThisNameConnected > 1) {
cFrom.wayRouteFlags |= Legend.ROUTE_FLAG_LEADS_TO_MULTIPLE_SAME_NAMED_WAYS;
}
//System.out.println(iConnFrom + ": " + iNumWaysWithThisNameConnected);
pc.searchConPrevWayRouteFlags = cFrom.wayRouteFlags;
connsFound++;
} else {
// if we had no way match, look for an area match
// System.out.println("search AREA MATCH FOR: " + iConnFrom);
for (int i = 0; i < 4; i++) {
trace.tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_CONNECTIONS2AREA);
}
// if we've got an area match
if (pc.conWayDistanceToNext != Float.MAX_VALUE ) {
cFrom = (ConnectionWithNode) route.elementAt(iConnFrom);
cFrom.wayFromConAt = pc.conWayFromAt;
cFrom.wayToConAt = pc.conWayToAt;
cFrom.wayNameIdx = pc.conWayNameIdx;
//#if polish.bigstyles
cFrom.wayType = pc.conWayType;
//#else
cFrom.wayType = (byte) (pc.conWayType & 0xff);
//#endif
cFrom.wayDistanceToNext = pc.conWayDistanceToNext;
cFrom.wayRouteFlags |= Legend.ROUTE_FLAG_AREA;
System.out.println("AREA MATCH FOR: " + iConnFrom);
connsFound++;
} else {
System.out.println("NO MATCH FOR: " + iConnFrom);
return 0f;
}
}
if (!RouteLineProducer.abort) {
routeLineTree.put(pc.conWayCombinedFileAndWayNr, trueObject);
}
return cFrom.wayDistanceToNext;
}
public static boolean isWayIdUsedByRouteLine(int wayId) {
return (routeLineTree != null && routeLineTree.get(wayId) != null);
}
public static boolean isRouteLineProduced() {
return (route != null && maxRouteElementDone == route.size());
}
/** abort the current route line production */
public synchronized void abort() {
RouteLineProducer.abort = true;
notifyAll();
try {
while ((producerThread != null) && (producerThread.isAlive())) {
wait(1000);
}
} catch (InterruptedException e) {
//Nothing to do
}
RouteLineProducer.abort = false;
}
/** returns if a route line is currently produced */
public static boolean isRunning() {
return (producerThread != null);
}
/** wait until route line is produced up to route element at index i */
public void waitForRouteLine(int i) {
//#debug debug
logger.debug("waitForRouteLine:" + i + ", maxRouteElement: " + maxRouteElementDone);
while (i >= maxRouteElementDone && !RouteLineProducer.abort) {
if (!isRunning()) {
//System.out.println("ERROR: Waiting for route line but RouteLineProducer is not running");
return;
}
synchronized (this) {
try {
notifyWhenAtElement = i;
wait(5000);
//#debug debug
logger.debug(" routeLineWait timed out waiting for: " + i + " maxRouteElement: " + maxRouteElementDone);
} catch(InterruptedException e) {
//#debug debug
logger.debug(" routeLineWait notified " + i);
}
}
}
}
} | gpl-2.0 |
USGS-CIDA/SOS | core/api/src/main/java/org/n52/sos/ogc/sensorML/elements/SmlClassifier.java | 4038 | /**
* Copyright (C) 2012-2014 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.ogc.sensorML.elements;
import org.n52.sos.util.StringHelper;
/**
* SOS internal representation of SensorML classifier
*
* @author <a href="mailto:e.h.juerrens@52north.org">Eike Hinderk
* Jürrens</a>
* @author <a href="mailto:c.hollmann@52north.org">Carsten Hollmann</a>
*
* @since 4.0.0
*/
public class SmlClassifier {
public static final String PROCEDURE_TYPE = "procedureType";
public static final String INTENDED_APPLICATION = "intendedApplication";
private String name;
private String definition;
/**
* Classifier codeSpace href
*/
private String codeSpace;
private String value;
/**
* constructor
*
* @param name
* Classifier name
* @param definition
* Classifier definition (OPTIONAL)
* @param codeSpace
* Classifier codeSpace (OPTIONAL)
* @param value
* Classifier value
*/
public SmlClassifier(final String name, final String definition, final String codeSpace,
final String value) {
super();
this.name = name;
this.definition = definition;
this.codeSpace = codeSpace;
this.value = value;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(final String name) {
this.name = name;
}
/**
* @return the Classifier definition
*/
public String getDefinition() {
return definition;
}
/**
* @param definition
* Identifier definition
*/
public void setDefinition(final String definition) {
this.definition = definition;
}
/**
* @return the Classifier codeSpace href
*/
public String getCodeSpace() {
return codeSpace;
}
/**
* @param codeSpace href
* Classifier codeSpace href
*/
public void setCodeSpace(final String codeSpace) {
this.codeSpace = codeSpace;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value
* the value to set
*/
public void setValue(final String value) {
this.value = value;
}
/**
* @return <code>true</code>, if the codeSpace is set AND not empty
*/
public boolean isSetCodeSpace() {
return StringHelper.isNotEmpty(codeSpace);
}
/**
* @return <code>true</code>, if the codeSpace is set AND not empty
*/
public boolean isSetDefinition() {
return StringHelper.isNotEmpty(definition);
}
}
| gpl-2.0 |
Ankama/harvey | src/com/ankamagames/dofus/harvey/engine/numeric/bytes/sets/classes/comparators/ByteSplitter.java | 3323 | /**
*
*/
package com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes.comparators;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import com.ankamagames.dofus.harvey.engine.common.sets.interfaces.ISortedSet;
import com.ankamagames.dofus.harvey.engine.generic.comparators.Splitter;
import com.ankamagames.dofus.harvey.numeric.bytes.sets.classes.ByteInterval;
import com.ankamagames.dofus.harvey.numeric.bytes.sets.classes.DegenerateByteSet;
import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteBound;
import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteInterval;
import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteSet;
import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IElementaryByteSet;
import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.ISimpleByteSet;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* @author blefevre
*
*/
@NonNullByDefault
public class ByteSplitter
implements Splitter<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval>
{
private static ByteSplitter _instance = new ByteSplitter();
public static ByteSplitter getInstance()
{
return _instance ;
}
private ByteSplitter()
{}
@Override
public IByteInterval[] split(final IByteInterval source)
{
final IByteBound lowerBoundObject = source.getLowerBound();
final IByteBound upperBoundObject = source.getUpperBound();
final byte diff;
final byte tmpLowerbound;
final byte tmpUpperbound;
if (lowerBoundObject == null || upperBoundObject == null || ((diff = (byte) ((tmpUpperbound = (upperBoundObject.getValue())) - (tmpLowerbound = lowerBoundObject.getValue()))) <= 0))
return new IByteInterval[]{};
final byte lowerbound = tmpLowerbound;
final byte upperbound = tmpUpperbound;
if(diff==1)
{
return new IByteInterval[]{ByteInterval.makeInterval(tmpLowerbound, tmpUpperbound), DegenerateByteSet.makeSet(tmpUpperbound)};
}
final byte splitBound = (byte) ((lowerbound+upperbound)/2);
return new IByteInterval[]{ByteInterval.makeInterval(tmpLowerbound, splitBound),
ByteInterval.makeInterval(splitBound, tmpUpperbound)};
}
@Override
public List<? extends IByteSet> split(final IByteSet set, int parts)
{
if(parts<=0 )
return Arrays.asList(set);
final double size = set.size();
if(parts > size)
parts = (int) size;
final byte chunk = (byte) (size/(parts-1));
final byte[] ret = new byte[parts];
int index = 0;
final Iterator<IByteBound> it = set.getBoundIterator();
IByteBound currentLowerBound = it.next();
IByteBound currentUpperBound = it.next();
byte next = currentLowerBound.getValue();
double currentChunckProgress = chunk-1;// because next is already the first value
double dist = currentUpperBound.compareTo(currentLowerBound);
while(index<parts)
{
if(currentChunckProgress <= dist)
{
dist-= currentChunckProgress;
next = (byte) (next + currentChunckProgress);
currentChunckProgress = chunk;
ret[index++] = next;
}
else
{
currentChunckProgress -= dist;
currentLowerBound = it.next();
currentUpperBound = it.next();
next = currentLowerBound.getValue();
dist = currentUpperBound.compareTo(currentLowerBound)+1;
}
}
return set.split(ret);
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/rm/cmp_Ed_Ib.java | 2078 | /*
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 com.github.smeny.jpc.emulator.execution.opcodes.rm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class cmp_Ed_Ib extends Executable
{
final int op1Index;
final int immb;
public cmp_Ed_Ib(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
op1Index = Modrm.Ed(modrm);
immb = Modrm.Ib(input);
}
public Branch execute(Processor cpu)
{
Reg op1 = cpu.regs[op1Index];
cpu.flagOp1 = op1.get32();
cpu.flagOp2 = immb;
cpu.flagResult = (cpu.flagOp1 - cpu.flagOp2);
cpu.flagIns = UCodes.SUB32;
cpu.flagStatus = OSZAPC;
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
isa-group/SEDL | modules/SEDL-core/generated/es/us/isa/sedl/core/design/Domain.java | 3060 | //
// Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.11
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen.
// Generado el: 2020.07.14 a las 12:52:39 PM CEST
//
package es.us.isa.sedl.core.design;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.CopyStrategy;
import org.jvnet.jaxb2_commons.lang.CopyTo;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBCopyStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
/**
* <p>Clase Java para Domain complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType name="Domain">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Domain")
@XmlSeeAlso({
ExtensionDomain.class,
IntensionDomain.class
})
public abstract class Domain
extends AbstractDomain
implements Cloneable, CopyTo, Equals, HashCode
{
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
if (!(object instanceof Domain)) {
return false;
}
if (this == object) {
return true;
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
int currentHashCode = 1;
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
public Object clone() {
return copyTo(createNewInstance());
}
public Object copyTo(Object target) {
final CopyStrategy strategy = JAXBCopyStrategy.INSTANCE;
return copyTo(null, target, strategy);
}
public Object copyTo(ObjectLocator locator, Object target, CopyStrategy strategy) {
if (null == target) {
throw new IllegalArgumentException("Target argument must not be null for abstract copyable classes.");
}
return target;
}
}
| gpl-2.0 |
alkhwarizmix/moqawalati | source/moqawalatiWeb/src/main/java/dz/alkhwarizmix/framework/java/services/impl/UserService.java | 16938 | ////////////////////////////////////////////////////////////////////////////////
// بسم الله الرحمن الرحيم
//
// حقوق التأليف والنشر ١٤٣٤ هجري، فارس بلحواس (Copyright 2013 Fares Belhaouas)
// كافة الحقوق محفوظة (All Rights Reserved)
//
// NOTICE: Fares Belhaouas permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package dz.alkhwarizmix.framework.java.services.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import dz.alkhwarizmix.framework.java.AlKhwarizmixErrorCode;
import dz.alkhwarizmix.framework.java.AlKhwarizmixException;
import dz.alkhwarizmix.framework.java.dao.IAlKhwarizmixDAO;
import dz.alkhwarizmix.framework.java.dao.IUserDAO;
import dz.alkhwarizmix.framework.java.domain.AbstractAlKhwarizmixDomainObject;
import dz.alkhwarizmix.framework.java.dtos.domain.model.vo.AlKhwarizmixDomainObject;
import dz.alkhwarizmix.framework.java.dtos.email.model.vo.EMail;
import dz.alkhwarizmix.framework.java.dtos.security.model.vo.Password;
import dz.alkhwarizmix.framework.java.dtos.security.model.vo.User;
import dz.alkhwarizmix.framework.java.security.ISecurityManager;
import dz.alkhwarizmix.framework.java.services.IAlKhwarizmixServiceValidator;
import dz.alkhwarizmix.framework.java.services.IEMailService;
import dz.alkhwarizmix.framework.java.services.IUserService;
import dz.alkhwarizmix.framework.java.services.IUserServiceValidator;
import dz.alkhwarizmix.framework.java.utils.DateUtil;
/**
* <p>
* TODO: Javadoc
* </p>
*
* @author فارس بلحواس (Fares Belhaouas)
* @since ٢٨ ذو الحجة ١٤٣٤ (November 01, 2013)
*/
@Service
@Transactional(readOnly = true)
public class UserService extends AbstractAlKhwarizmixService implements
IUserService {
// --------------------------------------------------------------------------
//
// Constructors
//
// --------------------------------------------------------------------------
public UserService() {
super();
}
protected UserService(final Logger theLogger) {
this();
logger = theLogger;
}
// --------------------------------------------------------------------------
//
// Logger
//
// --------------------------------------------------------------------------
private static Logger logger = null;
@Override
protected final Logger getLogger() {
if (logger == null)
logger = LoggerFactory.getLogger(UserService.class);
return logger;
}
// --------------------------------------------------------------------------
//
// Properties
//
// --------------------------------------------------------------------------
@Autowired
private IUserDAO userDAO;
@Autowired
private IUserServiceValidator userServiceValidator;
@Autowired
private IEMailService emailService;
@Autowired
private Jaxb2Marshaller jaxb2Marshaller;
@Autowired
private ISecurityManager securityManager;
// --------------------------------------------------------------------------
//
// Methods
//
// --------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Transactional(readOnly = false)
@Override
public User addUser(final User user, final boolean validateObjectToPublish)
throws AlKhwarizmixException {
getLogger().trace("addUser");
final User result = (User) addObject(user, validateObjectToPublish);
return result;
}
/**
* {@inheritDoc}
*/
@Transactional(readOnly = false)
@Override
public String addUserFromXML(final String userXml)
throws AlKhwarizmixException {
getLogger().trace("addUserFromXML");
final User newUser = (User) unmarshalObjectFromXML(userXml);
final User addedUser = addUser(newUser, true);
final String result = marshalObjectToXML(addedUser);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public AbstractAlKhwarizmixDomainObject getObject(
final AbstractAlKhwarizmixDomainObject object,
final boolean validateObjectToPublish) throws AlKhwarizmixException {
getLogger().trace("getObject");
User result = getUserDAO().getUser((User) object);
if (validateObjectToPublish && (result != null)) {
result = (User) result.clone();
getServiceValidator().validateObjectToPublish(result,
getSessionOwner());
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public User getUser(final User user, final boolean validateObjectToPublish)
throws AlKhwarizmixException {
getLogger().trace("getUser");
final User result = (User) getObject(user, validateObjectToPublish);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String getUserAsXML(final User user) throws AlKhwarizmixException {
getLogger().trace("getUserAsXML 1");
final String result = getObjectAsXML(user);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String getUserAsXML(final String userXml)
throws AlKhwarizmixException {
getLogger().trace("getUserAsXML 2");
final String result = getObjectAsXML(userXml);
return result;
}
/**
* {@inheritDoc}
*/
@Transactional(readOnly = false)
@Override
public User updateUser(final User user,
final boolean validateObjectToPublish) throws AlKhwarizmixException {
getLogger().trace("updateUser");
final User result = (User) updateObject(user, getSessionOwner(),
validateObjectToPublish);
return result;
}
/**
* {@inheritDoc}
*/
@Transactional(readOnly = false)
@Override
public String updateUserFromXML(final String userXml)
throws AlKhwarizmixException {
getLogger().trace("updateUserFromXML");
final User newUser = (User) unmarshalObjectFromXML(userXml);
final User updatedUser = updateUser(newUser, true);
final String result = marshalObjectToXML(updatedUser);
return result;
}
/**
* TODO: JAVADOC
*/
@SuppressWarnings("unchecked")
public List<User> getUserList(DetachedCriteria criteriaToUse,
final int firstResult, final int maxResult)
throws AlKhwarizmixException {
getLogger().trace("getUserList");
if (criteriaToUse == null) {
criteriaToUse = DetachedCriteria.forClass(User.class);
criteriaToUse.addOrder(Order.asc(User.USERID));
}
final List<User> result = (List<User>) (List<?>) getObjectList(
criteriaToUse, firstResult, maxResult, true);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String getUserListAsXML(final DetachedCriteria criteria,
final int firstResult, final int maxResult)
throws AlKhwarizmixException {
getLogger().trace("getUserListAsXML");
final String result = userListToXML(getUserList(criteria, firstResult,
maxResult));
return result;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public String userListToXML(final List<User> userList)
throws AlKhwarizmixException {
getLogger().trace("userListToXML");
String result = "<Users>";
result += objectListToXML((List<AbstractAlKhwarizmixDomainObject>) (List<?>) userList);
result += "</Users>";
getLogger().trace("userListToXML(): returns {}", result);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public User connect(final User user, final boolean validateObjectToPublish)
throws AlKhwarizmixException {
getLogger().trace("connect");
if (getSessionData().getConnectedUser() != null)
throw getErrorLoginException("connect1.");
validateUserAndUserId(user, getErrorLoginException("connect2."));
User result = new User(user.getUserId());
final User existingUser = getUser(user, false);
if (existingUser != null)
result.setName(existingUser.getName());
getSessionData().setConnectedUser(existingUser != null
? existingUser
: result);
if (validateObjectToPublish && (result != null)) {
result = (User) result.clone();
getUserServiceValidator().validateObjectToPublish(result,
getSessionOwner());
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public String connectFromXML(final String userXml)
throws AlKhwarizmixException {
getLogger().trace("connectFromXML");
final User userToConnect = (User) unmarshalObjectFromXML(userXml);
final User connectedUser = connect(userToConnect, true);
final String result = marshalObjectToXML(connectedUser);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public User login(final User user, final String password,
final boolean validateObjectToPublish) throws AlKhwarizmixException {
getLogger().trace("login");
try {
validateUserAndUserId(user, getErrorLoginException("login1."));
validateUserIsNotLogged(user, getErrorLoginException("login2."));
validateUserIsConnected(user, getErrorLoginException("login3."));
final User userToLogin = getUser(user, false);
if (userToLogin != null)
validateUserPassword(user, password,
getErrorLoginException("login4."));
else
throw getErrorLoginException("login5.");
getSessionData().setLoggedUser(userToLogin);
getSessionData().setSessionOwner(userToLogin.getDomainObject());
User result = userToLogin;
if (validateObjectToPublish && (result != null)) {
result = (User) result.clone();
getUserServiceValidator().validateObjectToPublish(result,
getSessionOwner());
}
return result;
} catch (final AlKhwarizmixException e) {
getSecurityManager().validateRemoteAddrRestrictionForWrongLogin();
throw e;
}
}
/**
* {@inheritDoc}
*/
@Override
public String loginFromXML(final String userXml, final String password)
throws AlKhwarizmixException {
getLogger().trace("loginFromXML");
final User userToLogin = (User) unmarshalObjectFromXML(userXml);
final User loggedUser = login(userToLogin, password, true);
final String result = marshalObjectToXML(loggedUser);
return result;
}
/**
* {@inheritDoc}
*/
@Transactional(readOnly = false)
@Override
public User subscribe(final User user, final boolean validateObjectToPublish)
throws AlKhwarizmixException {
getLogger().trace("subscribe");
validateUserAndUserId(user, getErrorLoginException("subscribe1."));
validateUserIsNotLogged(user, getErrorLoginException("subscribe2."));
validateUserIsConnected(user, getErrorLoginException("subscribe3."));
validateRemoteAddrRestriction(getErrorLoginException("subscribe4-1."));
User subscribedUser = getUser(user, false);
if (subscribedUser != null)
throw getErrorLoginException("subscribe5-1.");
subscribedUser = addUser(user, false);
Password generatedPassword = new Password(subscribedUser);
generatedPassword.setPassword("Mohamed"
+ new DateUtil().newDate().getTime());
generatedPassword = (Password) addObject(generatedPassword, false);
getSessionData().setLoggedUser(subscribedUser);
getSessionData().setSessionOwner(subscribedUser.getDomainObject());
sendEmailToAddedUser(subscribedUser, generatedPassword);
if (validateObjectToPublish && (subscribedUser != null)) {
subscribedUser = (User) subscribedUser.clone();
getUserServiceValidator().validateObjectToPublish(subscribedUser,
getSessionOwner());
}
return subscribedUser;
}
/**
* {@inheritDoc}
*/
@Transactional(readOnly = false)
@Override
public String subscribeFromXML(final String userXml)
throws AlKhwarizmixException {
getLogger().trace("subscribeFromXML");
final User userToSubscribe = (User) unmarshalObjectFromXML(userXml);
final User loggedUser = subscribe(userToSubscribe, true);
final String result = marshalObjectToXML(loggedUser);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public void logout(final User user) throws AlKhwarizmixException {
getLogger().trace("logout");
// final User loggedUser = getUser(user, false);
// if (loggedUser == null)
// throw new AlKhwarizmixException(AlKhwarizmixErrorCode.ERROR_LOGIN);
getSessionData().resetLoggedUser();
getSessionData().resetConnectedUser();
getSessionData().resetSessionOwner();
}
/**
* {@inheritDoc}
*/
@Override
public void logoutFromXML(final String userXml)
throws AlKhwarizmixException {
getLogger().trace("logoutFromXML");
final User userToLogout = (User) unmarshalObjectFromXML(userXml);
logout(userToLogout);
}
/**
*/
private AlKhwarizmixException getErrorLoginException(final String message) {
return new AlKhwarizmixException(message,
AlKhwarizmixErrorCode.ERROR_LOGIN);
}
/**
*/
private void validateUserAndUserId(final User user,
final AlKhwarizmixException exception) throws AlKhwarizmixException {
if (user == null)
throw exception;
if (!getUserServiceValidator().isValidUserId(user))
throw exception;
}
/**
*/
private void validateRemoteAddrRestriction(
final AlKhwarizmixException exception) throws AlKhwarizmixException {
if (!getSecurityManager()
.validateRemoteAddrRestrictionForSubscription())
throw exception;
}
/**
*/
private void validateUserIsNotLogged(final User user,
final AlKhwarizmixException exception) throws AlKhwarizmixException {
if (getSessionData().getLoggedUser() != null)
throw exception;
}
/**
*/
private void validateUserIsConnected(final User user,
final AlKhwarizmixException exception) throws AlKhwarizmixException {
if (getSessionData().getConnectedUser() == null)
throw exception;
if (!user.getUserId().equals(
getSessionData().getConnectedUser().getUserId()))
throw exception;
}
/**
*/
private Password validateUserPassword(final User user,
final String password, final AlKhwarizmixException exception)
throws AlKhwarizmixException {
if (validateUserPasswordForJMeter(user, password))
return null;
for (final Password result : getUserDAO().getUserPasswords(user))
if (result.getPassword().equals(password))
return result;
throw exception;
}
/**
*/
protected boolean validateUserPasswordForJMeter(final User user,
final String password) throws AlKhwarizmixException {
boolean result = false;
if (user.isJMeterTestUser() && ("Mohamed".equals(password)))
result = true;
return result;
}
/**
*/
private void sendEmailToAddedUser(final User user, final Password password)
throws AlKhwarizmixException {
final User infoUser = getUser(new User("fares@dz.moqawalati.com"),
false);
final EMail email = new EMail();
email.setSender(infoUser);
email.setReceiver(user);
email.setBody("Dear " + user.getName()
+ ", thank you for your subscription. Your password is "
+ password.getPassword());
getEmailService().addEMail(email, false);
}
/**
* {@inheritDoc}
*/
@Override
protected final AlKhwarizmixDomainObject getSessionOwner() {
final AlKhwarizmixDomainObject result = new AlKhwarizmixDomainObject();
result.setId(-1L);
return result;
}
// --------------------------------------------------------------------------
//
// Getters & Setters
//
// --------------------------------------------------------------------------
// ----------------------------------
// emailService
// ----------------------------------
protected final void setEmailService(final IEMailService value) {
emailService = value;
}
protected final IEMailService getEmailService() {
return emailService;
}
// ----------------------------------
// userDAO
// ----------------------------------
private final IUserDAO getUserDAO() {
return userDAO;
}
protected final void setUserDAO(final IUserDAO value) {
userDAO = value;
}
@Override
protected final IAlKhwarizmixDAO getServiceDAO() {
return userDAO;
}
// ----------------------------------
// userServiceValidator
// ----------------------------------
protected final void setUserServiceValidator(
final IUserServiceValidator value) {
userServiceValidator = value;
}
protected final IUserServiceValidator getUserServiceValidator() {
return userServiceValidator;
}
@Override
protected final IAlKhwarizmixServiceValidator getServiceValidator() {
return userServiceValidator;
}
// ----------------------------------
// jaxb2Marshaller
// ----------------------------------
@Override
protected Jaxb2Marshaller getJaxb2Marshaller() {
return jaxb2Marshaller;
}
@Override
protected void setJaxb2Marshaller(final Jaxb2Marshaller value) {
jaxb2Marshaller = value;
}
// ----------------------------------
// securityManager
// ----------------------------------
private ISecurityManager getSecurityManager() {
return securityManager;
}
protected final void setSecurityManager(final ISecurityManager value) {
securityManager = value;
}
} // Class
| gpl-2.0 |
carvalhomb/tsmells | guess/guess-src/org/python/core/PyLong.java | 12944 | // Copyright (c) Corporation for National Research Initiatives
package org.python.core;
import java.math.BigInteger;
import java.io.Serializable;
/**
* A builtin python long. This is implemented as a
* java.math.BigInteger.
*/
public class PyLong extends PyObject
{
private static final BigInteger minLong =
BigInteger.valueOf(Long.MIN_VALUE);
private static final BigInteger maxLong =
BigInteger.valueOf(Long.MAX_VALUE);
private static final BigInteger minDouble =
new java.math.BigDecimal(Double.MIN_VALUE).toBigInteger();
private static final BigInteger maxDouble =
new java.math.BigDecimal(Double.MAX_VALUE).toBigInteger();
private java.math.BigInteger value;
public PyLong(java.math.BigInteger v) {
value = v;
}
public PyLong(double v) {
this(new java.math.BigDecimal(v).toBigInteger());
}
public PyLong(long v) {
this(java.math.BigInteger.valueOf(v));
}
public PyLong(String s) {
this(new java.math.BigInteger(s));
}
public String toString() {
return value.toString()+"L";
}
public int hashCode() {
// Probably won't work well for some classes of keys...
return value.intValue();
}
public boolean __nonzero__() {
return !value.equals(java.math.BigInteger.valueOf(0));
}
public double doubleValue() {
double v = value.doubleValue();
if (v == Double.NEGATIVE_INFINITY || v == Double.POSITIVE_INFINITY) {
throw Py.OverflowError("long int too long to convert");
}
return v;
}
private long getLong(long min, long max) {
if (value.compareTo(maxLong) <= 0 && value.compareTo(minLong) >= 0) {
long v = value.longValue();
if (v >= min && v <= max)
return v;
}
throw Py.OverflowError("long int too long to convert");
}
public Object __tojava__(Class c) {
try {
if (c == Byte.TYPE || c == Byte.class) {
return new Byte((byte)getLong(Byte.MIN_VALUE,
Byte.MAX_VALUE));
}
if (c == Short.TYPE || c == Short.class) {
return new Short((short)getLong(Short.MIN_VALUE,
Short.MAX_VALUE));
}
if (c == Integer.TYPE || c == Integer.class) {
return new Integer((int)getLong(Integer.MIN_VALUE,
Integer.MAX_VALUE));
}
if (c == Long.TYPE || c == Long.class) {
return new Long(getLong(Long.MIN_VALUE,
Long.MAX_VALUE));
}
if (c == Float.TYPE || c == Double.TYPE || c == Float.class ||
c == Double.class)
{
return __float__().__tojava__(c);
}
if (c == BigInteger.class || c == Number.class ||
c == Object.class || c == Serializable.class)
{
return value;
}
} catch (PyException e) {
return Py.NoConversion;
}
return super.__tojava__(c);
}
public int __cmp__(PyObject other) {
return value.compareTo(((PyLong)other).value);
}
public Object __coerce_ex__(PyObject other) {
if (other instanceof PyLong)
return other;
else
if (other instanceof PyInteger) {
return new PyLong(((PyInteger)other).getValue());
} else {
return Py.None;
}
}
private static final boolean canCoerce(PyObject other) {
return other instanceof PyLong || other instanceof PyInteger;
}
private static final BigInteger coerce(PyObject other) {
if (other instanceof PyLong)
return ((PyLong) other).value;
else if (other instanceof PyInteger)
return java.math.BigInteger.valueOf(
((PyInteger) other).getValue());
else
throw Py.TypeError("xxx");
}
public PyObject __add__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(value.add(coerce(right)));
}
public PyObject __radd__(PyObject left) {
return __add__(left);
}
public PyObject __sub__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(value.subtract(coerce(right)));
}
public PyObject __rsub__(PyObject left) {
return new PyLong(coerce(left).subtract(value));
}
public PyObject __mul__(PyObject right) {
if (right instanceof PySequence)
return ((PySequence) right).repeat(coerceInt(this));
if (!canCoerce(right))
return null;
return new PyLong(value.multiply(coerce(right)));
}
public PyObject __rmul__(PyObject left) {
if (left instanceof PySequence)
return ((PySequence) left).repeat(coerceInt(this));
if (!canCoerce(left))
return null;
return new PyLong(coerce(left).multiply(value));
}
// Getting signs correct for integer division
// This convention makes sense when you consider it in tandem with modulo
private BigInteger divide(BigInteger x, BigInteger y) {
BigInteger zero = java.math.BigInteger.valueOf(0);
if (y.equals(zero))
throw Py.ZeroDivisionError("long division or modulo");
if (y.compareTo(zero) < 0) {
if (x.compareTo(zero) > 0)
return (x.subtract(y).subtract(
BigInteger.valueOf(1))).divide(y);
} else {
if (x.compareTo(zero) < 0)
return (x.subtract(y).add(BigInteger.valueOf(1))).divide(y);
}
return x.divide(y);
}
public PyObject __div__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(divide(value, coerce(right)));
}
public PyObject __rdiv__(PyObject left) {
if (!canCoerce(left))
return null;
return new PyLong(divide(coerce(left), value));
}
private BigInteger modulo(BigInteger x, BigInteger y, BigInteger xdivy) {
return x.subtract(xdivy.multiply(y));
}
public PyObject __mod__(PyObject right) {
if (!canCoerce(right))
return null;
BigInteger rightv = coerce(right);
return new PyLong(modulo(value, rightv, divide(value, rightv)));
}
public PyObject __rmod__(PyObject left) {
if (!canCoerce(left))
return null;
BigInteger leftv = coerce(left);
return new PyLong(modulo(leftv, value, divide(leftv, value)));
}
public PyObject __divmod__(PyObject right) {
if (!canCoerce(right))
return null;
BigInteger rightv = coerce(right);
BigInteger xdivy = divide(value, rightv);
return new PyTuple(new PyObject[] {
new PyLong(xdivy),
new PyLong(modulo(value, rightv, xdivy))
});
}
public PyObject __rdivmod__(PyObject left) {
if (!canCoerce(left))
return null;
BigInteger leftv = coerce(left);
BigInteger xdivy = divide(leftv, value);
return new PyTuple(new PyObject[] {
new PyLong(xdivy),
new PyLong(modulo(leftv, value, xdivy))
});
}
public PyObject __pow__(PyObject right, PyObject modulo) {
if (!canCoerce(right))
return null;
if (modulo != null && !canCoerce(right))
return null;
return _pow(value, coerce(right), modulo);
}
public PyObject __rpow__(PyObject left) {
if (!canCoerce(left))
return null;
return _pow(coerce(left), value, null);
}
public static PyLong _pow(BigInteger value, BigInteger y,
PyObject modulo)
{
if (y.compareTo(BigInteger.valueOf(0)) < 0) {
if (value.compareTo(BigInteger.valueOf(0)) != 0)
throw Py.ValueError("long integer to a negative power");
else
throw Py.ZeroDivisionError("zero to a negative power");
}
if (modulo == null)
return new PyLong(value.pow(y.intValue()));
else {
// This whole thing can be trivially rewritten after bugs
// in modPow are fixed by SUN
BigInteger z = coerce(modulo);
int zi = z.intValue();
// Clear up some special cases right away
if (zi == 0)
throw Py.ValueError("pow(x, y, z) with z == 0");
if (zi == 1 || zi == -1)
return new PyLong(0);
if (z.compareTo(BigInteger.valueOf(0)) <= 0) {
// Handle negative modulo's specially
/*if (z.compareTo(BigInteger.valueOf(0)) == 0) {
throw Py.ValueError("pow(x, y, z) with z == 0");
}*/
y = value.modPow(y, z.negate());
if (y.compareTo(BigInteger.valueOf(0)) > 0) {
return new PyLong(z.add(y));
} else {
return new PyLong(y);
}
//return __pow__(right).__mod__(modulo);
} else {
// This is buggy in SUN's jdk1.1.5
// Extra __mod__ improves things slightly
return new PyLong(value.modPow(y, z));
//return __pow__(right).__mod__(modulo);
}
}
}
private static final int coerceInt(PyObject other) {
if (other instanceof PyLong)
return (int) ((PyLong) other).getLong(
Integer.MIN_VALUE, Integer.MAX_VALUE);
else if (other instanceof PyInteger)
return ((PyInteger) other).getValue();
else
throw Py.TypeError("xxx");
}
public PyObject __lshift__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(value.shiftLeft(coerceInt(right)));
}
public PyObject __rshift__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(value.shiftRight(coerceInt(right)));
}
public PyObject __and__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(value.and(coerce(right)));
}
public PyObject __xor__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(value.xor(coerce(right)));
}
public PyObject __or__(PyObject right) {
if (!canCoerce(right))
return null;
return new PyLong(value.or(coerce(right)));
}
public PyObject __neg__() {
return new PyLong(value.negate());
}
public PyObject __pos__() {
return this;
}
public PyObject __abs__() {
return new PyLong(value.abs());
}
public PyObject __invert__() {
return new PyLong(value.not());
}
public PyInteger __int__() {
return new PyInteger((int)getLong(Integer.MIN_VALUE,
Integer.MAX_VALUE));
}
public PyLong __long__() {
return this;
}
public PyFloat __float__() {
return new PyFloat(doubleValue());
}
public PyComplex __complex__() {
return new PyComplex(doubleValue(), 0.);
}
public PyString __oct__() {
String s = value.toString(8);
if (s.startsWith("-"))
return new PyString("-0"+s.substring(1, s.length())+"L");
else
if (s.startsWith("0"))
return new PyString(s+"L");
else
return new PyString("0"+s+"L");
}
public PyString __hex__() {
String s = value.toString(16).toUpperCase();
if (s.startsWith("-"))
return new PyString("-0x"+s.substring(1, s.length())+"L");
else
return new PyString("0x"+s+"L");
}
public PyString __str__() {
return Py.newString(value.toString());
}
public boolean isMappingType() { return false; }
public boolean isSequenceType() { return false; }
// __class__ boilerplate -- see PyObject for details
public static PyClass __class__;
protected PyClass getPyClass() {
return __class__;
}
}
| gpl-2.0 |
Malkuthe/BattleClasses | battleclassmod/guis/BCMGuiHandler.java | 993 | package battleclassmod.guis;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import battleclassmod.BattleClassMod;
import battleclassmod.PlayerClass;
import battleclassmod.inventories.containers.BCMInterfaceContainer;
import cpw.mods.fml.common.network.IGuiHandler;
public class BCMGuiHandler implements IGuiHandler {
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world,
int x, int y, int z) {
if (ID == BattleClassMod.GUI_CLASS_INTERFACE_INV){
return new BCMInterfaceContainer(player, player.inventory, PlayerClass.get(player).inventory);
} else {
return null;
}
}
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world,
int x, int y, int z) {
if (ID == BattleClassMod.GUI_CLASS_INTERFACE_INV){
return new BCMInterfaceInventoryGui(player, player.inventory, PlayerClass.get(player).inventory);
} else {
return null;
}
}
}
| gpl-2.0 |
DIY-green/AndroidStudyDemo | MVPFrameStudy/src/main/java/com/cheng/mvpframestudy/diymvp/presenter/impl/WeatherPresenterImpl.java | 1273 | package com.cheng.mvpframestudy.diymvp.presenter.impl;
import com.cheng.mvpframestudy.diymvp.model.bean.WeatherBean;
import com.cheng.mvpframestudy.diymvp.model.i.IWeatherModel;
import com.cheng.mvpframestudy.diymvp.model.impl.WeatherModelImpl;
import com.cheng.mvpframestudy.diymvp.presenter.i.OnWeatherListener;
import com.cheng.mvpframestudy.diymvp.presenter.i.IWeatherPresenter;
import com.cheng.mvpframestudy.diymvp.ui.i.IWeatherView;
/**
* 天气 Prestener实现
*/
public class WeatherPresenterImpl implements IWeatherPresenter, OnWeatherListener {
/*Presenter作为中间层,持有View和Model的引用*/
private IWeatherView weatherView;
private IWeatherModel weatherModel;
public WeatherPresenterImpl(IWeatherView weatherView) {
this.weatherView = weatherView;
weatherModel = new WeatherModelImpl();
}
@Override
public void getWeather(String cityNO) {
weatherView.showLoading();
weatherModel.loadWeather(cityNO, this);
}
@Override
public void onSuccess(WeatherBean weather) {
weatherView.hideLoading();
weatherView.setWeatherInfo(weather);
}
@Override
public void onError() {
weatherView.hideLoading();
weatherView.showError();
}
}
| gpl-2.0 |
RJSDevel/CV-Collector | src/main/java/com/github/rjsdevel/cvcollector/io/model/Job.java | 2548 | package com.github.rjsdevel.cvcollector.io.model;
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
/**
* Created by Руслик on 04.05.15.
* Класс хранитель работ соискателя
*/
@Entity
@Table( name = "job" )
public class Job {
private Long id;
// Город
private City city;
// Должность
private Position position;
private String sPosition;
// Компания
private Company company;
private String sCompany;
// Продолжительность работы
private CVDate date;
// Описание деятельности
private String description;
// В данный монет работает в компании
private Boolean isStillWorking;
public Job() {
}
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToOne( cascade = CascadeType.ALL, fetch = FetchType.EAGER )
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
@OneToOne( cascade = CascadeType.ALL, fetch = FetchType.EAGER )
public Position getPosition() {
return position;
}
public void setPosition(Position position) {
this.position = position;
}
public String getsPosition() {
return sPosition;
}
public void setsPosition(String sPosition) {
this.sPosition = sPosition;
}
@OneToOne( cascade = CascadeType.ALL, fetch = FetchType.EAGER )
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public String getsCompany() {
return sCompany;
}
public void setsCompany(String sCompany) {
this.sCompany = sCompany;
}
@OneToOne( cascade = CascadeType.ALL, fetch = FetchType.EAGER )
public CVDate getDate() {
return date;
}
public void setDate(CVDate date) {
this.date = date;
}
@Column( length = 4096 )
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getIsStillWorking() {
return isStillWorking;
}
public void setIsStillWorking(Boolean isStillWorking) {
this.isStillWorking = isStillWorking;
}
}
| gpl-2.0 |
KazeEspada/IRCBot | com/iarekylew00t/managers/FileManager.java | 8374 | package com.iarekylew00t.managers;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import com.iarekylew00t.helpers.Downloader;
import com.iarekylew00t.helpers.FileHelper;
import com.iarekylew00t.ircbot.handlers.LogHandler;
public enum FileManager {
INSTANCE;
private static String endFile = "-quotes.txt";
private static String FILE_BASE = "https://raw.github.com/IAreKyleW00t/IRCBot/master/files/";
private static File _ROOT = new File("./files/");
private static File _QUOTE = new File("./files/quotes/");
private static File HS_LINKS = new File("./files/hs_links.txt");
private static File[] quotes = {
new File("./files/quotes/aradia" + endFile),
new File("./files/quotes/aranea" + endFile),
new File("./files/quotes/arquiusprite" + endFile),
new File("./files/quotes/caliborn" + endFile),
new File("./files/quotes/calliope" + endFile),
new File("./files/quotes/calsprite" + endFile),
new File("./files/quotes/cronus" + endFile),
new File("./files/quotes/damara" + endFile),
new File("./files/quotes/dave" + endFile),
new File("./files/quotes/davesprite" + endFile),
new File("./files/quotes/dirk" + endFile),
new File("./files/quotes/doc" + endFile),
new File("./files/quotes/dragonsprite" + endFile),
new File("./files/quotes/equius" + endFile),
new File("./files/quotes/eridan" + endFile),
new File("./files/quotes/erisolsprite" + endFile),
new File("./files/quotes/feferi" + endFile),
new File("./files/quotes/fefetasprite" + endFile),
new File("./files/quotes/gamzee" + endFile),
new File("./files/quotes/hic" + endFile),
new File("./files/quotes/horuss" + endFile),
new File("./files/quotes/hussie" + endFile),
new File("./files/quotes/jade" + endFile),
new File("./files/quotes/jadesprite" + endFile),
new File("./files/quotes/jake" + endFile),
new File("./files/quotes/jane" + endFile),
new File("./files/quotes/jaspersprite" + endFile),
new File("./files/quotes/john" + endFile),
new File("./files/quotes/kanaya" + endFile),
new File("./files/quotes/kankri" + endFile),
new File("./files/quotes/karkat" + endFile),
new File("./files/quotes/kurloz" + endFile),
new File("./files/quotes/latula" + endFile),
new File("./files/quotes/meenah" + endFile),
new File("./files/quotes/meulin" + endFile),
new File("./files/quotes/mituna" + endFile),
new File("./files/quotes/nannasprite" + endFile),
new File("./files/quotes/nepeta" + endFile),
new File("./files/quotes/porrim" + endFile),
new File("./files/quotes/rose" + endFile),
new File("./files/quotes/roxy" + endFile),
new File("./files/quotes/rufioh" + endFile),
new File("./files/quotes/sollux" + endFile),
new File("./files/quotes/squarewave" + endFile),
new File("./files/quotes/tavrisprite" + endFile),
new File("./files/quotes/tavros" + endFile),
new File("./files/quotes/terezi" + endFile),
new File("./files/quotes/vriska" + endFile)};
private static LogHandler logger = DataManager.logHandler;
public static void checkFiles() throws MalformedURLException {
if (!_QUOTE.exists()) {
_QUOTE.mkdirs();
}
if (!_ROOT.exists()) {
_ROOT.mkdirs();
}
if (!HS_LINKS.exists()) {
Downloader.downloadFile(new URL(FILE_BASE + HS_LINKS.getName()), HS_LINKS);
}
for (File file : quotes) {
if(!file.exists()) {
Downloader.downloadFile(new URL(FILE_BASE + "/quotes/" + file.getName()), file);
}
}
}
public static void updateConfig() {
FileHelper.writeToFile(DataManager.CONFIG, "#======================================================\r\n" +
"#=== Configuration File for Aradiabot (Rev. 1.1D) ===\r\n" +
"#======================================================\r\n", false);
FileHelper.writeToFile(DataManager.CONFIG, "#The Nickname for your bot\r\n" +
"Nick = " + DataManager.nick + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Your NickServ Password\r\n" +
"#LEAVE BLANK FOR NO PASSWORD\r\n" +
"Password = " + DataManager.nickPassword + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Your Login Name\r\n" +
"Login = " + DataManager.login + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Server to connect to\r\n" +
"Server = " + DataManager.server + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Channel(s) to connect to\r\n" +
"Channel = " + DataManager.channel + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#The Email Address to use for the Email Client\r\n" +
"#LEAVE BLANK TO NOT USE THE EMAIL CLIENT\r\n" +
"Email = " + DataManager.emailAddress + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#The Email Password for the Email Client\r\n" +
"#LEAVE BLANK TO NOT USE THE EMAIL CLIENT\r\n" +
"EmailPassword = " + DataManager.emailPassword + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Enable or Disable Debugging\r\n" +
"#Default: true\r\n" +
"Debug = " + DataManager.debug + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Enable to disable Password Encryption\r\n" +
"#Default: false\r\n" +
"#NOTE: This will encrypt your NickServ and Email Address password (regardless if they're blank or not).\r\n" +
"#It will still encrypt the blank space. DON'T TOUCH IT. It won't activate anything since it'll still\r\n" +
"#decrypt to an empty space like before.\r\n" +
"Encrypt = " + DataManager.encrypt + "\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Securely Generated Salt\r\n" +
"#NOTE: This is generated the first time you run the bot\r\n" +
"#DO NOT CHANGE THIS UNLESS YOU KNOW WHAT YOU'RE DOING (Min. 24 characters)\r\n" +
"Salt = " + DataManager.salt, true);
}
public static void createDefaultConfig() {
logger.notice("NO DataManager.CONFIGURATION FOUND - CREATING DEFAULT");
FileHelper.writeToFile(DataManager.CONFIG, "#======================================================\r\n" +
"#=== Configuration File for Aradiabot (Rev. 1.1D) ===\r\n" +
"#======================================================\r\n", false);
FileHelper.writeToFile(DataManager.CONFIG, "#The Nickname for your bot\r\n" +
"Nick = Aradiabot\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Your NickServ Password\r\n" +
"#LEAVE BLANK FOR NO PASSWORD\r\n" +
"Password =\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Your Login Name\r\n" +
"Login = AA\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Server to connect to\r\n" +
"Server = irc.esper.net\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Channel(s) to connect to\r\n" +
"Channel = #channel1,#channel2,#channel3\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#The Email Address to use for the Email Client\r\n" +
"#LEAVE BLANK TO NOT USE THE EMAIL CLIENT\r\n" +
"Email =\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#The Email Password for the Email Client\r\n" +
"#LEAVE BLANK TO NOT USE THE EMAIL CLIENT\r\n" +
"EmailPassword =\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Enable or Disable Debugging\r\n" +
"#Default: false\r\n" +
"Debug = false\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Enable to disable Password Encryption\r\n" +
"#Default: false\r\n" +
"#NOTE: This will encrypt your NickServ and Email Address password (regardless if they're blank or not).\r\n" +
"#It will still encrypt the blank space. DON'T TOUCH IT. It won't activate anything since it'll still\r\n" +
"#decrypt to an empty space like before.\r\n" +
"Encrypt = false\r\n", true);
FileHelper.writeToFile(DataManager.CONFIG, "#Securely Generated Salt\r\n" +
"#NOTE: This is generated the first time you run the bot\r\n" +
"#DO NOT CHANGE THIS UNLESS YOU KNOW WHAT YOU'RE DOING\r\n" +
"Salt =",true);
}
}
| gpl-2.0 |
Jason918/SkySpace | JavaSky/src/main/java/com/skyspace/restfulsky/Application.java | 394 | package com.skyspace.restfulsky;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
} | gpl-2.0 |
wirthandrel/sadaapp | sadaapp/src/main/java/br/com/andre/sada/stub/ManejosCallbackHandler.java | 7408 |
/**
* ManejosCallbackHandler.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.6.1-wso2v6 Built on : Sep 11, 2012 (04:36:42 PDT)
*/
package br.com.andre.sada.stub;
/**
* ManejosCallbackHandler Callback class, Users can extend this class and implement
* their own receiveResult and receiveError methods.
*/
public abstract class ManejosCallbackHandler{
protected Object clientData;
/**
* User can pass in any object that needs to be accessed once the NonBlocking
* Web service call is finished and appropriate method of this CallBack is called.
* @param clientData Object mechanism by which the user can pass in user data
* that will be avilable at the time this callback is called.
*/
public ManejosCallbackHandler(Object clientData){
this.clientData = clientData;
}
/**
* Please use this constructor if you don't want to set any clientData
*/
public ManejosCallbackHandler(){
this.clientData = null;
}
/**
* Get the client data
*/
public Object getClientData() {
return clientData;
}
/**
* auto generated Axis2 call back method for ehprimeiroManejo method
* override this method for handling normal response from ehprimeiroManejo operation
*/
public void receiveResultehprimeiroManejo(
br.com.andre.sada.stub.ManejosStub.AcompanhamentosSemClasseE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from ehprimeiroManejo operation
*/
public void receiveErrorehprimeiroManejo(java.lang.Exception e) {
}
// No methods generated for meps other than in-out
/**
* auto generated Axis2 call back method for getAcompanhamentoSemManejo method
* override this method for handling normal response from getAcompanhamentoSemManejo operation
*/
public void receiveResultgetAcompanhamentoSemManejo(
br.com.andre.sada.stub.ManejosStub.EntriesNotClassE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from getAcompanhamentoSemManejo operation
*/
public void receiveErrorgetAcompanhamentoSemManejo(java.lang.Exception e) {
}
/**
* auto generated Axis2 call back method for manejosInfo method
* override this method for handling normal response from manejosInfo operation
*/
public void receiveResultmanejosInfo(
br.com.andre.sada.stub.ManejosStub.AcompsInfoE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from manejosInfo operation
*/
public void receiveErrormanejosInfo(java.lang.Exception e) {
}
/**
* auto generated Axis2 call back method for getVML method
* override this method for handling normal response from getVML operation
*/
public void receiveResultgetVML(
br.com.andre.sada.stub.ManejosStub.ResE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from getVML operation
*/
public void receiveErrorgetVML(java.lang.Exception e) {
}
/**
* auto generated Axis2 call back method for insereManejoOp method
* override this method for handling normal response from insereManejoOp operation
*/
public void receiveResultinsereManejoOp(
br.com.andre.sada.stub.ManejosStub.GeneratedKeysE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from insereManejoOp operation
*/
public void receiveErrorinsereManejoOp(java.lang.Exception e) {
}
// No methods generated for meps other than in-out
// No methods generated for meps other than in-out
/**
* auto generated Axis2 call back method for getManejoByAtributes method
* override this method for handling normal response from getManejoByAtributes operation
*/
public void receiveResultgetManejoByAtributes(
br.com.andre.sada.stub.ManejosStub.ManejosE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from getManejoByAtributes operation
*/
public void receiveErrorgetManejoByAtributes(java.lang.Exception e) {
}
// No methods generated for meps other than in-out
/**
* auto generated Axis2 call back method for getAcompanhamentoSemClasse method
* override this method for handling normal response from getAcompanhamentoSemClasse operation
*/
public void receiveResultgetAcompanhamentoSemClasse(
br.com.andre.sada.stub.ManejosStub.AcompanhamentosSemClasseE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from getAcompanhamentoSemClasse operation
*/
public void receiveErrorgetAcompanhamentoSemClasse(java.lang.Exception e) {
}
/**
* auto generated Axis2 call back method for getid method
* override this method for handling normal response from getid operation
*/
public void receiveResultgetid(
br.com.andre.sada.stub.ManejosStub.EntriesE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from getid operation
*/
public void receiveErrorgetid(java.lang.Exception e) {
}
/**
* auto generated Axis2 call back method for getManejoByID method
* override this method for handling normal response from getManejoByID operation
*/
public void receiveResultgetManejoByID(
br.com.andre.sada.stub.ManejosStub.EntriesSemManejoE result
) {
}
/**
* auto generated Axis2 Error handler
* override this method for handling error response from getManejoByID operation
*/
public void receiveErrorgetManejoByID(java.lang.Exception e) {
}
}
| gpl-2.0 |
meadicus/npc-builder | NPCBuilder/src/main/java/uk/co/meadicus/npcbuilder/client/stats/StatSum.java | 2113 | package uk.co.meadicus.npcbuilder.client.stats;
import java.util.ArrayList;
import java.util.List;
import uk.co.meadicus.npcbuilder.client.util.NPCUtils;
public class StatSum {
private static class StatSumItem {
private final int value;
private final String name;
private final boolean renderIfZero;
protected StatSumItem(int value, String name, boolean renderIfZero) {
super();
this.value = value;
this.name = name;
this.renderIfZero = renderIfZero;
}
public final int getValue() {
return value;
}
public final String getName() {
return name;
}
public final boolean isRenderIfZero() {
return renderIfZero;
}
}
private final List<StatSumItem> items = new ArrayList<StatSumItem>();
private boolean totalIsModifier = true;
public void add(int val, String name, boolean renderIfZero) {
StatSumItem item = new StatSumItem(val, name, renderIfZero);
getItems().add(item);
}
private int getTotal() {
int total = 0;
for (StatSumItem item : getItems()) {
total += item.getValue();
}
return total;
}
public String render() {
String output = "";
if (isTotalIsModifier()) {
output += NPCUtils.renderModifier(getTotal());
} else {
output += Integer.toString(getTotal());
}
String sum = "";
int sumItems = 0;
for (StatSumItem item : getItems()) {
if (item.getValue() != 0 || item.isRenderIfZero()) {
// don't put a '+' in front of the first number if positive
if (sum.isEmpty()) {
sum = Integer.toString(item.getValue());
} else {
sum += NPCUtils.renderModifier(item.getValue());
}
// if there is an item name to render
if (!(item.getName() == null || item.getName().isEmpty())) {
sum += "(" + item.getName() + ")";
}
++ sumItems;
}
}
if (sumItems > 1) {
output += "=" + sum;
}
return output;
}
private final boolean isTotalIsModifier() {
return totalIsModifier;
}
public final void setTotalIsModifier(boolean totalIsModifier) {
this.totalIsModifier = totalIsModifier;
}
private final List<StatSumItem> getItems() {
return items;
}
}
| gpl-2.0 |
MyCATApache/Mycat-Server | src/main/java/io/mycat/net/mysql/ErrorPacket.java | 4491 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. 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.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.net.mysql;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import io.mycat.backend.mysql.BufferUtil;
import io.mycat.backend.mysql.MySQLMessage;
import io.mycat.net.FrontendConnection;
/**
* From server to client in response to command, if error.
*
* <pre>
* Bytes Name
* ----- ----
* 1 field_count, always = 0xff
* 2 errno
* 1 (sqlstate marker), always '#'
* 5 sqlstate (5 characters)
* n message
*
* @see http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Error_Packet
* </pre>
*
* @author mycat
*/
public class ErrorPacket extends MySQLPacket {
public static final byte FIELD_COUNT = (byte) 0xff;
private static final byte SQLSTATE_MARKER = (byte) '#';
private static final byte[] DEFAULT_SQLSTATE = "HY000".getBytes();
public byte fieldCount = FIELD_COUNT;
public int errno;
public byte mark = SQLSTATE_MARKER;
public byte[] sqlState = DEFAULT_SQLSTATE;
public byte[] message;
public void read(BinaryPacket bin) {
packetLength = bin.packetLength;
packetId = bin.packetId;
MySQLMessage mm = new MySQLMessage(bin.data);
fieldCount = mm.read();
errno = mm.readUB2();
if (mm.hasRemaining() && (mm.read(mm.position()) == SQLSTATE_MARKER)) {
mm.read();
sqlState = mm.readBytes(5);
}
message = mm.readBytes();
}
public void read(byte[] data) {
MySQLMessage mm = new MySQLMessage(data);
packetLength = mm.readUB3();
packetId = mm.read();
fieldCount = mm.read();
errno = mm.readUB2();
if (mm.hasRemaining() && (mm.read(mm.position()) == SQLSTATE_MARKER)) {
mm.read();
sqlState = mm.readBytes(5);
}
message = mm.readBytes();
}
public byte[] writeToBytes(FrontendConnection c) {
ByteBuffer buffer = c.allocate();
buffer = write(buffer, c, false);
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
c.recycle(buffer);
return data;
}
public byte[] writeToBytes() {
ByteBuffer buffer = ByteBuffer.allocate(calcPacketSize()+4);
int size = calcPacketSize();
BufferUtil.writeUB3(buffer, size);
buffer.put(packetId);
buffer.put(fieldCount);
BufferUtil.writeUB2(buffer, errno);
buffer.put(mark);
buffer.put(sqlState);
if (message != null) {
buffer.put(message);
}
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
return data;
}
@Override
public ByteBuffer write(ByteBuffer buffer, FrontendConnection c,
boolean writeSocketIfFull) {
int size = calcPacketSize();
buffer = c.checkWriteBuffer(buffer, c.getPacketHeaderSize() + size,
writeSocketIfFull);
BufferUtil.writeUB3(buffer, size);
buffer.put(packetId);
buffer.put(fieldCount);
BufferUtil.writeUB2(buffer, errno);
buffer.put(mark);
buffer.put(sqlState);
if (message != null) {
buffer = c.writeToBuffer(message, buffer);
}
return buffer;
}
public void write(FrontendConnection c) {
ByteBuffer buffer = c.allocate();
buffer = this.write(buffer, c, true);
c.write(buffer);
}
@Override
public int calcPacketSize() {
int size = 9;// 1 + 2 + 1 + 5
if (message != null) {
size += message.length;
}
return size;
}
@Override
protected String getPacketInfo() {
return "MySQL Error Packet";
}
} | gpl-2.0 |
UniversalMediaServer/UniversalMediaServer | src/main/java/net/pms/dlna/CueFolder.java | 6607 | /*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.dlna;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import net.pms.dlna.Range.Time;
import net.pms.encoders.Player;
import net.pms.encoders.PlayerFactory;
import net.pms.formats.Format;
import org.apache.commons.lang3.StringUtils;
import org.digitalmediaserver.cuelib.CueParser;
import org.digitalmediaserver.cuelib.CueSheet;
import org.digitalmediaserver.cuelib.FileData;
import org.digitalmediaserver.cuelib.Position;
import org.digitalmediaserver.cuelib.TrackData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CueFolder extends DLNAResource {
private static final Logger LOGGER = LoggerFactory.getLogger(CueFolder.class);
private File playlistfile;
public File getPlaylistfile() {
return playlistfile;
}
private boolean valid = true;
public CueFolder(File f) {
playlistfile = f;
setLastModified(playlistfile.lastModified());
}
@Override
public InputStream getInputStream() throws IOException {
return null;
}
@Override
public String getName() {
return playlistfile.getName();
}
@Override
public String getSystemName() {
return playlistfile.getName();
}
@Override
public boolean isFolder() {
return true;
}
@Override
public boolean isValid() {
return valid;
}
@Override
public long length() {
return 0;
}
@Override
protected void resolveOnce() {
if (playlistfile.length() < 10000000) {
CueSheet sheet;
try {
sheet = CueParser.parse(playlistfile, null);
} catch (IOException e) {
LOGGER.info("Error in parsing cue: " + e.getMessage());
return;
}
if (sheet != null) {
List<FileData> files = sheet.getFileData();
// only the first one
if (!files.isEmpty()) {
FileData f = files.get(0);
List<TrackData> tracks = f.getTrackData();
Player defaultPlayer = null;
DLNAMediaInfo originalMedia = null;
ArrayList<DLNAResource> addedResources = new ArrayList<>();
for (int i = 0; i < tracks.size(); i++) {
TrackData track = tracks.get(i);
if (i > 0) {
double end = getTime(track.getIndices().get(0).getPosition());
if (addedResources.isEmpty()) {
// seems the first file was invalid or non existent
return;
}
DLNAResource prec = addedResources.get(i - 1);
int count = 0;
while (prec.isFolder() && i + count < addedResources.size()) { // not used anymore
prec = addedResources.get(i + count);
count++;
}
prec.getSplitRange().setEnd(end);
prec.getMedia().setDuration(prec.getSplitRange().getDuration());
LOGGER.debug("Track #" + i + " split range: " + prec.getSplitRange().getStartOrZero() + " - " + prec.getSplitRange().getDuration());
}
Position start = track.getIndices().get(0).getPosition();
RealFile realFile = new RealFile(new File(playlistfile.getParentFile(), f.getFile()));
addChild(realFile);
addedResources.add(realFile);
if (i > 0 && realFile.getMedia() == null) {
realFile.setMedia(new DLNAMediaInfo());
realFile.getMedia().setMediaparsed(true);
}
realFile.syncResolve();
if (i == 0) {
originalMedia = realFile.getMedia();
if (originalMedia == null) {
LOGGER.trace("Couldn't resolve media \"{}\" for cue file \"{}\" - aborting", realFile.getName(), playlistfile.getAbsolutePath());
return;
}
}
realFile.getSplitRange().setStart(getTime(start));
realFile.setSplitTrack(i + 1);
// Assign a splitter engine if file is natively supported by renderer
if (realFile.getPlayer() == null) {
if (defaultPlayer == null) {
defaultPlayer = PlayerFactory.getPlayer(realFile);
}
realFile.setPlayer(defaultPlayer);
}
if (realFile.getMedia() != null) {
try {
realFile.setMedia(originalMedia.clone());
} catch (CloneNotSupportedException e) {
LOGGER.info("Error in cloning media info: " + e.getMessage());
}
if (realFile.getMedia() != null && realFile.getMedia().getFirstAudioTrack() != null) {
if (realFile.getFormat().isAudio()) {
realFile.getMedia().getFirstAudioTrack().setSongname(track.getTitle());
} else {
realFile.getMedia().getFirstAudioTrack().setSongname("Chapter #" + (i + 1));
}
realFile.getMedia().getFirstAudioTrack().setTrack(i + 1);
realFile.getMedia().setSize(-1);
if (StringUtils.isNotBlank(sheet.getTitle())) {
realFile.getMedia().getFirstAudioTrack().setAlbum(sheet.getTitle());
}
if (StringUtils.isNotBlank(sheet.getPerformer())) {
realFile.getMedia().getFirstAudioTrack().setArtist(sheet.getPerformer());
}
if (StringUtils.isNotBlank(track.getPerformer())) {
realFile.getMedia().getFirstAudioTrack().setArtist(track.getPerformer());
}
}
}
}
if (!tracks.isEmpty() && !addedResources.isEmpty()) {
DLNAResource lastTrack = addedResources.get(addedResources.size() - 1);
Time lastTrackSplitRange = lastTrack.getSplitRange();
DLNAMediaInfo lastTrackMedia = lastTrack.getMedia();
if (lastTrackSplitRange != null && lastTrackMedia != null) {
lastTrackSplitRange.setEnd(lastTrackMedia.getDurationInSeconds());
lastTrackMedia.setDuration(lastTrackSplitRange.getDuration());
LOGGER.debug("Track #" + childrenNumber() + " split range: " + lastTrackSplitRange.getStartOrZero() + " - " + lastTrackSplitRange.getDuration());
}
}
storeFileInCache(playlistfile, Format.PLAYLIST);
}
}
}
}
private double getTime(Position p) {
return p.getMinutes() * 60 + p.getSeconds() + ((double) p.getFrames() / 100);
}
}
| gpl-2.0 |
smarr/Truffle | compiler/src/org.graalvm.compiler.phases.common/src/org/graalvm/compiler/phases/common/inlining/policy/AbstractInliningPolicy.java | 4459 | /*
* Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.phases.common.inlining.policy;
import static org.graalvm.compiler.phases.common.inlining.InliningPhase.Options.AlwaysInlineIntrinsics;
import java.util.Map;
import org.graalvm.compiler.nodes.Invoke;
import org.graalvm.compiler.nodes.StructuredGraph;
import org.graalvm.compiler.nodes.spi.Replacements;
import org.graalvm.compiler.phases.common.inlining.info.InlineInfo;
import org.graalvm.compiler.phases.common.inlining.info.elem.Inlineable;
import jdk.vm.ci.meta.ProfilingInfo;
import jdk.vm.ci.meta.ResolvedJavaMethod;
public abstract class AbstractInliningPolicy implements InliningPolicy {
public static final float RelevanceCapForInlining = 1.0f;
public static final float CapInheritedRelevance = 1.0f;
protected final Map<Invoke, Double> hints;
public AbstractInliningPolicy(Map<Invoke, Double> hints) {
this.hints = hints;
}
protected double computeMaximumSize(double relevance, int configuredMaximum) {
double inlineRatio = Math.min(RelevanceCapForInlining, relevance);
return configuredMaximum * inlineRatio;
}
protected double getInliningBonus(InlineInfo info) {
if (hints != null && hints.containsKey(info.invoke())) {
return hints.get(info.invoke());
}
return 1;
}
protected boolean isIntrinsic(Replacements replacements, InlineInfo info) {
if (AlwaysInlineIntrinsics.getValue(info.graph().getOptions())) {
return onlyIntrinsics(replacements, info);
} else {
return onlyForcedIntrinsics(replacements, info);
}
}
private static boolean onlyIntrinsics(Replacements replacements, InlineInfo info) {
for (int i = 0; i < info.numberOfMethods(); i++) {
if (!replacements.hasSubstitution(info.methodAt(i), info.graph().getOptions())) {
return false;
}
}
return true;
}
private static boolean onlyForcedIntrinsics(Replacements replacements, InlineInfo info) {
if (!onlyIntrinsics(replacements, info)) {
return false;
}
if (!info.shouldInline()) {
return false;
}
return true;
}
protected int previousLowLevelGraphSize(InlineInfo info) {
int size = 0;
for (int i = 0; i < info.numberOfMethods(); i++) {
ResolvedJavaMethod m = info.methodAt(i);
ProfilingInfo profile = info.graph().getProfilingInfo(m);
int compiledGraphSize = profile.getCompilerIRSize(StructuredGraph.class);
if (compiledGraphSize > 0) {
size += compiledGraphSize;
}
}
return size;
}
protected double determineInvokeProbability(InlineInfo info) {
double invokeProbability = 0;
for (int i = 0; i < info.numberOfMethods(); i++) {
Inlineable callee = info.inlineableElementAt(i);
Iterable<Invoke> invokes = callee.getInvokes();
if (invokes.iterator().hasNext()) {
for (Invoke invoke : invokes) {
invokeProbability += callee.getProbability(invoke);
}
}
}
return invokeProbability;
}
}
| gpl-2.0 |
coder1001/towerdefense | src/game/entities/Tower.java | 6927 | package game.entities;
import java.util.ArrayList;
import gfx.Colours;
import gfx.Screen;
import level.Level;
/**
* Die Tower Klasse erweitert die Entity Klasse
* Es handelt sich um ein feststehendes Objekt, welches Gegner in reichweite sucht und auf diese schießt
*
* @author Martin
*
*/
public class Tower extends Entity implements ITower{
protected int scale = 1;
private int colour = Colours.get(-1,111,500, 543); //black , darkgrey, lightgrey, white 543 -1,111,421, 543);
private int range = 30;
private double damage = 20;
private int price = 100;
public String name;
private int[] Sprite;
boolean inPlaceMode = false;
boolean inShowRadiusMode = false;
private int laserColor;
/*
* Wenn ein Gegner Schaden erleidet, wird neben dem Schaden auch der Effekt mitgegeben
* Für Effekte wie z.B Freeze/Stun
*/
int effect;
/*
* reloadTime ist die Nachladezeit
* WENN reloadStart-reloadNow > reloadTime -> Tower kann wieder schießen -> readyToShot = true
*/
private int reloadTime;
private long reloadStart;
private long reloadNow;
private boolean readyToShot;
/*
* shotTime ist die Anzahl der Ticks, welche ein Turm schießen kann bevor er nachladen muss
* shotTimeCounter zählt von 0 an bis shotTime hoch
*/
private int shotTime;
private int shotTimeCount;
/*
* Im ARRAY werden alle gelockten Gegner gespeichert
* Im INT ist die Anzahl der maximal gleichzeitig gelockten Gegner gespeichert
*/
public ArrayList<Mob> LockedEnemys;
private int lockedEnemyNumber;
/**
* Konstruktor, in dem die Standardparameter mitgegeben werden
* @param level
* @param x
* @param y
* @param towertype
*/
public Tower(Level level, int x, int y,TowerType towertype) {
super(level);
this.x = x;
this.y = y;
name = towertype.getName();
range = towertype.getRange();
damage = towertype.getDamage();
Sprite = towertype.getSprite();
colour = towertype.getColor();
price = towertype.getPrice();
effect = towertype.getEffect();
reloadTime = towertype.getReloadTime();
lockedEnemyNumber=towertype.getLockedEnemys();
shotTime = towertype.getShotTime();
this.inPlaceMode = false;
this.inShowRadiusMode = false;
this.readyToShot=true;
this.laserColor=towertype.getLaserColor();
LockedEnemys = new ArrayList<Mob>();
shotTimeCount=0;
}
/**
* Funktion zum setzen der Towerposition
* @param x
* @param y
*/
public void SetPosition(int x,int y)
{
this.x = x;
this.y = y;
}
/**
* FUnktion um den Tower in den PLacemode zu setzen
* In diesem Modus kann der Tower nicht schießen
* @param placemode
*/
public void SetPlaceMode(boolean placemode)
{
this.inPlaceMode = placemode;
}
/**
* Funktion um den Radius anzuzeigen, in dem der Tower schießt
* Zum Beispiel wenn man mit der Maus drüber zeigt oder einen neuen Twoer zeichnet
* @param radiusmode
*/
public void SetShowRadiusMode(boolean radiusmode)
{
this.inShowRadiusMode = radiusmode;
}
/**
* Towerpreis ermitteln?
* @return
*/
public int GetPrice()
{
return price;
}
/**
* Funktion überprüft ob ein ENtity in der Reichweite vom Tower ist
* @param e Entity das überprüft wird
* @return
*/
private Boolean IsInRange(Entity e)
{
if(e == null)
return false;
double distance = Math.sqrt( ((e.x-x)*(e.x-x))+((e.y-y)*(e.y-y)) );
if(distance <= range)
return true;
return false;
}
long lastTime = System.nanoTime();
/**
* Funktion in der die Physik Berechnungen durchgeführt werden
*/
public void tick() {
//Wenn in Placemode -> nicht schießen
if (this.inPlaceMode)
return;
//Wenn der Tower noch nicht seine Maximalanzahl an Gegner im Visier hat...
if(LockedEnemys.size()<lockedEnemyNumber){
for(Entity e : level.entities)
{
//Es interessieren uns nur die Enemys, die noch nicht im Visier sind und in Reichweite sind
if(e.getClass() != game.entities.Tower.class && !LockedEnemys.contains(e) && IsInRange(e))
{
Mob tempo = (Mob) e;
//Wenn der Tower den Freeze-Effekt hat und der Gegne bereits eingefroren ist,
//wird der Gegner nicht ins Vesier genommen
if(!(this.effect==1 && tempo.isFreezed()==true)){
LockedEnemys.add((Mob)e);
if(LockedEnemys.size()==lockedEnemyNumber)
break;
}
}
}
}
//Gehe alle im Visier befindlichen Gegner durch...
for(Mob lockedEnemy : LockedEnemys){
reloadNow=System.currentTimeMillis();
//wenn der tower nachgeladen hat ist er wieder bereit zu schießen
if(reloadNow-reloadStart>reloadTime && readyToShot == false){
readyToShot=true;
shotTimeCount=0;
}
//Schieße wenn Enemy in Reichweite ist, nicht gefreezed ist und reloadTime vorbei ist
if(IsInRange(lockedEnemy) && readyToShot==true)
{
//true, wenn Gegner nach dem Schaden keine HP mehr hat
if(lockedEnemy.DoDamage(this.damage, this.effect)){
LockedEnemys.remove(lockedEnemy);
break;
}
else{
shotTimeCount++;
//Wenn der Tower länger als shotTime geschossen hat, muss er nachladen...
if(shotTimeCount>=shotTime){
readyToShot=false;
reloadStart=System.currentTimeMillis();
}
}
}
else
{
// Entferne den Gegner, wenn er außerhalb der Reichweite ist
if(!IsInRange(lockedEnemy)){
LockedEnemys.remove(lockedEnemy);
break;
}
}
}
}//end tick
/**
* Funktion zum zeichnen der Tower
*/
public void render(Screen screen) {
int xTile = Sprite[0];
int yTile = Sprite[1];
int modifier = 8 * scale;
int xOffset = x - modifier/2;
int yOffset = y - modifier/2 -4;
//Wenn der Tower einen Gegner anvisiert hat, Linie zeichnen (Stellt den Schuss dar)
for(Mob lockedEnemy : LockedEnemys){
if(readyToShot == true)
screen.DrawLine(x+5, y-5, lockedEnemy.x,lockedEnemy.y,this.laserColor);
}
//Wenn der Tower im PLacemode oder im showRadiusMode ist, Kreis für den Radius zeichnen
if(this.inPlaceMode || this.inShowRadiusMode)
screen.DrawCircle(x+3, y+1, this.range, 215);
//Tower besteht aus 4 Tiles, alle zeichnen
screen.render(xOffset , yOffset , xTile + yTile * 32, colour);
screen.render(xOffset + modifier, yOffset , (xTile + 1) + yTile * 32, colour);
screen.render(xOffset , yOffset + modifier , xTile + (yTile+1) * 32, colour);
screen.render(xOffset + modifier, yOffset + modifier, (xTile + 1) + (yTile + 1) * 32, colour);
}
/**
* Funktion für Kollissionsüberprüfung, wird hier nicht benötigt.
* @param xa
* @param ya
* @return
*/
public boolean hasCollided(int xa, int ya) {
return false;
}
}
| gpl-2.0 |
Projet-JEE-EMN-FILA2-G8/EventManager | src/main/java/eventmanager/presentation/utils/Constants.java | 1569 | /**
*
*/
package eventmanager.presentation.utils;
/**
* @author Hadrien
*
*/
public class Constants {
public static final int SESSION_MAXTIME = 30*60; // 30 minutes
public static final String SERVLET_LOGIN = "/Login";
public static final String SERVLET_SUBSCRIBE = "/Subscribe";
public static final String SERVLET_PUBLIC_EVENT = "/Event";
public static final String SERVLET_CREATE_EVENT = "/CreateEvent";
public static final String SERVLET_EDIT_EVENT = "/EditEvent";
public static final String SERVLET_EVENT_LIST = "/MyEvents";
public static final String SERVLET_LOGOUT = "/Logout";
public static final String SERVLET_MAIN = SERVLET_EVENT_LIST;
public static String FOLDER_JS = "/js/";
public static String FOLDER_CSS = "/css/";
public static String FOLDER_FONTS = "/fonts/";
public static String FOLDER_JSP = "/WEB-INF/jsp/";
public static final String JSP_HEAD = FOLDER_JSP + "head.jsp";
public static final String JSP_NAV = FOLDER_JSP + "nav.jsp";
public static final String JSP_LOGIN = FOLDER_JSP + "login.jsp";
public static final String JSP_SUBSCRIBE = FOLDER_JSP + "subscribe.jsp";
public static final String JSP_EVENT_LIST = FOLDER_JSP + "myEvents.jsp";
public static final String JSP_EVENT = FOLDER_JSP + "event.jsp";
public static final String JSP_EDIT_EVENT = FOLDER_JSP + "editEvent.jsp";
public static final String ACTION = "action";
public static final String ACTION_DELETE = "delete";
public static final String ACTION_SHOW = "publish";
public static final String ACTION_SUSBCRIBE= "show";
}
| gpl-2.0 |
christopherfebles/magicdbapi | src/main/java/com/christopherfebles/magic/enums/Type.java | 1843 | package com.christopherfebles.magic.enums;
import org.springframework.util.StringUtils;
/**
* Magic Cards' types can be broken down into SuperType, Type, and SubType.<br>
* For example, the full type "Basic Land — Island" consists of a SuperType (Basic), a Type (Land), and a SubType (Island).<br>
* <br>
* This is an enumeration of all possible Types as of August 2014. I believe Type is a required field, but Magic Cards in Unglued or Unhinged are nuts.
*
* @author Christopher Febles
*
*/
public enum Type implements CardType {
ARTIFACT,
CREATURE,
ENCHANTMENT,
HERO,
INSTANT,
LAND,
PHENOMENON,
PLANE,
PLANESWALKER,
SCHEME,
SORCERY,
TRIBAL,
VANGUARD;
@Override
public boolean equals( CardType otherCard ) {
return this.toString().equalsIgnoreCase( otherCard.toString() );
}
@Override
public String toString() {
return StringUtils.capitalize( super.toString().toLowerCase() );
}
/**
* Bean formatted method name for JSP display
*
* @see #toString()
* @return The same value as the toString() method
*/
public String getDisplayableName() {
return this.toString();
}
@Override
public String getDatabaseSearchText() {
return this.toString();
}
/**
* Check if Type contains a given value, to avoid an IllegalArgumentException when calling {@link #valueOf(String)}
*
* @param name The name of Type Enum constant to look up
* @return True if the given name is present, false otherwise
*/
public static boolean contains( String name ) {
for ( Type type : Type.values() ) {
if ( type.name().equalsIgnoreCase( name ) ) {
return true;
}
}
return false;
}
}
| gpl-2.0 |
truhanen/JSana | JSana/src_others/org/crosswire/jsword/examples/StrongsAnalysis.java | 4766 | /**
* Distribution License:
* JSword is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License, version 2.1 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 Lesser General Public License for more details.
*
* The License is available on the internet at:
* http://www.gnu.org/copyleft/lgpl.html
* or by writing to:
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307, USA
*
* Copyright: 2007
* The copyright to this program is held by it's authors.
*
* ID: $Id: DictToOsis.java 1344 2007-05-23 21:50:52 -0400 (Wed, 23 May 2007) dmsmith $
*/
package org.crosswire.jsword.examples;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.crosswire.jsword.book.Book;
import org.crosswire.jsword.book.BookData;
import org.crosswire.jsword.book.BookException;
import org.crosswire.jsword.book.BookFilters;
import org.crosswire.jsword.book.Books;
import org.crosswire.jsword.book.FeatureType;
import org.crosswire.jsword.book.OSISUtil;
import org.crosswire.jsword.book.study.StrongsMapSet;
import org.crosswire.jsword.book.study.StrongsNumber;
import org.crosswire.jsword.passage.Key;
import org.jdom.Content;
import org.jdom.Element;
/**
* Analyze Strong's Numbers in a module.
*
* @see gnu.lgpl.License for license details.<br>
* The copyright to this program is held by it's authors.
* @author DM Smith [dmsmith555 at yahoo dot com]
*/
public class StrongsAnalysis {
/**
*
*/
public StrongsAnalysis() {
Book bible = Books.installed().getBook("KJV");
if (!bible.hasFeature(FeatureType.STRONGS_NUMBERS)) {
bible = null;
List<Book> bibles = Books.installed().getBooks(new BookFilters.BookFeatureFilter(FeatureType.STRONGS_NUMBERS));
if (!bibles.isEmpty()) {
bible = bibles.get(0);
}
}
if (bible == null) {
return;
}
List<Key> errors = new ArrayList<Key>();
StrongsMapSet sms = new StrongsMapSet();
analyze(sms, bible, errors, bible.getGlobalKeyList());
}
/**
* @param sms
* @param book
* @param errors
* @param wholeBible
*/
public void analyze(StrongsMapSet sms, Book book, List<Key> errors, Key wholeBible) {
BookData data = null;
Element osis = null;
StringBuilder buffer = new StringBuilder();
for (Key subkey : wholeBible) {
if (subkey.canHaveChildren()) {
analyze(sms, book, errors, subkey);
} else {
data = new BookData(book, subkey);
osis = null;
try {
osis = data.getOsisFragment();
} catch (BookException e) {
errors.add(subkey);
continue;
}
// Do the actual indexing
for (Content content : OSISUtil.getDeepContent(osis, OSISUtil.OSIS_ELEMENT_W)) {
// Clear out the buffer for re-use
int len = buffer.length();
if (len > 0) {
buffer.delete(0, len);
}
Element wElement = (Element) content;
String snAttr = wElement.getAttributeValue(OSISUtil.ATTRIBUTE_W_LEMMA);
String text = OSISUtil.getPlainText(wElement);
Matcher matcher = strongsNumberPattern.matcher(snAttr);
while (matcher.find()) {
try {
StrongsNumber strongsNumber = new StrongsNumber(matcher.group(1));
if (buffer.length() > 0) {
buffer.append(' ');
}
buffer.append(strongsNumber.getStrongsNumber());
} catch (BookException e) {
errors.add(subkey);
continue;
}
}
// now we can actually store the mapping
sms.add(buffer.toString(), text);
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
new StrongsAnalysis();
}
private static Pattern strongsNumberPattern = Pattern.compile("strong:([GH][0-9]+)");
}
| gpl-2.0 |
panbasten/imeta | imeta2.x/imeta-src/imeta-ui/src/main/java/com/panet/imeta/ui/dialog/EntryPluginDialog.java | 4007 | package com.panet.imeta.ui.dialog;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.panet.iform.core.BaseFormMeta;
import com.panet.iform.forms.columnForm.ColumnFormDataMeta;
import com.panet.iform.forms.columnForm.ColumnFormMeta;
import com.panet.iform.forms.grid.GridHeaderDataMeta;
import com.panet.iform.forms.grid.GridRowDataMeta;
import com.panet.iform.forms.labelGrid.LabelGridMeta;
import com.panet.imeta.core.exception.KettleException;
import com.panet.imeta.job.JobEntryLoader;
import com.panet.imeta.ui.exception.ImetaException;
public class EntryPluginDialog {
private String id;
private ColumnFormMeta columnFormMeta;
private ColumnFormDataMeta columnFormDataMeta;
private LabelGridMeta EntryPluginList;
public EntryPluginDialog() throws KettleException {
}
public JSONObject open() throws ImetaException {
try {
JSONObject rtn = new JSONObject();
JSONArray cArr = new JSONArray();
List<Object[]> pluginInformation = JobEntryLoader.getInstance().getPluginInformation();
this.id = "EntryPluginList";
// 得到form
this.columnFormDataMeta = new ColumnFormDataMeta(id, null);
this.columnFormMeta = new ColumnFormMeta(columnFormDataMeta);
this.EntryPluginList = new LabelGridMeta(id + "_EntryPluginList", "可以使用的作业项插件", 400);
this.EntryPluginList.addHeaders(new GridHeaderDataMeta[] {
new GridHeaderDataMeta(this.id + "#", "#", null,false, 50),
new GridHeaderDataMeta(this.id + "TypeDesc", "类型", null, false,100),
new GridHeaderDataMeta(this.id + "ID", "ID", null,false, 150),
new GridHeaderDataMeta(this.id + "Description", "描述", null,false, 200),
new GridHeaderDataMeta(this.id + "Tooltip", "提示", null, false,400),
new GridHeaderDataMeta(this.id + "Directory", "目录", null,false, 100),
new GridHeaderDataMeta(this.id + "JarfilesList", "Jar文件类表", null,false, 150),
new GridHeaderDataMeta(this.id + "IconFilename", "图标文件", null, false,100),
new GridHeaderDataMeta(this.id + "Classname", "类名", null,false, 260),
new GridHeaderDataMeta(this.id + "Category", "步骤类别", null,false, 100),
new GridHeaderDataMeta(this.id + "ErrorHelpFile", "错误帮助文件", null, false,150),
new GridHeaderDataMeta(this.id + "isSeparateClassloaderNeeded", "分离的类加载器?", null,false, 150),
});
for (int i=0;i<pluginInformation.size();i++) {
int index = 0;
Object[] stepPlugin = (Object[])pluginInformation.get(i);
GridRowDataMeta rowDataMeta = new GridRowDataMeta(12);
rowDataMeta.setCell(index++,i+1+"");
rowDataMeta.setCell(index++,stepPlugin[0]!=null?stepPlugin[0].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[1]!=null?stepPlugin[1].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[2]!=null?stepPlugin[2].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[3]!=null?stepPlugin[3].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[4]!=null?stepPlugin[4].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[5]!=null?stepPlugin[5].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[6]!=null?stepPlugin[6].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[7]!=null?stepPlugin[7].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[8]!=null?stepPlugin[8].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[9]!=null?stepPlugin[9].toString():"" );
rowDataMeta.setCell(index++,stepPlugin[10].toString()=="true"?"Y":"N" );
this.EntryPluginList.addRow(rowDataMeta);
}
this.EntryPluginList.setSingle(true);
this.columnFormMeta
.putFieldsetsContent(new BaseFormMeta[] { this.EntryPluginList });
cArr.add(this.columnFormMeta.getFormJo());
rtn.put("items", cArr);
rtn.put("title", "作业项插件列表");
rtn.put("id", this.id);
return rtn;
} catch (Exception ex) {
throw new ImetaException(ex.getMessage(), ex);
}
}
}
| gpl-2.0 |
itomi/SztuczneOko | src/pl/pwr/sztuczneoko/ui/CameraActivity.java | 5492 | package pl.pwr.sztuczneoko.ui;
import pl.pwr.sztuczneoko.camera.*;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.regex.Pattern;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import pl.pwr.sztuczneoko.camera.CameraSurface;
import pl.pwr.sztuczneoko.core.ImageItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
public class CameraActivity extends soActivity implements CameraCallback{
private FrameLayout cameraholder = null;
private CameraSurface camerasurface = null;
private MenuItem mItemRunCamProp;
private MenuItem mItemRunFilterProp;
private MenuItem mItemRunBTProp;
private ProgressDialog progressDialog;
protected static final String MEDIA_TYPE_IMAGE = null;
Button captureButton;
Button filterButton;
Button againPhotoButton;
@Override
public void onResume(){
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
captureButton = (Button) findViewById(R.id.button_capture);
filterButton = (Button) findViewById(R.id.button_filter_photo);
againPhotoButton = (Button) findViewById(R.id.button_photo_again);
cameraholder = (FrameLayout)findViewById(R.id.camera_preview);
setupPictureMode();
filterButton.setEnabled(false);
againPhotoButton.setEnabled(false);
}
public void againPhotoClick(View view){
filterButton.setEnabled(false);
againPhotoButton.setEnabled(false);
captureButton.setEnabled(true);
camerasurface.startPreview();
}
public void captureClick(View view){
camerasurface.startTakePicture();
filterButton.setEnabled(true);
againPhotoButton.setEnabled(true);
captureButton.setEnabled(false);
}
public void filterPhotoClick(View view){
core.sendPhoto(this,"/soAppDir/myImages/");
}
public void showProgressDialog(String title,String message) {
progressDialog = ProgressDialog.show(this, title, message, true);
progressDialog.setCancelable(true);
}
public void hideProgressDialog(){
progressDialog.dismiss();
}
private void setupPictureMode(){
camerasurface = new CameraSurface(this,core);
cameraholder.addView(camerasurface, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
camerasurface.setCallback(this);
}
@Override
public void onJpegPictureTaken(byte[] data, Camera camera) {
try
{
Log.d("cam", "fotka");
core.setCurrentImg(data);
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
}
@Override
public void onRawPictureTaken(byte[] data, Camera camera) {
}
@Override
public void onShutter() {
}
@Override
public String onGetVideoFilename(){
String filename = String.format("/sdcard/%d.3gp",System.currentTimeMillis());
return filename;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mItemRunCamProp = menu.add("ustawienia kamery");
mItemRunFilterProp = menu.add("ustawienia filtracji");
mItemRunBTProp = menu.add("ustawienia bluetooth");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == mItemRunCamProp) {
startActivity(core.getPropertiesMenuEvents().runCamPropertiesActivity(this));
} else if (item == mItemRunFilterProp) {
startActivity(core.getPropertiesMenuEvents().runFilterPropertiesActivity(this));
} else if (item == mItemRunBTProp) {
startActivity(core.getPropertiesMenuEvents().runBTPropertiesActivity(this));
}
return true;
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i("openCV", "OpenCV loaded successfully");
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
} | gpl-2.0 |
pddthinh/android-vlc | vlc-android/src/org/videolan/vlc/gui/tv/browser/SortedBrowserFragment.java | 11262 | /*
* *************************************************************************
* SortedBrowserFragment.java
* **************************************************************************
* Copyright © 2016 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui.tv.browser;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v17.leanback.app.BackgroundManager;
import android.support.v17.leanback.app.BrowseFragment;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.OnItemViewSelectedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.support.v4.util.SimpleArrayMap;
import org.videolan.libvlc.Media;
import org.videolan.medialibrary.media.MediaWrapper;
import org.videolan.vlc.R;
import org.videolan.vlc.VLCApplication;
import org.videolan.vlc.gui.helpers.MediaComparators;
import org.videolan.vlc.gui.tv.CardPresenter;
import org.videolan.vlc.gui.tv.DetailsActivity;
import org.videolan.vlc.gui.tv.MainTvActivity;
import org.videolan.vlc.gui.tv.MediaItemDetails;
import org.videolan.vlc.gui.tv.TvUtil;
import org.videolan.vlc.gui.tv.browser.interfaces.BrowserActivityInterface;
import org.videolan.vlc.gui.tv.browser.interfaces.BrowserFragmentInterface;
import org.videolan.vlc.gui.tv.browser.interfaces.DetailsFragment;
import org.videolan.vlc.util.WeakHandler;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public abstract class SortedBrowserFragment extends BrowseFragment implements BrowserFragmentInterface, OnItemViewSelectedListener, OnItemViewClickedListener, DetailsFragment {
public static final String TAG = "VLC/SortedBrowserFragment";
public static final String KEY_URI = "uri";
public static final String SELECTED_ITEM = "selected";
public static final String CURRENT_BROWSER_LIST = "CURRENT_BROWSER_LIST";
public static final int UPDATE_DISPLAY = 1;
public static final int UPDATE_ITEM = 2;
public static final int HIDE_LOADING = 3;
protected ArrayObjectAdapter mAdapter = new ArrayObjectAdapter(new ListRowPresenter());
protected MediaWrapper mItemSelected;
protected Map<String, ListItem> mMediaItemMap = new ArrayMap<>();
SimpleArrayMap<String, Integer> mMediaIndex = new SimpleArrayMap<>();
ArrayList<MediaWrapper> mVideosList = new ArrayList<>();
protected BrowserHandler mHandler = new BrowserHandler(this);
private BackgroundManager mBackgroundManager;
abstract protected void browse();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
mItemSelected = savedInstanceState.getParcelable(SELECTED_ITEM);
setOnItemViewClickedListener(this);
setAdapter(mAdapter);
// UI setting
setHeadersState(HEADERS_ENABLED);
setBrandColor(ContextCompat.getColor(getActivity(), R.color.orange800));
mBackgroundManager = BackgroundManager.getInstance(getActivity());
mBackgroundManager.setAutoReleaseOnStop(false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHeadersState(HEADERS_HIDDEN);
setOnItemViewSelectedListener(this);
if (mAdapter.size() == 0)
browse();
}
@Override
public void onStart() {
super.onStart();
if (mItemSelected != null)
TvUtil.updateBackground(mBackgroundManager, mItemSelected);
}
@Override
public void onResume() {
super.onResume();
VLCApplication.storeData(CURRENT_BROWSER_LIST, mVideosList);
if (!mBackgroundManager.isAttached())
mBackgroundManager.attachToView(getView());
}
@Override
public void onPause() {
super.onPause();
TvUtil.releaseBackgroundManager(mBackgroundManager);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mItemSelected != null)
outState.putParcelable(SELECTED_ITEM, mItemSelected);
}
public void showDetails() {
if (mItemSelected == null)
return;
Intent intent = new Intent(getActivity(),
DetailsActivity.class);
// pass the item information
intent.putExtra("media", mItemSelected);
intent.putExtra("item", new MediaItemDetails(mItemSelected.getTitle(),
mItemSelected.getArtist(), mItemSelected.getAlbum(),
mItemSelected.getLocation(), mItemSelected.getArtworkURL()));
startActivity(intent);
}
@Override
public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
mItemSelected = (MediaWrapper)item;
TvUtil.updateBackground(mBackgroundManager, item);
}
@Override
public void onItemClicked(Presenter.ViewHolder viewHolder, Object item, RowPresenter.ViewHolder viewHolder1, Row row) {
MediaWrapper media = (MediaWrapper) item;
if (media.getType() == MediaWrapper.TYPE_DIR)
TvUtil.browseFolder(getActivity(), getCategoryId(), ((MediaWrapper) item).getUri());
else
TvUtil.openMedia(getActivity(), item, null);
}
private long getCategoryId() {
if (this instanceof NetworkBrowserFragment)
return MainTvActivity.HEADER_NETWORK;
else if (this instanceof DirectoryBrowserFragment)
return MainTvActivity.HEADER_DIRECTORIES;
return -1;
}
@Override
public void refresh() {
mMediaItemMap.clear();
mMediaIndex.clear();
mAdapter.clear();
browse();
}
protected void sort(){
VLCApplication.runBackground(new Runnable() {
@Override
public void run() {
mMediaItemMap = new TreeMap<>(mMediaItemMap); //sort sections
for (ListItem item : mMediaItemMap.values()) {
Collections.sort(item.mediaList, MediaComparators.byFileType);
mVideosList.addAll(item.mediaList);
}
mHandler.sendEmptyMessage(UPDATE_DISPLAY);
VLCApplication.storeData(CURRENT_BROWSER_LIST, mVideosList);
}
});
}
@Override
public void updateList() {
Activity activity = getActivity();
if (activity == null)
return;
mAdapter = new ArrayObjectAdapter(new ListRowPresenter());
setAdapter(mAdapter);
ArrayObjectAdapter adapter;
HeaderItem header;
for (ListItem item : mMediaItemMap.values()){
adapter = new ArrayObjectAdapter(new CardPresenter(activity));
header = new HeaderItem(0, item.Letter);
adapter.addAll(0, item.mediaList);
mAdapter.add(new ListRow(header, adapter));
}
mHandler.sendEmptyMessageDelayed(HIDE_LOADING, 3000);
}
protected void addMedia(Media media){
addMedia(new MediaWrapper(media));
}
protected void addMedia(MediaWrapper mw) {
int type = mw.getType();
if (type != MediaWrapper.TYPE_AUDIO && type != MediaWrapper.TYPE_VIDEO && type != MediaWrapper.TYPE_DIR)
return;
String letter = mw.getTitle().substring(0, 1).toUpperCase();
if (mMediaItemMap.containsKey(letter)) {
int position = mMediaItemMap.get(letter).mediaList.indexOf(mw);
if (position != -1) {
mMediaItemMap.get(letter).mediaList.set(position, mw);
} else
mMediaItemMap.get(letter).mediaList.add(mw);
} else {
ListItem item = new ListItem(letter, mw);
mMediaItemMap.put(letter, item);
}
((BrowserActivityInterface)getActivity()).showProgress(false);
((BrowserActivityInterface)getActivity()).updateEmptyView(false);
mHandler.removeMessages(HIDE_LOADING);
}
public boolean isEmpty() {
return mMediaItemMap.isEmpty();
}
public void updateItem(MediaWrapper item) {
if (mAdapter != null && mMediaIndex != null && item != null
&& mMediaIndex.containsKey(item.getLocation()))
mAdapter.notifyArrayItemRangeChanged(mMediaIndex.get(item.getLocation()), 1);
}
public static class ListItem {
String Letter;
public ArrayList<MediaWrapper> mediaList;
ListItem(String letter, MediaWrapper mediaWrapper) {
mediaList = new ArrayList<>();
if (mediaWrapper != null)
mediaList.add(mediaWrapper);
Letter = letter;
}
}
protected static class BrowserHandler extends WeakHandler<SortedBrowserFragment> {
BrowserHandler(SortedBrowserFragment owner) {
super(owner);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
SortedBrowserFragment owner = getOwner();
if (owner == null)
return;
switch (msg.what) {
case UPDATE_ITEM:
owner.updateItem((MediaWrapper)msg.obj);
break;
case UPDATE_DISPLAY:
owner.updateList();
break;
case HIDE_LOADING:
if (owner.getActivity() != null) {
((VerticalGridActivity)owner.getActivity()).showProgress(false);
((VerticalGridActivity)owner.getActivity()).updateEmptyView(owner.isEmpty());
}
break;
}
}
}
}
| gpl-2.0 |
hbv401g-team3f/flugverkefni | src/exceptions/InvalidTimeException.java | 219 | package exceptions;
/**
* Custom exception for invalid flight time boundaries
*/
public class InvalidTimeException extends Exception {
public InvalidTimeException(String message){
super(message);
}
} | gpl-2.0 |
favedit/MoPlatform | mo-4-web/src/web-java/org/mo/web/core/webtools/common/XMenuButtonSplit.java | 172 | package org.mo.web.core.webtools.common;
import org.mo.web.core.webtools.base.XBaseMenuButtonSplit;
public class XMenuButtonSplit
extends XBaseMenuButtonSplit
{
}
| gpl-2.0 |
cjg/blifpad | src/KissTab.java | 3263 | /* KissTab.java */
/* <project_name> -- <project_description>
*
* Copyright (C) 2006 - 2007
* Giuseppe Coviello <cjg@cruxppc.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
public class KissTab extends FullOptionalTab {
private JButton kissButton;
public KissTab(Notebook notebook) {
super();
this.notebook = notebook;
buildLayout();
kissButton.addActionListener(new KissListener());
}
public void writeKiss() {
if(!check())
return;
if(myPreferences == null)
myPreferences = new MyPreferences();
String filename = getFilename();
File stateMinimized = null;
if(stateMinimizeBox.isSelected()) {
try {
stateMinimized = getStateMinimizedFile(filename);
filename = stateMinimized.getName();
} catch (IOException e) {
return;
}
}
String cmd[] = {
myPreferences.getSisPath(),
"-t", "blif",
"-T", "none",
"-c", "write_kiss",
filename
};
exec(cmd, null, getPath());
if(stateMinimized != null)
stateMinimized.delete();
String formattedOutput = ("<body bgcolor='black'><b><pre>" +
"<font color='white'>" +
getFilename() + "<br>========<br>");
if(getStdErr().length() > 0)
formattedOutput += "<font color='red'>" + getStdErr() + "</font><br>";
formattedOutput += getStdOut() + "</font></pre></b></body>";
consolePane.setText(formattedOutput);
}
private void buildLayout() {
setLayout(new BorderLayout());
stateMinimizeBox = new JCheckBox(ResourceLoader._("State Minimize"));
kissButton = new JButton(ResourceLoader._("Write Transictions Table"));
JPanel controlPanel = new JPanel();
controlPanel.add(stateMinimizeBox);
controlPanel.add(kissButton);
consolePane = new ConsolePane();
add(controlPanel, BorderLayout.NORTH);
add(consolePane, BorderLayout.CENTER);
}
public class KissListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
writeKiss();
}
}
}
| gpl-2.0 |
callakrsos/Gargoyle | gargoyle-commons/src/main/java/com/kyj/fx/commons/fx/controls/grid/skin/CVirtualFlow.java | 2830 | /********************************
* 프로젝트 : VisualFxVoEditor
* 패키지 : com.sun.javafx.scene.control.skin
* 작성일 : 2017. 7. 6.
* 프로젝트 : OPERA
* 작성자 : KYJ
*******************************/
package com.kyj.fx.commons.fx.controls.grid.skin;
import java.util.List;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import com.sun.javafx.scene.control.skin.VirtualScrollBar;
import javafx.geometry.Insets;
import javafx.scene.control.IndexedCell;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.paint.Color;
/**
* @author KYJ
*
*/
public class CVirtualFlow<T extends IndexedCell> extends VirtualFlow<T> {
private CTableView<?> tableView;
public void init(CTableView<?> tableView) {
this.tableView = tableView;
}
@SuppressWarnings("restriction")
public VirtualScrollBar getVerticalbar() {
return getVbar();
}
@SuppressWarnings("restriction")
public VirtualScrollBar getHorizontalBar() {
return getHbar();
}
@Override
protected void layoutChildren() {
super.layoutChildren();
//이부분이 중요
if (tableView != null) {
/*
* 이 부분은 테이블 row를 의미함. fixed를 사용하기 위해선 갱신시켜줘야되는것으로 보임.
*
*/
for (CTableRow<T> cell : (List<CTableRow<T>>) getCells()) {
// int index = cell.getIndex();
// System.out.println(index);
cell.requestLayout();
// cell.requestFocus();
}
}
}
/**
* With that comparator we can lay out our rows in the reverse order. That is to say from the bottom to the very top. In that manner we
* are sure that our spanning cells will COVER the cell below so we don't have any problems with missing hovering, the editor jammed
* etc. <br/>
*
* The only problem is for the fixed column but the {@link #getTopRow(int) } now returns the very first row and allow us to put some
* privileged TableCell in it if they feel the need to be on top in term of z-order.
*
* FIXME The best would be to put a TreeList of something like that in order not to sort the rows everytime, need investigation..
*/
// private static final Comparator<GridRow> ROWCMP = new Comparator<GridRow>() {
// @Override
// public int compare(GridRow firstRow, GridRow secondRow) {
// // o1.getIndex() < o2.getIndex() ? -1 : +1;
// return secondRow.getIndex() - firstRow.getIndex();
// }
// };
/**
* Sort the rows so that they stay in order for layout
*/
// private void sortRows() {
// final List<GridRow> temp = (List<GridRow>) getCells();
// final List<GridRow> tset = new ArrayList<>(temp);
// Collections.sort(tset, ROWCMP);
// for (final TableRow<ObservableList<SpreadsheetCell>> r : tset) {
// r.toFront();
// }
// }
}
| gpl-2.0 |
nekosune/OpenEnd | openend_common/com/newgaea/openEnd/gen/EndVillageGenner.java | 1563 | package com.newgaea.openEnd.gen;
import java.util.Random;
import com.newgaea.openEnd.Configs;
import cpw.mods.fml.common.IWorldGenerator;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenMinable;
import net.minecraft.world.gen.feature.WorldGenerator;
public class EndVillageGenner implements IWorldGenerator {
private void generateEnd(World world, Random random, int i, int j) {
for(int k = 0; k < Configs.oreDensity; k++) {
int firstBlockXCoord = i + random.nextInt(16);
int firstBlockYCoord = random.nextInt(64);
int firstBlockZCoord = j + random.nextInt(16);
(new WorldGenEndMinable(Configs.DarkEndStoneId, 13)).generate(world, random, firstBlockXCoord, firstBlockYCoord, firstBlockZCoord);
}
}
private void generateSurface(World world, Random random, int i, int j) {
// TODO Auto-generated method stub
}
private void generateNether(World world, Random random, int i, int j) {
// TODO Auto-generated method stub
}
@Override
public void generate(Random random, int chunkX, int chunkZ, World world,
IChunkProvider chunkGenerator, IChunkProvider chunkProvider) {
switch(world.provider.dimensionId){
case -1:
generateNether(world, random, chunkX * 16, chunkZ * 16);
break;
case 0:
generateSurface(world, random, chunkX * 16, chunkZ * 16);
break;
case 1:
generateEnd(world, random, chunkX * 16, chunkZ * 16);
break;
}
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest06441.java | 1730 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest06441")
public class BenchmarkTest06441 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getQueryString();
String bar = param.split(" ")[0];
// javax.servlet.http.HttpSession.putValue(java.lang.String^,java.lang.Object)
request.getSession().putValue( bar, "foo");
}
}
| gpl-2.0 |
KayOnline/DesignPatterns | src/main/java/org/gof/mediator/ConcreteColleague1.java | 421 | package org.gof.mediator;
public class ConcreteColleague1 implements Colleague {
private Mediator mediator;
public ConcreteColleague1(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void receive(String message) {
System.out.printf("Colleague %s Received: %s \n", this.getClass().getName(), message);
}
@Override
public void send(String message) {
mediator.send(message, this);
}
}
| gpl-2.0 |
christianchristensen/resin | modules/kernel/src/com/caucho/config/ConfigException.java | 4752 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.config;
import com.caucho.util.*;
import com.caucho.vfs.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.logging.*;
/**
* Thrown by the various Builders
*/
public class ConfigException
extends ConfigRuntimeException
implements CompileException, DisplayableException
{
private static final Logger log
= Logger.getLogger(ConfigException.class.getName());
/**
* Create a null exception
*/
public ConfigException()
{
}
/**
* Creates an exception with a message
*/
public ConfigException(String msg)
{
super(msg);
}
/**
* Creates an exception with a message and throwable
*/
public ConfigException(String msg, Throwable e)
{
super(msg, e);
}
/**
* Creates an exception with a throwable
*/
protected ConfigException(Throwable e)
{
super(getMessage(e), e);
}
protected static String getMessage(Throwable e)
{
if (e instanceof DisplayableException || e instanceof CompileException)
return e.getMessage();
else
return e.toString();
}
public static RuntimeException create(String location, Throwable e)
{
if (e instanceof InstantiationException && e.getCause() != null)
e = e.getCause();
if (e instanceof InvocationTargetException && e.getCause() != null)
e = e.getCause();
if (e instanceof LineConfigException)
throw (LineConfigException) e;
else if (e instanceof DisplayableException) {
return new ConfigException(location + e.getMessage(), e);
}
else
return new ConfigException(location + e, e);
}
public static RuntimeException createLine(String line, Throwable e)
{
while (e.getCause() != null
&& (e instanceof InstantiationException
|| e instanceof InvocationTargetException
|| e.getClass().equals(ConfigRuntimeException.class))) {
e = e.getCause();
}
if (e instanceof LineConfigException)
throw (LineConfigException) e;
else if (e instanceof DisplayableException) {
return new LineConfigException(line + e.getMessage(), e);
}
else
return new LineConfigException(line + e, e);
}
public static RuntimeException create(Field field, Throwable e)
{
return create(loc(field), e);
}
public static RuntimeException create(Method method, Throwable e)
{
return create(loc(method), e);
}
public static RuntimeException create(Method method, String msg, Throwable e)
{
return new ConfigException(loc(method) + msg, e);
}
public static RuntimeException create(Method method, String msg)
{
return new ConfigException(loc(method) + msg);
}
public static RuntimeException create(Throwable e)
{
while (e.getCause() != null
&& (e instanceof InstantiationException
|| e instanceof InvocationTargetException
|| e.getClass().equals(ConfigRuntimeException.class))) {
e = e.getCause();
}
if (e instanceof RuntimeException)
return (RuntimeException) e;
else if (e instanceof LineCompileException)
return new LineConfigException(e.getMessage(), e);
else if (e instanceof DisplayableException
|| e instanceof CompileException)
return new ConfigException(e.getMessage(), e);
else
return new ConfigRuntimeException(e);
}
public void print(PrintWriter out)
{
out.println(Html.escapeHtml(getMessage()));
}
public static String loc(Field field)
{
return field.getDeclaringClass().getName() + "." + field.getName() + ": ";
}
public static String loc(Method method)
{
return method.getDeclaringClass().getName() + "." + method.getName() + "(): ";
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/ServerTimeout.java | 9773 | /*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4836493
* @summary Socket timeouts for SSLSockets causes data corruption.
*/
import java.io.*;
import java.net.*;
import java.util.*;
import java.security.*;
import javax.net.ssl.*;
public class ServerTimeout {
/*
* =============================================================
* Set the various variables needed for the tests, then
* specify what tests to run on each side.
*/
/*
* Should we run the client or server in a separate thread?
* Both sides can throw exceptions, but do you have a preference
* as to which side should be the main thread.
*/
static boolean separateServerThread = true;
/*
* Where do we find the keystores?
*/
static String pathToStores = "/../../../../../../../etc";
static String keyStoreFile = "keystore";
static String trustStoreFile = "truststore";
static String passwd = "passphrase";
/*
* Is the server ready to serve?
*/
volatile static boolean serverReady = false;
/*
* Turn on SSL debugging?
*/
static boolean debug = false;
/*
* If the client or server is doing some kind of object creation
* that the other side depends on, and that thread prematurely
* exits, you may experience a hang. The test harness will
* terminate all hung threads after its timeout has expired,
* currently 3 minutes by default, but you might try to be
* smart about it....
*/
/*
* Define the server side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doServerSide() throws Exception {
SSLServerSocketFactory sslssf =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslServerSocket =
(SSLServerSocket) sslssf.createServerSocket(serverPort);
serverPort = sslServerSocket.getLocalPort();
/*
* Signal Client, we're ready for his connect.
*/
serverReady = true;
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslSocket.startHandshake();
// read application data from client
MessageDigest md = MessageDigest.getInstance("SHA");
DigestInputStream transIns = new DigestInputStream(sslIS, md);
byte[] bytes = new byte[2000];
sslSocket.setSoTimeout(100); // The stall timeout
while (true) {
try {
while (transIns.read(bytes, 0, 17) != -1);
break;
} catch (SocketTimeoutException e) {
System.out.println("Server inputStream Exception: "
+ e.getMessage());
}
}
// wait for client to get ready
while (clientDigest == null) {
Thread.sleep(20);
}
byte[] srvDigest = md.digest();
if (!Arrays.equals(clientDigest, srvDigest)) {
throw new Exception("Application data trans error");
}
transIns.close();
sslSocket.close();
}
/*
* Define the client side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doClientSide() throws Exception {
boolean caught = false;
/*
* Wait for server to get started.
*/
while (!serverReady) {
Thread.sleep(50);
}
SSLSocketFactory sslsf =
(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket)
sslsf.createSocket("localhost", serverPort);
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslSocket.startHandshake();
// transfer a file to server
String transFilename =
System.getProperty("test.src", "./") + "/" +
this.getClass().getName() + ".java";
MessageDigest md = MessageDigest.getInstance("SHA");
DigestInputStream transIns = new DigestInputStream(
new FileInputStream(transFilename), md);
byte[] bytes = new byte[2000];
int i = 0;
while (true) {
// reset the cycle
if (i >= bytes.length) {
i = 0;
}
int length = transIns.read(bytes, 0, i++);
if (length == -1) {
break;
} else {
sslOS.write(bytes, 0, length);
sslOS.flush();
if (i % 3 == 0) {
Thread.sleep(300); // Stall past the timeout...
}
}
}
clientDigest = md.digest();
transIns.close();
sslSocket.close();
}
/*
* =============================================================
* The remainder is just support stuff
*/
// use any free port by default
volatile int serverPort = 0;
volatile Exception serverException = null;
volatile Exception clientException = null;
volatile byte[] clientDigest = null;
public static void main(String[] args) throws Exception {
String keyFilename =
System.getProperty("test.src", "./") + "/" + pathToStores +
"/" + keyStoreFile;
String trustFilename =
System.getProperty("test.src", "./") + "/" + pathToStores +
"/" + trustStoreFile;
System.setProperty("javax.net.ssl.keyStore", keyFilename);
System.setProperty("javax.net.ssl.keyStorePassword", passwd);
System.setProperty("javax.net.ssl.trustStore", trustFilename);
System.setProperty("javax.net.ssl.trustStorePassword", passwd);
if (debug)
System.setProperty("javax.net.debug", "all");
/*
* Start the tests.
*/
new ServerTimeout();
}
Thread clientThread = null;
Thread serverThread = null;
/*
* Primary constructor, used to drive remainder of the test.
*
* Fork off the other side, then do your work.
*/
ServerTimeout() throws Exception {
if (separateServerThread) {
startServer(true);
startClient(false);
} else {
startClient(true);
startServer(false);
}
/*
* Wait for other side to close down.
*/
if (separateServerThread) {
serverThread.join();
} else {
clientThread.join();
}
/*
* When we get here, the test is pretty much over.
*
* If the main thread excepted, that propagates back
* immediately. If the other thread threw an exception, we
* should report back.
*/
if (serverException != null) {
System.out.print("Server Exception:");
throw serverException;
}
if (clientException != null) {
System.out.print("Client Exception:");
throw clientException;
}
}
void startServer(boolean newThread) throws Exception {
if (newThread) {
serverThread = new Thread() {
public void run() {
try {
doServerSide();
} catch (Exception e) {
/*
* Our server thread just died.
*
* Release the client, if not active already...
*/
System.err.println("Server died...");
System.err.println(e);
serverReady = true;
serverException = e;
}
}
};
serverThread.start();
} else {
doServerSide();
}
}
void startClient(boolean newThread) throws Exception {
if (newThread) {
clientThread = new Thread() {
public void run() {
try {
doClientSide();
} catch (Exception e) {
/*
* Our client thread just died.
*/
System.err.println("Client died...");
clientException = e;
}
}
};
clientThread.start();
} else {
doClientSide();
}
}
}
| gpl-2.0 |
ambro2/jabref | src/main/java/net/sf/jabref/external/SynchronizeFileField.java | 18127 | package net.sf.jabref.external;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import net.sf.jabref.BibDatabaseContext;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRefExecutorService;
import net.sf.jabref.gui.BasePanel;
import net.sf.jabref.gui.FileListEntry;
import net.sf.jabref.gui.FileListEntryEditor;
import net.sf.jabref.gui.FileListTableModel;
import net.sf.jabref.gui.IconTheme;
import net.sf.jabref.gui.keyboard.KeyBinding;
import net.sf.jabref.gui.undo.NamedCompound;
import net.sf.jabref.gui.undo.UndoableFieldChange;
import net.sf.jabref.gui.util.FocusRequester;
import net.sf.jabref.gui.worker.AbstractWorker;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.util.io.FileUtil;
import net.sf.jabref.model.entry.BibEntry;
import net.sf.jabref.model.entry.FieldName;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* This action goes through all selected entries in the BasePanel, and attempts to autoset the
* given external file (pdf, ps, ...) based on the same algorithm used for the "Auto" button in
* EntryEditor.
*/
public class SynchronizeFileField extends AbstractWorker {
private final BasePanel panel;
private List<BibEntry> sel;
private SynchronizeFileField.OptionsDialog optDiag;
private int entriesChangedCount;
private final Object[] brokenLinkOptions = {Localization.lang("Ignore"), Localization.lang("Assign new file"),
Localization.lang("Remove link"), Localization.lang("Remove all broken links"),
Localization.lang("Quit synchronization")};
private boolean goOn = true;
private boolean autoSet = true;
private boolean checkExisting = true;
public SynchronizeFileField(BasePanel panel) {
this.panel = panel;
}
@Override
public void init() {
Collection<BibEntry> col = panel.getDatabase().getEntries();
goOn = true;
sel = new ArrayList<>(col);
// Ask about rules for the operation:
if (optDiag == null) {
optDiag = new SynchronizeFileField.OptionsDialog(panel.frame(), panel.getBibDatabaseContext());
}
optDiag.setLocationRelativeTo(panel.frame());
optDiag.setVisible(true);
if (optDiag.canceled()) {
goOn = false;
return;
}
autoSet = !optDiag.isAutoSetNone();
checkExisting = optDiag.isCheckLinks();
panel.output(Localization.lang("Synchronizing file links..."));
}
@Override
public void run() {
if (!goOn) {
panel.output(Localization.lang("This operation requires one or more entries to be selected."));
return;
}
entriesChangedCount = 0;
panel.frame().setProgressBarValue(0);
panel.frame().setProgressBarVisible(true);
int weightAutoSet = 10; // autoSet takes 10 (?) times longer than checkExisting
int progressBarMax = (autoSet ? weightAutoSet * sel.size() : 0) + (checkExisting ? sel.size() : 0);
panel.frame().setProgressBarMaximum(progressBarMax);
int progress = 0;
final NamedCompound ce = new NamedCompound(Localization.lang("Automatically set file links"));
Set<BibEntry> changedEntries = new HashSet<>();
// First we try to autoset fields
if (autoSet) {
List<BibEntry> entries = new ArrayList<>(sel);
// Start the automatically setting process:
Runnable r = AutoSetLinks.autoSetLinks(entries, ce, changedEntries, null, panel.getBibDatabaseContext(), null, null);
JabRefExecutorService.INSTANCE.executeAndWait(r);
}
progress += sel.size() * weightAutoSet;
panel.frame().setProgressBarValue(progress);
// The following loop checks all external links that are already set.
if (checkExisting) {
boolean removeAllBroken = false;
mainLoop: for (BibEntry aSel : sel) {
panel.frame().setProgressBarValue(progress++);
final Optional<String> old = aSel.getFieldOptional(FieldName.FILE);
// Check if a extension is set:
if (old.isPresent() && !(old.get().isEmpty())) {
FileListTableModel tableModel = new FileListTableModel();
tableModel.setContentDontGuessTypes(old.get());
// We need to specify which directories to search in for Util.expandFilename:
List<String> dirsS = panel.getBibDatabaseContext().getFileDirectory();
List<File> dirs = new ArrayList<>();
for (String dirs1 : dirsS) {
dirs.add(new File(dirs1));
}
for (int j = 0; j < tableModel.getRowCount(); j++) {
FileListEntry flEntry = tableModel.getEntry(j);
// See if the link looks like an URL:
boolean httpLink = flEntry.link.toLowerCase(Locale.ENGLISH).startsWith("http");
if (httpLink) {
continue; // Don't check the remote file.
// TODO: should there be an option to check remote links?
}
// A variable to keep track of whether this link gets deleted:
boolean deleted = false;
// Get an absolute path representation:
Optional<File> file = FileUtil.expandFilename(flEntry.link, dirsS);
if ((!file.isPresent()) || !file.get().exists()) {
int answer;
if (removeAllBroken) {
answer = 2; // We should delete this link.
} else {
answer = JOptionPane.showOptionDialog(panel.frame(),
Localization.lang("<HTML>Could not find file '%0'<BR>linked from entry '%1'</HTML>",
flEntry.link,
aSel.getCiteKeyOptional().orElse(Localization.lang("undefined"))),
Localization.lang("Broken link"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, brokenLinkOptions, brokenLinkOptions[0]
);
}
switch (answer) {
case 1:
// Assign new file.
FileListEntryEditor flEditor = new FileListEntryEditor
(panel.frame(), flEntry, false, true, panel.getBibDatabaseContext());
flEditor.setVisible(true, true);
break;
case 2:
// Clear field:
tableModel.removeEntry(j);
deleted = true; // Make sure we don't investigate this link further.
j--; // Step back in the iteration, because we removed an entry.
break;
case 3:
// Clear field:
tableModel.removeEntry(j);
deleted = true; // Make sure we don't investigate this link further.
j--; // Step back in the iteration, because we removed an entry.
removeAllBroken = true; // Notify for further cases.
break;
default:
// Cancel
break mainLoop;
}
}
// Unless we deleted this link, see if its file type is recognized:
if (!deleted && flEntry.type.isPresent()
&& (flEntry.type.get() instanceof UnknownExternalFileType)) {
String[] options = new String[] {
Localization.lang("Define '%0'", flEntry.type.get().getName()),
Localization.lang("Change file type"),
Localization.lang("Cancel")};
String defOption = options[0];
int answer = JOptionPane.showOptionDialog(panel.frame(), Localization.lang("One or more file links are of the type '%0', which is undefined. What do you want to do?",
flEntry.type.get().getName()),
Localization.lang("Undefined file type"), JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, defOption
);
if (answer == JOptionPane.CANCEL_OPTION) {
// User doesn't want to handle this unknown link type.
} else if (answer == JOptionPane.YES_OPTION) {
// User wants to define the new file type. Show the dialog:
ExternalFileType newType = new ExternalFileType(flEntry.type.get().getName(), "", "",
"", "new", IconTheme.JabRefIcon.FILE.getSmallIcon());
ExternalFileTypeEntryEditor editor = new ExternalFileTypeEntryEditor(panel.frame(), newType);
editor.setVisible(true);
if (editor.okPressed()) {
// Get the old list of types, add this one, and update the list in prefs:
List<ExternalFileType> fileTypes = new ArrayList<>(
ExternalFileTypes.getInstance().getExternalFileTypeSelection());
fileTypes.add(newType);
Collections.sort(fileTypes);
ExternalFileTypes.getInstance().setExternalFileTypes(fileTypes);
panel.getMainTable().repaint();
}
} else {
// User wants to change the type of this link.
// First get a model of all file links for this entry:
FileListEntryEditor editor = new FileListEntryEditor
(panel.frame(), flEntry, false, true, panel.getBibDatabaseContext());
editor.setVisible(true, false);
}
}
}
if (!tableModel.getStringRepresentation().equals(old.orElse(null))) {
// The table has been modified. Store the change:
String toSet = tableModel.getStringRepresentation();
if (toSet.isEmpty()) {
ce.addEdit(new UndoableFieldChange(aSel, FieldName.FILE, old.orElse(null), null));
aSel.clearField(FieldName.FILE);
} else {
ce.addEdit(new UndoableFieldChange(aSel, FieldName.FILE, old.orElse(null), toSet));
aSel.setField(FieldName.FILE, toSet);
}
changedEntries.add(aSel);
}
}
}
}
if (!changedEntries.isEmpty()) {
// Add the undo edit:
ce.end();
panel.getUndoManager().addEdit(ce);
panel.markBaseChanged();
entriesChangedCount = changedEntries.size();
}
}
@Override
public void update() {
if (!goOn) {
return;
}
panel.output(Localization.lang("Finished synchronizing file links. Entries changed: %0.",
String.valueOf(entriesChangedCount)));
panel.frame().setProgressBarVisible(false);
if (entriesChangedCount > 0) {
panel.markBaseChanged();
}
}
static class OptionsDialog extends JDialog {
private final JButton ok = new JButton(Localization.lang("OK"));
private final JButton cancel = new JButton(Localization.lang("Cancel"));
private boolean canceled = true;
private final BibDatabaseContext databaseContext;
private final JRadioButton autoSetUnset = new JRadioButton(Localization.lang("Automatically set file links")
+ ". " + Localization.lang("Do not overwrite existing links."), true);
private final JRadioButton autoSetAll = new JRadioButton(Localization.lang("Automatically set file links")
+ ". " + Localization.lang("Allow overwriting existing links."), false);
private final JRadioButton autoSetNone = new JRadioButton(Localization.lang("Do not automatically set"), false);
private final JCheckBox checkLinks = new JCheckBox(Localization.lang("Check existing file links"), true);
public OptionsDialog(JFrame parent, BibDatabaseContext databaseContext) {
super(parent, Localization.lang("Synchronize file links"), true);
this.databaseContext = databaseContext;
ok.addActionListener(e -> {
canceled = false;
dispose();
});
Action closeAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
};
cancel.addActionListener(closeAction);
InputMap im = cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = cancel.getActionMap();
im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
am.put("close", closeAction);
ButtonGroup bg = new ButtonGroup();
bg.add(autoSetUnset);
bg.add(autoSetNone);
bg.add(autoSetAll);
FormLayout layout = new FormLayout("fill:pref",
"pref, 2dlu, pref, 2dlu, pref, pref, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref");
FormBuilder builder = FormBuilder.create().layout(layout);
JLabel description = new JLabel("<HTML>"
+ Localization
.lang("Attempt to automatically set file links for your entries. Automatically setting works if "
+ "a file in your file directory<BR>or a subdirectory is named identically to an entry's BibTeX key, plus extension.")
+ "</HTML>");
builder.addSeparator(Localization.lang("Automatically set file links")).xy(1, 1);
builder.add(description).xy(1, 3);
builder.add(autoSetUnset).xy(1, 5);
builder.add(autoSetAll).xy(1, 6);
builder.add(autoSetNone).xy(1, 7);
builder.addSeparator(Localization.lang("Check links")).xy(1, 9);
description = new JLabel("<HTML>"
+ Localization
.lang("This makes JabRef look up each file link and check if the file exists. If not, you will be given options<BR>to resolve the problem.")
+ "</HTML>");
builder.add(description).xy(1, 11);
builder.add(checkLinks).xy(1, 13);
builder.addSeparator("").xy(1, 15);
JPanel main = builder.getPanel();
main.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
bb.addButton(ok);
bb.addButton(cancel);
bb.addGlue();
getContentPane().add(main, BorderLayout.CENTER);
getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
pack();
}
@Override
public void setVisible(boolean visible) {
if (visible) {
canceled = true;
}
List<String> dirs = databaseContext.getFileDirectory();
if (dirs.isEmpty()) {
autoSetNone.setSelected(true);
autoSetNone.setEnabled(false);
autoSetAll.setEnabled(false);
autoSetUnset.setEnabled(false);
} else {
autoSetNone.setEnabled(true);
autoSetAll.setEnabled(true);
autoSetUnset.setEnabled(true);
}
new FocusRequester(ok);
super.setVisible(visible);
}
public boolean isAutoSetNone() {
return autoSetNone.isSelected();
}
public boolean isCheckLinks() {
return checkLinks.isSelected();
}
public boolean canceled() {
return canceled;
}
}
}
| gpl-2.0 |
qoswork/opennmszh | integrations/opennms-link-provisioning-adapter/src/main/java/org/opennms/netmgt/provision/adapters/link/DefaultNodeLinkService.java | 10107 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2009-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.provision.adapters.link;
import static org.opennms.core.utils.LogUtils.debugf;
import static org.opennms.core.utils.LogUtils.infof;
import static org.opennms.core.utils.LogUtils.warnf;
import java.util.Collection;
import java.util.Date;
import org.hibernate.criterion.Restrictions;
import org.opennms.core.utils.BeanUtils;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.netmgt.dao.DataLinkInterfaceDao;
import org.opennms.netmgt.dao.LinkStateDao;
import org.opennms.netmgt.dao.MonitoredServiceDao;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.model.DataLinkInterface;
import org.opennms.netmgt.model.OnmsCriteria;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsLinkState;
import org.opennms.netmgt.model.OnmsLinkState.LinkState;
import org.opennms.netmgt.model.OnmsMonitoredService;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.events.EventForwarder;
import org.opennms.netmgt.provision.adapters.link.endpoint.dao.EndPointConfigurationDao;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
@Transactional
/**
* <p>DefaultNodeLinkService class.</p>
*
* @author ranger
* @version $Id: $
*/
public class DefaultNodeLinkService implements NodeLinkService, InitializingBean {
@Autowired
private NodeDao m_nodeDao;
@Autowired
private DataLinkInterfaceDao m_dataLinkDao;
@Autowired
private MonitoredServiceDao m_monitoredServiceDao;
@Autowired
private EndPointConfigurationDao m_endPointConfigDao;
@Autowired
private LinkStateDao m_linkStateDao;
@Autowired
@Qualifier("transactionAware")
private EventForwarder m_eventForwarder;
@Override
public void afterPropertiesSet() throws Exception {
BeanUtils.assertAutowiring(this);
}
/** {@inheritDoc} */
@Transactional
public void saveLinkState(OnmsLinkState state) {
debugf(this, "saving LinkState %s", state.getLinkState());
m_linkStateDao.saveOrUpdate(state);
m_linkStateDao.flush();
}
/** {@inheritDoc} */
@Transactional
public void createLink(final int nodeParentId, final int nodeId) {
infof(this, "adding link between node: %d and node: %d", nodeParentId, nodeId);
final OnmsNode parentNode = m_nodeDao.get(nodeParentId);
Assert.notNull(parentNode, "node with id: " + nodeParentId + " does not exist");
final OnmsNode node = m_nodeDao.get(nodeId);
Assert.notNull(node, "node with id: " + nodeId + " does not exist");
final OnmsCriteria criteria = new OnmsCriteria(DataLinkInterface.class);
criteria.createAlias("node", "node", OnmsCriteria.LEFT_JOIN);
criteria.add(Restrictions.eq("node.id", nodeId));
criteria.add(Restrictions.eq("nodeParentId", nodeParentId));
final Collection<DataLinkInterface> dataLinkInterface = m_dataLinkDao.findMatching(criteria);
DataLinkInterface dli = null;
if (dataLinkInterface.size() > 1) {
warnf(this, "more than one data link interface exists for nodes %d and %d", nodeParentId, nodeId);
return;
} else if (dataLinkInterface.size() > 0) {
dli = dataLinkInterface.iterator().next();
infof(this, "link between nodes %d and %d already exists", nodeParentId, nodeId);
} else {
dli = new DataLinkInterface();
dli.setNode(node);
dli.setNodeParentId(nodeParentId);
dli.setIfIndex(getPrimaryIfIndexForNode(node));
dli.setParentIfIndex(getPrimaryIfIndexForNode(parentNode));
infof(this, "creating new link between nodes %d and %d", nodeParentId, nodeId);
}
OnmsLinkState onmsLinkState = null;
if (dli.getId() != null) {
onmsLinkState = m_linkStateDao.findByDataLinkInterfaceId(dli.getId());
}
if (onmsLinkState == null) {
onmsLinkState = new OnmsLinkState();
}
onmsLinkState.setDataLinkInterface(dli);
Boolean nodeParentEndPoint = getEndPointStatus(nodeParentId);
Boolean nodeEndPoint = getEndPointStatus(nodeId);
LinkState state = LinkState.LINK_UP;
LinkEventSendingStateTransition transition = new LinkEventSendingStateTransition(dli, m_eventForwarder, this);
if (nodeParentEndPoint == null) {
state = state.parentNodeEndPointDeleted(transition);
} else if (!nodeParentEndPoint) {
state = state.parentNodeDown(transition);
}
if (nodeEndPoint == null) {
state = state.nodeEndPointDeleted(transition);
} else if (!nodeEndPoint) {
state = state.nodeDown(null);
}
dli.setStatus(state.getDataLinkInterfaceStateType());
onmsLinkState.setLinkState(state);
dli.setLastPollTime(new Date());
dli.setLinkTypeId(777);
m_dataLinkDao.save(dli);
m_linkStateDao.save(onmsLinkState);
m_dataLinkDao.flush();
m_linkStateDao.flush();
}
private int getPrimaryIfIndexForNode(OnmsNode node) {
if(node.getPrimaryInterface() != null && node.getPrimaryInterface().getIfIndex() != null){
return node.getPrimaryInterface().getIfIndex();
}else{
return -1;
}
}
/** {@inheritDoc} */
@Transactional(readOnly=true)
public Integer getNodeId(String endPoint) {
if (endPoint == null){
return null;
}
Collection<OnmsNode> nodes = m_nodeDao.findByLabel(endPoint);
if(nodes.size() > 0){
return nodes.iterator().next().getId();
}
return null;
}
/** {@inheritDoc} */
@Transactional(readOnly=true)
public String getNodeLabel(int nodeId) {
OnmsNode node = m_nodeDao.get(nodeId);
if(node != null){
return node.getLabel();
}
return null;
}
/** {@inheritDoc} */
@Transactional(readOnly=true)
public Collection<DataLinkInterface> getLinkContainingNodeId(int nodeId) {
OnmsCriteria criteria = new OnmsCriteria(DataLinkInterface.class);
criteria.createAlias("node", "node", OnmsCriteria.LEFT_JOIN);
criteria.add(Restrictions.or(
Restrictions.eq("node.id", nodeId),
Restrictions.eq("nodeParentId", nodeId)
));
return m_dataLinkDao.findMatching(criteria);
}
/** {@inheritDoc} */
@Transactional(readOnly=true)
public OnmsLinkState getLinkStateForInterface(DataLinkInterface dataLinkInterface) {
return m_linkStateDao.findByDataLinkInterfaceId(dataLinkInterface.getId());
}
/** {@inheritDoc} */
@Transactional
public void updateLinkStatus(int nodeParentId, int nodeId, String status) {
OnmsCriteria criteria = new OnmsCriteria(DataLinkInterface.class);
criteria.createAlias("node", "node", OnmsCriteria.LEFT_JOIN);
criteria.add(Restrictions.eq("node.id", nodeId));
criteria.add(Restrictions.eq("nodeParentId", nodeParentId));
Collection<DataLinkInterface> dataLinkInterface = m_dataLinkDao.findMatching(criteria);
if(dataLinkInterface.size() > 0){
DataLinkInterface dataLink = dataLinkInterface.iterator().next();
dataLink.setStatus(status);
m_dataLinkDao.update(dataLink);
m_dataLinkDao.flush();
}
}
/** {@inheritDoc} */
@Transactional(readOnly=true)
public String getPrimaryAddress(int nodeId) {
OnmsNode node = m_nodeDao.get(nodeId);
OnmsIpInterface primaryInterface = node.getPrimaryInterface();
if(node != null && primaryInterface != null) {
return InetAddressUtils.str(primaryInterface.getIpAddress());
}
return null;
}
/** {@inheritDoc} */
@Transactional(readOnly=true)
public boolean nodeHasEndPointService(int nodeId) {
OnmsMonitoredService endPointService = m_monitoredServiceDao.getPrimaryService(nodeId, m_endPointConfigDao.getValidator().getServiceName());
return endPointService == null ? false : true;
}
/** {@inheritDoc} */
@Transactional(readOnly=true)
public Boolean getEndPointStatus(int nodeId) {
OnmsMonitoredService endPointService = m_monitoredServiceDao.getPrimaryService(nodeId, m_endPointConfigDao.getValidator().getServiceName());
if (endPointService == null) {
return null;
}
// want true to be UP, not DOWN
return !endPointService.isDown();
}
}
| gpl-2.0 |
iKlipse/primeidea | ip-hook/src/main/java/za/co/idea/ip/hook/model/IpGroupClp.java | 13062 | package za.co.idea.ip.hook.model;
import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.model.BaseModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import za.co.idea.ip.hook.service.ClpSerializer;
import za.co.idea.ip.hook.service.IpGroupLocalServiceUtil;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class IpGroupClp extends BaseModelImpl<IpGroup> implements IpGroup {
/**
*
*/
private static final long serialVersionUID = 6692217882935061903L;
private long _groupId;
private long _groupAdminId;
private long _groupParentId;
private String _groupName;
private String _groupStatus;
private String _groupEmail;
private String _groupIsCore;
private BaseModel<?> _ipGroupRemoteModel;
public IpGroupClp() {
}
@Override
public Class<?> getModelClass() {
return IpGroup.class;
}
@Override
public String getModelClassName() {
return IpGroup.class.getName();
}
@Override
public long getPrimaryKey() {
return _groupId;
}
@Override
public void setPrimaryKey(long primaryKey) {
setGroupId(primaryKey);
}
@Override
public Serializable getPrimaryKeyObj() {
return _groupId;
}
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj) {
setPrimaryKey(((Long) primaryKeyObj).longValue());
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("groupId", getGroupId());
attributes.put("groupAdminId", getGroupAdminId());
attributes.put("groupParentId", getGroupParentId());
attributes.put("groupName", getGroupName());
attributes.put("groupStatus", getGroupStatus());
attributes.put("groupEmail", getGroupEmail());
attributes.put("groupIsCore", getGroupIsCore());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Long groupId = (Long) attributes.get("groupId");
if (groupId != null) {
setGroupId(groupId);
}
Long groupAdminId = (Long) attributes.get("groupAdminId");
if (groupAdminId != null) {
setGroupAdminId(groupAdminId);
}
Long groupParentId = (Long) attributes.get("groupParentId");
if (groupParentId != null) {
setGroupParentId(groupParentId);
}
String groupName = (String) attributes.get("groupName");
if (groupName != null) {
setGroupName(groupName);
}
String groupStatus = (String) attributes.get("groupStatus");
if (groupStatus != null) {
setGroupStatus(groupStatus);
}
String groupEmail = (String) attributes.get("groupEmail");
if (groupEmail != null) {
setGroupEmail(groupEmail);
}
String groupIsCore = (String) attributes.get("groupIsCore");
if (groupIsCore != null) {
setGroupIsCore(groupIsCore);
}
}
@Override
public long getGroupId() {
return _groupId;
}
@Override
public void setGroupId(long groupId) {
_groupId = groupId;
if (_ipGroupRemoteModel != null) {
try {
Class<?> clazz = _ipGroupRemoteModel.getClass();
Method method = clazz.getMethod("setGroupId", long.class);
method.invoke(_ipGroupRemoteModel, groupId);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getGroupAdminId() {
return _groupAdminId;
}
@Override
public void setGroupAdminId(long groupAdminId) {
_groupAdminId = groupAdminId;
if (_ipGroupRemoteModel != null) {
try {
Class<?> clazz = _ipGroupRemoteModel.getClass();
Method method = clazz.getMethod("setGroupAdminId", long.class);
method.invoke(_ipGroupRemoteModel, groupAdminId);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getGroupParentId() {
return _groupParentId;
}
@Override
public void setGroupParentId(long groupParentId) {
_groupParentId = groupParentId;
if (_ipGroupRemoteModel != null) {
try {
Class<?> clazz = _ipGroupRemoteModel.getClass();
Method method = clazz.getMethod("setGroupParentId", long.class);
method.invoke(_ipGroupRemoteModel, groupParentId);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getGroupName() {
return _groupName;
}
@Override
public void setGroupName(String groupName) {
_groupName = groupName;
if (_ipGroupRemoteModel != null) {
try {
Class<?> clazz = _ipGroupRemoteModel.getClass();
Method method = clazz.getMethod("setGroupName", String.class);
method.invoke(_ipGroupRemoteModel, groupName);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getGroupStatus() {
return _groupStatus;
}
@Override
public void setGroupStatus(String groupStatus) {
_groupStatus = groupStatus;
if (_ipGroupRemoteModel != null) {
try {
Class<?> clazz = _ipGroupRemoteModel.getClass();
Method method = clazz.getMethod("setGroupStatus", String.class);
method.invoke(_ipGroupRemoteModel, groupStatus);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getGroupEmail() {
return _groupEmail;
}
@Override
public void setGroupEmail(String groupEmail) {
_groupEmail = groupEmail;
if (_ipGroupRemoteModel != null) {
try {
Class<?> clazz = _ipGroupRemoteModel.getClass();
Method method = clazz.getMethod("setGroupEmail", String.class);
method.invoke(_ipGroupRemoteModel, groupEmail);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getGroupIsCore() {
return _groupIsCore;
}
@Override
public void setGroupIsCore(String groupIsCore) {
_groupIsCore = groupIsCore;
if (_ipGroupRemoteModel != null) {
try {
Class<?> clazz = _ipGroupRemoteModel.getClass();
Method method = clazz.getMethod("setGroupIsCore", String.class);
method.invoke(_ipGroupRemoteModel, groupIsCore);
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
public BaseModel<?> getIpGroupRemoteModel() {
return _ipGroupRemoteModel;
}
public void setIpGroupRemoteModel(BaseModel<?> ipGroupRemoteModel) {
_ipGroupRemoteModel = ipGroupRemoteModel;
}
public Object invokeOnRemoteModel(String methodName,
Class<?>[] parameterTypes, Object[] parameterValues)
throws Exception {
Object[] remoteParameterValues = new Object[parameterValues.length];
for (int i = 0; i < parameterValues.length; i++) {
if (parameterValues[i] != null) {
remoteParameterValues[i] = ClpSerializer.translateInput(parameterValues[i]);
}
}
Class<?> remoteModelClass = _ipGroupRemoteModel.getClass();
ClassLoader remoteModelClassLoader = remoteModelClass.getClassLoader();
Class<?>[] remoteParameterTypes = new Class[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i].isPrimitive()) {
remoteParameterTypes[i] = parameterTypes[i];
} else {
String parameterTypeName = parameterTypes[i].getName();
remoteParameterTypes[i] = remoteModelClassLoader.loadClass(parameterTypeName);
}
}
Method method = remoteModelClass.getMethod(methodName,
remoteParameterTypes);
Object returnValue = method.invoke(_ipGroupRemoteModel,
remoteParameterValues);
if (returnValue != null) {
returnValue = ClpSerializer.translateOutput(returnValue);
}
return returnValue;
}
@Override
public void persist() throws SystemException {
if (this.isNew()) {
IpGroupLocalServiceUtil.addIpGroup(this);
} else {
IpGroupLocalServiceUtil.updateIpGroup(this);
}
}
@Override
public IpGroup toEscapedModel() {
return (IpGroup) ProxyUtil.newProxyInstance(IpGroup.class.getClassLoader(),
new Class[] { IpGroup.class }, new AutoEscapeBeanHandler(this));
}
@Override
public Object clone() {
IpGroupClp clone = new IpGroupClp();
clone.setGroupId(getGroupId());
clone.setGroupAdminId(getGroupAdminId());
clone.setGroupParentId(getGroupParentId());
clone.setGroupName(getGroupName());
clone.setGroupStatus(getGroupStatus());
clone.setGroupEmail(getGroupEmail());
clone.setGroupIsCore(getGroupIsCore());
return clone;
}
@Override
public int compareTo(IpGroup ipGroup) {
int value = 0;
value = getGroupName().compareTo(ipGroup.getGroupName());
if (value != 0) {
return value;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof IpGroupClp)) {
return false;
}
IpGroupClp ipGroup = (IpGroupClp) obj;
long primaryKey = ipGroup.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
return (int) getPrimaryKey();
}
@Override
public String toString() {
StringBundler sb = new StringBundler(15);
sb.append("{groupId=");
sb.append(getGroupId());
sb.append(", groupAdminId=");
sb.append(getGroupAdminId());
sb.append(", groupParentId=");
sb.append(getGroupParentId());
sb.append(", groupName=");
sb.append(getGroupName());
sb.append(", groupStatus=");
sb.append(getGroupStatus());
sb.append(", groupEmail=");
sb.append(getGroupEmail());
sb.append(", groupIsCore=");
sb.append(getGroupIsCore());
sb.append("}");
return sb.toString();
}
@Override
public String toXmlString() {
StringBundler sb = new StringBundler(25);
sb.append("<model><model-name>");
sb.append("za.co.idea.ip.hook.model.IpGroup");
sb.append("</model-name>");
sb.append(
"<column><column-name>groupId</column-name><column-value><![CDATA[");
sb.append(getGroupId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupAdminId</column-name><column-value><![CDATA[");
sb.append(getGroupAdminId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupParentId</column-name><column-value><![CDATA[");
sb.append(getGroupParentId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupName</column-name><column-value><![CDATA[");
sb.append(getGroupName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupStatus</column-name><column-value><![CDATA[");
sb.append(getGroupStatus());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupEmail</column-name><column-value><![CDATA[");
sb.append(getGroupEmail());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupIsCore</column-name><column-value><![CDATA[");
sb.append(getGroupIsCore());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
}
| gpl-2.0 |
deepakab03/spring-training | spring-2/src/com/perot/training/util/Utils.java | 513 | /**
*
*/
package com.perot.training.util;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.PatternLayout;
/**
* @author abrahade
*
*/
public class Utils {
public static void initLog4j() {
BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("[%t:%c{2}:%L][%d{HH:mm:ss,SSS}] %p %m%n")));
LogManager.getRootLogger().setLevel(Level.INFO);
}
}
| gpl-2.0 |
Chocanto/planetsWars | Souris.java | 1392 | package planetsWars;
import javax.media.opengl.*;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import javax.media.opengl.awt.GLCanvas;
import javax.swing.JFrame;
import com.jogamp.opengl.util.FPSAnimator;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.*;
import java.awt.Robot;
public class Souris implements MouseMotionListener{
GLCanvas canvas;
Scene dessin;
JFrame frame;
Robot robot;
public Souris(){
}
public Souris(JFrame frame, GLCanvas canvas, Scene dessin){
this.canvas=canvas;
this.dessin=dessin;
this.frame=frame;
try {
robot = new Robot();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public void mouseClicked (MouseEvent me) {
}
public void mouseEntered (MouseEvent me) {}
public void mousePressed (MouseEvent me) {
}
public void mouseReleased (MouseEvent me) {
}
public void mouseExited (MouseEvent me) {}
public void mouseMoved (MouseEvent me) {
/*dessin.setPhi(frame.getHeight()/2 - (me.getY()+38));
dessin.setTheta(frame.getWidth()/2 - (me.getX()+10));
robot.mouseMove(frame.getX() + frame.getWidth()/2, frame.getY() + frame.getHeight()/2);*/
}
public void mouseDragged (MouseEvent me) {}
}
| gpl-2.0 |
kainagel/teach-oop | src/main/java/hh_generics/dd_genericMethod/ClassInspector.java | 225 | package hh_generics.dd_genericMethod;
class ClassInspector {
// public <T> void inspect ( T tt ) {
public void inspect ( Object tt ) {
System.out.println ( " instance of class: " + tt.getClass().getName() ) ;
}
} | gpl-2.0 |
jurkov/j-algo-mod | src/org/jalgo/module/app/controller/GraphActionListener.java | 5222 | package org.jalgo.module.app.controller;
import java.awt.geom.Point2D;
import org.jalgo.module.app.controller.undoRedo.UndoManager;
import org.jalgo.module.app.core.dataType.DataType;
import org.jalgo.module.app.core.graph.Edge;
import org.jalgo.module.app.core.graph.Graph;
import org.jalgo.module.app.core.graph.Node;
/**
* This interface is used for notifying changes made in the graph (core,
* <code>GraphComponent</code> or <code>GraphTextComponent</code>) to the
* core and the components which display the graph.
*
*/
public interface GraphActionListener {
/**
* Returns the graph all actions below deal with.
*
* @return the graph of the listener
*/
public Graph getGraph();
/**
* Returns the data type of all edge weights in the graph.
*
* @return the weight data type
*/
public Class<? extends DataType> getDataType();
/**
* Adds <code>newObserver</code> to the listener as observer, notifying it
* of all changes done to the graph (also initiated by itself).
*
* @param newObserver
* the observer to add
*/
public void addGraphObserver(GraphObserver newObserver);
/**
* Provides the mode that says which element is edited.
*/
public enum EditMode {
/**
* No element is currently edited.
*/
NONE,
/**
* A node is edited.
*/
EDITING_NODES,
/**
* A edge is edited.
*/
EDITING_EDGES,
/**
* The weight of an edge is edited.
*/
EDITING_WEIGHT,
};
/**
* Gets the current edit mode.
*
* @return the current edit mode.
*/
public EditMode getEditMode();
/**
* Sets the current edit mode.
*
* @param mode
* the new edit mode.
*/
public void setEditMode(EditMode mode);
/**
* Gets the node that is currently selected.
*
* @return the currently selected node. If no node is selected,
* <code>null</code> is returned.
*/
public Node getSelectedNode();
/**
* Sets the currently selected node.
*
* @param node
* the currently selected node. If no node is selected,
* <code>node</code> has to be set to <code>null</code>.
*/
public void setSelectedNode(Node node);
/**
* Gets the edge that is currently selected.
*
* @return the currently selected edge. If no edge is selected,
* <code>null</code> is returned.
*/
public Edge getSelectedEdge();
/**
* Sets the currently selected edge.
*
* @param edge
* the currently selected edge. If no edge is selected,
* <code>edge</code> has to be set to <code>null</code>.
*/
public void setSelectedEdge(Edge edge);
/**
* Begins grouping of change notifications. Makes only sense when editing
* multiple things.
*
* @see #endEditing()
*/
public void beginEditing();
/**
* Ends grouping of change notifications.
*
* @see #beginEditing()
*/
public void endEditing();
/*
* NODES
*
*/
/**
* Adds a new node to the graph.
*
* @return the new node.
*/
public Node addNode();
/**
* Adds a new node to the graph, setting the given position.
*
* @param position
* the position of the new node
*/
public Node addNode(Point2D position);
/**
* Changes the position of the given node to <code>position</code>.
*
* @param node
* the node to change
* @param position
* the position to set
*/
public void alterNodePosition(Node node, Point2D position);
/**
* Removes the given node from the graph. This also removes all attached
* edges as well.
*
* @param node
* the node to remove
*/
public void removeNode(Node node);
/*
* EDGES
*
*/
/**
* Adds a edge between the given start and end node to the graph.
*
* @param start
* the start node
* @param end
* the end node
*/
public Edge addEdge(Node start, Node end);
/**
* Adds a edge between the given start and end node to the graph, setting
* it's weight to <code>weight</code>.
*
* @param start
* the start node
* @param end
* the end node
* @param weight
* the weight for the new edge
*/
public Edge addEdge(Node start, Node end, DataType weight);
/**
* Changes the weight of the given edge to <code>weight</code>.
*
* @param edge
* the edge to change
* @param weight
* the weight to set
*/
public void alterEdgeWeight(Edge edge, DataType weight);
/**
* Removes the given edge from the graph.
*
* @param edge
* the edge to remove
*/
public void removeEdge(Edge edge);
/**
* Gets the undo manager to provide undo redo actions.
*
* @return The undo manager.
*/
public UndoManager getUndoManager();
/**
* Sets the position of a node before dragging to remember for undo/redo.
*
* @param previousPosition
* the previousPosition to set
*/
public void setPreviousPosition(Point2D previousPosition);
/**
* Method which is called when a dragged node has reached its actual
* position.
*
* @param node The node which was dragged.
* @param point The final position.
*/
public void setFinalNodePosition(Node node, Point2D point);
}
| gpl-2.0 |
dsromero/misCuentas | app/src/main/java/es/pruebas/dsromero/miscuentas/Inicio.java | 1128 | package es.pruebas.dsromero.miscuentas;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class Inicio extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_inicio, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| gpl-2.0 |
callakrsos/Gargoyle | VisualFxVoEditor/src/main/java/com/kyj/fx/voeditor/visual/framework/file/jcifs/DefaultSMBOpen.java | 1369 | /********************************
* 프로젝트 : VisualFxVoEditor
* 패키지 : com.kyj.fx.voeditor.visual.framework.file.jcifs
* 작성일 : 2018. 5. 3.
* 작성자 : KYJ
*******************************/
package com.kyj.fx.voeditor.visual.framework.file.jcifs;
import java.io.File;
import java.io.FileOutputStream;
import com.kyj.fx.commons.utils.FileUtil;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
/**
*
* 기본형으로 파일을 읽기 위한 처리 클래스 <br/>
*
* @author KYJ
*
*/
public class DefaultSMBOpen implements GargoyleSMBOpenExtension, GargoyleSMBOpen {
private SmbFile file;
@Override
public boolean canOpen(SmbFile file) {
try {
return file.isFile();
} catch (SmbException e) {
e.printStackTrace();
}
return false;
}
@Override
public void setOpenFile(SmbFile file) {
this.file = file;
}
@Override
public void open() throws Exception {
String name = this.file.getName();
File tempGagoyle = FileUtil.getTempGagoyle();
File outFile = new File(tempGagoyle, name);
try (SmbFileInputStream in = new SmbFileInputStream(this.file)) {
int temp = -1;
try (FileOutputStream out = new FileOutputStream(outFile, false)) {
while ((temp = in.read()) != -1) {
out.write(temp);
}
}
}
FileUtil.openFile(outFile);
}
}
| gpl-2.0 |
ibnoe/steganography-dalam-file-music-mp3 | stegaMP3/jid3lib-0.5.4/jid3lib-0.5.4/src/org/farng/mp3/filename/AbstractFilenameComposite.java | 2827 | package org.farng.mp3.filename;
import org.farng.mp3.AbstractMP3Tag;
import org.farng.mp3.id3.AbstractID3v2Frame;
import org.farng.mp3.id3.ID3v2_4;
import java.util.Iterator;
/**
* The file name is parsed into a composite with this class as the base composite class.
*
* @author Eric Farng
* @version $Revision: 1.3 $
*/
public abstract class AbstractFilenameComposite {
/**
* Keep a record of the original token that this composite is supposed to represent
*/
private String originalToken = null;
/**
* Creates a new AbstractFilenameComposite object.
*/
protected AbstractFilenameComposite() {
super();
}
/**
* Creates a new AbstractFilenameComposite object.
*/
protected AbstractFilenameComposite(final AbstractFilenameComposite copyObject) {
super();
originalToken = copyObject.originalToken;
}
public abstract void setFrame(AbstractID3v2Frame frame);
/**
* Reconstruct the filename that is represented by this composite.
*
* @return the filename that is represented by this composite.
*/
public abstract String composeFilename();
/**
* Returns an iterator through each <code>FilenameToken</code> in this composite in the correct order for the file
* name.
*
* @return an iterator through each <code>FilenameToken</code> in this composite
*/
public abstract Iterator iterator();
/**
* Match all elements of this composite against the keywords for this class type found in
* <code>TagOptionSingleton</code>. If the <code>FilenameToken</code> matches the keyword, the token's class is
* set.
*
* @param id3v2FrameBodyClass Class of keywords to match against.
*/
public abstract void matchAgainstKeyword(Class id3v2FrameBodyClass);
/**
* Match all elements of this composite against the given tag. If any element of <code>matchTag</code> matches any
* element of this tag's composite, then this tag's composite leaf node's class is set.
*
* @param matchTag Tag to match against
*/
public abstract void matchAgainstTag(AbstractMP3Tag matchTag);
/**
* Sets the original string that this composite represents.
*
* @param originalToken the original string that this composite represents.
*/
public void setOriginalToken(final String originalToken) {
this.originalToken = originalToken;
}
/**
* Get the original string that this composite represents.
*
* @return the original string that this composite represents.
*/
public String getOriginalToken() {
return originalToken;
}
public abstract ID3v2_4 createId3Tag();
} | gpl-2.0 |
lkastler/RDFDistributedSail | src/main/java/de/unikoblenz/west/rdf/distributedsail/middleware/commands/sail/SailRetrievalResponse.java | 1623 | package de.unikoblenz.west.rdf.distributedsail.middleware.commands.sail;
import info.aduna.iteration.CloseableIteration;
import info.aduna.iteration.Iterations;
import java.io.Serializable;
import java.util.List;
import org.openrdf.model.Statement;
import org.openrdf.sail.SailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.unikoblenz.west.rdf.distributedsail.middleware.IntermediateResult;
/**
* TODO add doc
*
* @author lkastler
*/
public class SailRetrievalResponse implements SailResponse, Serializable {
private Logger log = LoggerFactory.getLogger(getClass());
/** */
private static final long serialVersionUID = 1L;
protected final String id;
protected final SailRequest request;
protected final List<Statement> result;
/**
* TODO add doc
*
* @param id
* @param request
* @param result
* @throws SailException
*/
public SailRetrievalResponse(String id, SailRequest request,
CloseableIteration<Statement, SailException> result) throws SailException {
super();
this.id = id;
this.request = request;
this.result = Iterations.asList(result);
log.debug("created");
}
/**
* @return the result
*/
public CloseableIteration<Statement, SailException> getResult() {
return new IntermediateResult<Statement,SailException>(result);
}
/**
* TODO add doc
*/
public SailRequest getRequest() {
return request;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "SailRetrievalResponse [id=" + id + ", request=" + request + ", result="
+ result + "]";
}
}
| gpl-2.0 |
favedit/MoPlatform | mo-3-logic/src/logic-data/org/mo/logic/data/impl/FCpActionImpl.java | 3037 | /*
* @(#)FCpActionImpl.java
*
* Copyright 2008 microbject, All Rights Reserved.
*
*/
package org.mo.logic.data.impl;
import org.mo.com.data.ESqlDataDirection;
import org.mo.com.data.ESqlDataType;
import org.mo.com.data.FSqlProcedure;
import org.mo.com.data.ISqlConnect;
import org.mo.com.data.MSqlConnect;
import org.mo.logic.data.ICpAction;
/**
* <T>数据库逻辑包(CP_ACTION)的代理对象</T>
*
* @author MAOCY
* @version 1.0.1
*/
public class FCpActionImpl
extends MSqlConnect
implements
ICpAction
{
public final String LOGIC_NAME = "CP_ACTION";
public FCpActionImpl(){
}
public FCpActionImpl(ISqlConnect connect){
super(connect);
}
/* (non-Javadoc)
* @see org.mo.logic.data.ICmCityDi(java.lang.Object, java.lang.Object)
*/
@Override
public FSqlProcedure doInsert(Object logic,
Object params){
FSqlProcedure procedure = new FSqlProcedure("Do_Insert");
procedure.setLogicName(LOGIC_NAME);
procedure.createParameter("logic_", logic, ESqlDataType.String, ESqlDataDirection.InOut);
procedure.createParameter("params_", params, ESqlDataType.String, ESqlDataDirection.InOut);
activeConnection().execute(procedure);
return procedure;
}
/* (non-Javadoc)
* @see org.mo.logic.data.ICmCityDi(java.lang.Object, java.lang.Object)
*/
@Override
public FSqlProcedure doUpdate(Object logic,
Object params){
FSqlProcedure procedure = new FSqlProcedure("Do_Update");
procedure.setLogicName(LOGIC_NAME);
procedure.createParameter("logic_", logic, ESqlDataType.String, ESqlDataDirection.InOut);
procedure.createParameter("params_", params, ESqlDataType.String, ESqlDataDirection.InOut);
activeConnection().execute(procedure);
return procedure;
}
/* (non-Javadoc)
* @see org.mo.logic.data.ICmCityDi(java.lang.Object, java.lang.Object)
*/
@Override
public FSqlProcedure doSync(Object logic,
Object params){
FSqlProcedure procedure = new FSqlProcedure("Do_Sync");
procedure.setLogicName(LOGIC_NAME);
procedure.createParameter("logic_", logic, ESqlDataType.String, ESqlDataDirection.InOut);
procedure.createParameter("params_", params, ESqlDataType.String, ESqlDataDirection.InOut);
activeConnection().execute(procedure);
return procedure;
}
/* (non-Javadoc)
* @see org.mo.logic.data.ICmCityDi(java.lang.Object, java.lang.Object)
*/
@Override
public FSqlProcedure doDelete(Object logic,
Object params){
FSqlProcedure procedure = new FSqlProcedure("Do_Delete");
procedure.setLogicName(LOGIC_NAME);
procedure.createParameter("logic_", logic, ESqlDataType.String, ESqlDataDirection.InOut);
procedure.createParameter("params_", params, ESqlDataType.String, ESqlDataDirection.InOut);
activeConnection().execute(procedure);
return procedure;
}
}
| gpl-2.0 |
luismr/lab | job-applications/crossover/tickets-web/src/test/java/com/luismachadoreis/tickets/web/model/UserAssert.java | 4355 | package com.luismachadoreis.tickets.web.model;
import org.fest.assertions.Assertions;
import org.fest.assertions.GenericAssert;
import com.luismachadoreis.tickets.web.model.Role;
import com.luismachadoreis.tickets.web.model.AuthenticatorService;
import com.luismachadoreis.tickets.web.model.User;
/**
* @author Luis Machado Reis
*/
public class UserAssert extends GenericAssert<UserAssert, User> {
protected UserAssert(User actual) {
super(UserAssert.class, actual);
}
public static UserAssert assertThat(User actual) {
return new UserAssert(actual);
}
public UserAssert hasEmail(String email) {
isNotNull();
String errorMessage = String.format(
"Expected email to be <%s> but was <%s>",
email,
actual.getEmail()
);
Assertions.assertThat(actual.getEmail())
.overridingErrorMessage(errorMessage)
.isEqualTo(email);
return this;
}
public UserAssert hasFirstName(String firstName) {
isNotNull();
String errorMessage = String.format(
"Expected first name to be <%s> but was <%s>",
firstName,
actual.getFirstName()
);
Assertions.assertThat(actual.getFirstName())
.overridingErrorMessage(errorMessage)
.isEqualTo(firstName);
return this;
}
public UserAssert hasLastName(String lastName) {
isNotNull();
String errorMessage = String.format(
"Expected last name to be <%s> but was <%s>",
lastName,
actual.getLastName()
);
Assertions.assertThat(actual.getLastName())
.overridingErrorMessage(errorMessage)
.isEqualTo(lastName);
return this;
}
public UserAssert hasNoId() {
isNotNull();
String errorMessage = String.format(
"Expected id to be <null> but was <%d>",
actual.getId()
);
Assertions.assertThat(actual.getId())
.overridingErrorMessage(errorMessage)
.isNull();
return this;
}
public UserAssert hasNoPassword() {
isNotNull();
String errorMessage = String.format(
"Expected password to be <null> but was <%s>",
actual.getPassword()
);
Assertions.assertThat(actual.getPassword())
.overridingErrorMessage(errorMessage)
.isNull();
return this;
}
public UserAssert hasPassword(String password) {
isNotNull();
String errorMessage = String.format(
"Expected password to be <%s> but was <%s>",
password,
actual.getPassword()
);
Assertions.assertThat(actual.getPassword())
.overridingErrorMessage(errorMessage)
.isEqualTo(password);
return this;
}
public UserAssert isRegisteredByUsingNormalRegistration() {
isNotNull();
String errorMessage = String.format(
"Expected signInProvider to be <null> but was <%s>",
actual.getSignInProvider()
);
Assertions.assertThat(actual.getSignInProvider())
.overridingErrorMessage(errorMessage)
.isNull();
return this;
}
public UserAssert isRegisteredByUsingSignInProvider(AuthenticatorService signInProvider) {
isNotNull();
String errorMessage = String.format(
"Expected signInProvider to be <%s> but was <%s>",
signInProvider,
actual.getSignInProvider()
);
Assertions.assertThat(actual.getSignInProvider())
.overridingErrorMessage(errorMessage)
.isEqualTo(signInProvider);
return this;
}
public UserAssert isRegisteredUser() {
isNotNull();
String errorMessage = String.format(
"Expected role to be <ROLE_USER> but was <%s>",
actual.getRole()
);
Assertions.assertThat(actual.getRole())
.overridingErrorMessage(errorMessage)
.isEqualTo(Role.ROLE_USER);
return this;
}
}
| gpl-2.0 |
mniami/burkia | AndroidApp/data/src/test/java/pl/guideme/data/ExampleUnitTest.java | 393 | package pl.guideme.data;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | gpl-2.0 |
alarulrajan/CodeFest | test/com/technoetic/xplanner/acceptance/web/MailTester.java | 11332 | /*
* Copyright (c) 2005 Your Corporation. All Rights Reserved.
*/
package com.technoetic.xplanner.acceptance.web;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import junit.framework.Assert;
import org.apache.commons.lang.StringUtils;
import com.dumbster.smtp.SimpleSmtpServer;
import com.dumbster.smtp.SmtpMessage;
import com.technoetic.xplanner.XPlannerProperties;
/**
* The Class MailTester.
*/
public class MailTester {
/** The current day offset. */
private int currentDayOffset = 0;
/** The tester. */
private XPlannerWebTester tester;
/** Gets the current day offset.
*
* @return the current day offset
*/
public int getCurrentDayOffset() {
return currentDayOffset;
}
/** The Class Email.
*/
public static class Email {
/** The subject. */
public String subject;
/** The recipients. */
public String[] recipients;
/** The from. */
public String from;
/** The body elements. */
public List bodyElements;
/** Instantiates a new email.
*
* @param from
* the from
* @param recipients
* the recipients
* @param subject
* the subject
* @param bodyElements
* the body elements
*/
public Email(String from, String[] recipients, String subject, List bodyElements){
this.subject = subject;
this.recipients = recipients;
this.from = from;
this.bodyElements = bodyElements;
}
/** Instantiates a new email.
*
* @param from
* the from
* @param subject
* the subject
* @param bodyElements
* the body elements
*/
public Email(String from, String subject, List bodyElements){
this(from, new String[0], subject, bodyElements);
}
/** Checks if is equal.
*
* @param message
* the message
* @return true, if is equal
*/
public boolean isEqual(SmtpMessage message) {
if (!isSubjectEqual(message)) return false;
if (!isFromAddressEqual(message)) return false;
if (!isBodyContainingElements(message)) return false;
return isRecipientsEqual(message);
}
/** Checks if is recipients equal.
*
* @param message
* the message
* @return true, if is recipients equal
*/
private boolean isRecipientsEqual(SmtpMessage message) {
List messageRecipients = new ArrayList();
messageRecipients.addAll(Arrays.asList(message.getHeaderValues("To")));
messageRecipients.addAll(Arrays.asList(message.getHeaderValues("Cc")));
messageRecipients.addAll(Arrays.asList(message.getHeaderValues("Bcc")));
return messageRecipients.containsAll(Arrays.asList(recipients));
}
/** Checks if is body containing elements.
*
* @param message
* the message
* @return true, if is body containing elements
*/
private boolean isBodyContainingElements(SmtpMessage message) {
String trimmedBody = StringUtils.deleteWhitespace(message.getBody());
for (Iterator iterator = bodyElements.iterator(); iterator.hasNext();) {
String element = (String) iterator.next();
if (!StringUtils.contains(trimmedBody,
StringUtils.deleteWhitespace(element))) {
return false;
}
}
return true;
}
/** Checks if is from address equal.
*
* @param message
* the message
* @return true, if is from address equal
*/
protected boolean isFromAddressEqual(SmtpMessage message) {
return StringUtils.equals(from, message.getHeaderValue("From"));
}
/** Checks if is subject equal.
*
* @param message
* the message
* @return true, if is subject equal
*/
private boolean isSubjectEqual(SmtpMessage message) {
return StringUtils.equals(subject, message.getHeaderValue("Subject"));
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
String result = "Email(from=" + from + ", " + "to={";
for (int i=0; i<recipients.length; i++){
if (i>0) result+=",";
result+=recipients[i];
}
result+="}"+", subject=" + subject + ", body includes {\n";
for (int i=0; i<bodyElements.size(); i++){
if (i>0) result+=",\n";
result+=bodyElements.get(i);
}
result+="\n})";
return result;
}
}
/** The smtp server. */
private SimpleSmtpServer smtpServer;
/** Instantiates a new mail tester.
*
* @param tester
* the tester
*/
public MailTester(XPlannerWebTester tester) {
this.tester = tester;
}
/** Assert number of email received by.
*
* @param expectedNumberOfEmailReceived
* the expected number of email received
* @param receiver
* the receiver
*/
public void assertNumberOfEmailReceivedBy(int expectedNumberOfEmailReceived, String receiver) {
int cnt = 0;
for (Iterator iterator = smtpServer.getReceivedEmail(); iterator.hasNext();) {
SmtpMessage message = (SmtpMessage) iterator.next();
if (Arrays.asList(message.getHeaderValues("To")).contains(receiver)) {
cnt++;
}
}
if (expectedNumberOfEmailReceived != cnt) {
String message = "number of email sent to "+ receiver +" expected " + expectedNumberOfEmailReceived + " was " +
cnt +"\n messages received=" + getAllEmailsReceived();
Assert.fail(message);
}
}
/** Assert email has not been received.
*
* @param email
* the email
* @throws InterruptedException
* the interrupted exception
*/
public void assertEmailHasNotBeenReceived(Email email) throws InterruptedException {
boolean isFound = hasEmailBeenReceived(email);
Assert.assertFalse("A message " + email + " has been sent", isFound);
}
/** Assert email has not been received.
*
* @param recipient
* the recipient
* @param email
* the email
* @throws InterruptedException
* the interrupted exception
*/
public void assertEmailHasNotBeenReceived(String recipient, Email email) throws InterruptedException {
email.recipients = new String[]{recipient};
assertEmailHasNotBeenReceived(email);
}
/** Assert email has been received.
*
* @param expectedEmail
* the expected email
* @throws InterruptedException
* the interrupted exception
*/
public void assertEmailHasBeenReceived(Email expectedEmail) throws InterruptedException {
boolean isFound = hasEmailBeenReceived(expectedEmail);
if (!isFound) {
Assert.fail("A message " + expectedEmail + " not found in \n" + getAllEmailsReceived());
}
}
/** Assert email has been received.
*
* @param recipient
* the recipient
* @param email
* the email
* @throws InterruptedException
* the interrupted exception
*/
public void assertEmailHasBeenReceived(String recipient, Email email) throws InterruptedException {
email.recipients = new String[] {recipient};
assertEmailHasBeenReceived(email);
}
/** The Constant SECOND. */
public static final int SECOND = 2;
/** Checks for email been received.
*
* @param email
* the email
* @return true, if successful
* @throws InterruptedException
* the interrupted exception
*/
private boolean hasEmailBeenReceived(Email email) throws InterruptedException {
int timeout = 4 * SECOND;
while (--timeout > 0) {
Thread.sleep(500);
if (hasEmailArrived(email)) return true;
}
return false;
}
/** Checks for email arrived.
*
* @param email
* the email
* @return true, if successful
*/
private boolean hasEmailArrived(Email email) {
for (Iterator it = smtpServer.getReceivedEmail(); it.hasNext();) {
SmtpMessage message = (SmtpMessage) it.next();
if (email.isEqual(message)) return true;
}
return false;
}
/** Sets the up.
*
* @throws Exception
* the exception
*/
public void setUp() throws Exception{
currentDayOffset = 0;
startSmtp();
}
/** Start smtp.
*
* @throws InterruptedException
* the interrupted exception
*/
private void startSmtp() throws InterruptedException {
int port = Integer.parseInt(new XPlannerProperties().getProperty("xplanner.mail.smtp.port"));
smtpServer = new SimpleSmtpServer(port);
Thread t = new Thread(smtpServer);
tryStartNTimes(t, 10);
}
/** Try start n times.
*
* @param t
* the t
* @param tries
* the tries
* @throws InterruptedException
* the interrupted exception
*/
private void tryStartNTimes(Thread t, int tries) throws InterruptedException {
while (tries > 0) {
try {
t.start();
break;
} catch (Exception e) {
Thread.sleep(100);
tries--;
}
}
}
/** Tear down.
*/
public void tearDown() {
currentDayOffset = 0;
stopSmtp();
}
/** Stop smtp.
*/
private void stopSmtp() {
if (smtpServer != null && !smtpServer.isStopped()) {
smtpServer.stop();
}
}
/** Reset smtp.
*
* @throws Exception
* the exception
*/
public void resetSmtp() throws Exception {
stopSmtp();
startSmtp();
}
/** Gets the all emails received.
*
* @return the all emails received
*/
public String getAllEmailsReceived() {
String result = "{\n";
Iterator email = smtpServer.getReceivedEmail();
while (email.hasNext()) {
SmtpMessage message = (SmtpMessage) email.next();
if (email.hasNext()) {
result += " " + message + "\n###########################################################\n";
}
}
result += "}";
return result;
}
/** Move current day and send email.
*
* @param days
* the days
* @throws UnsupportedEncodingException
* the unsupported encoding exception
*/
public void moveCurrentDayAndSendEmail(int days) throws UnsupportedEncodingException {
tester.moveCurrentDay(days);
tester.executeTask("/do/edit/missingTimeEntryNotification");
}
} | gpl-2.0 |
dbt/jamm | src/backend/test/java/jamm/util/CaseInsensitiveStringSetTest.java | 2976 | /*
* Jamm
* Copyright (C) 2002 Dave Dribin and Keith Garner
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jamm.util;
import java.util.Set;
import java.util.Arrays;
import junit.framework.TestCase;
/**
* Tests the {@link CaseInsensitiveStringSet} class.
*/
public class CaseInsensitiveStringSetTest extends TestCase
{
/**
* Standard JUnit constructor.
*
* @param name Name.
*/
public CaseInsensitiveStringSetTest(String name)
{
super(name);
}
/**
* Creates a default set.
*/
protected void setUp()
{
mSet = new CaseInsensitiveStringSet();
}
/**
* Tests adding items to the set.
*/
public void testAdd()
{
assertTrue("Checking add succeeds", mSet.add("apple"));
assertTrue("Checking add fails", !mSet.add("APPLE"));
}
/**
* tests removing items from the set.
*/
public void testRemove()
{
mSet.add("MANGO");
mSet.add("apple");
mSet.add("Orange");
assertTrue("Checking remove succeeds", mSet.remove("APPLE"));
assertTrue("Checking remove succeeds", mSet.remove("mango"));
assertTrue("Checking remove succeeds", mSet.remove("orange"));
assertTrue("Checking remove fails", !mSet.remove("apple"));
}
/**
* Tests checking for items.
*/
public void testContains()
{
mSet.add("string");
assertTrue("Checking lower case", mSet.contains("string"));
assertTrue("Checking upper case", mSet.contains("STRING"));
assertTrue("Checking mixed case", mSet.contains("StRiNg"));
}
/**
* Tests the iterator by converting to an array.
*/
public void testToArray()
{
mSet.add("MANGO");
mSet.add("apple");
mSet.add("Orange");
mSet.add("APPLE");
String[] fruits = (String[]) mSet.toArray(new String[0]);
assertEquals("Checking array length", 3, fruits.length);
Arrays.sort(fruits, String.CASE_INSENSITIVE_ORDER);
assertEquals("Checking element 0", "apple", fruits[0]);
assertEquals("Checking element 1", "MANGO", fruits[1]);
assertEquals("Checking element 2", "Orange", fruits[2]);
}
/** The default set. */
private Set mSet;
}
| gpl-2.0 |
smarr/Truffle | regex/src/com.oracle.truffle.regex/src/com/oracle/truffle/regex/tregex/automaton/TransitionSet.java | 3114 | /*
* Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.regex.tregex.automaton;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
/**
* Represents a set of NFA transitions to be used in {@link TransitionBuilder}.
*/
public class TransitionSet<SI extends StateIndex<? super S>, S extends AbstractState<S, T>, T extends AbstractTransition<S, T>> {
private final T[] transitions;
private final StateSet<SI, S> targetStateSet;
public TransitionSet(T[] transitions, StateSet<SI, S> targetStateSet) {
this.transitions = transitions;
this.targetStateSet = targetStateSet;
}
public T[] getTransitions() {
return transitions;
}
public StateSet<SI, S> getTargetStateSet() {
return targetStateSet;
}
public boolean isEmpty() {
return size() == 0;
}
public int size() {
return transitions.length;
}
public T getTransition(int i) {
return transitions[i];
}
@TruffleBoundary
@Override
public String toString() {
return targetStateSet.toString();
}
}
| gpl-2.0 |
DIY-green/AndroidStudyDemo | DesignPatternStudy/src/main/java/com/cheng/zenofdesignpatterns/patterns/adapter/mmssection2/UserInfo.java | 1144 | package com.cheng.zenofdesignpatterns.patterns.adapter.mmssection2;
/**
*
*/
public class UserInfo implements IUserInfo {
/*
* 获得家庭地址,下属送礼也可以找到地方
*/
public String getHomeAddress() {
System.out.println("这里是员工的家庭地址....");
return null;
}
/*
* 获得家庭电话号码
*/
public String getHomeTelNumber() {
System.out.println("员工的家庭电话是....");
return null;
}
/*
* 员工的职位,是部门经理还是小兵
*/
public String getJobPosition() {
System.out.println("这个人的职位是BOSS....");
return null;
}
/*
* 手机号码
*/
public String getMobileNumber() {
System.out.println("这个人的手机号码是0000....");
return null;
}
/*
* 办公室电话,烦躁的时候最好“不小心”把电话线踢掉,我经常这么干,对己对人都有好处
*/
public String getOfficeTelNumber() {
System.out.println("办公室电话是....");
return null;
}
/*
* 姓名了,这个老重要了
*/
public String getUserName() {
System.out.println("姓名叫做...");
return null;
}
}
| gpl-2.0 |
sysunite/f25-parser | src/main/java/com/sysunite/rws/deflecties/NormalizedDeflections.java | 2653 | package com.sysunite.rws.deflecties;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Vector;
/**
* @author Mohamad Alamili <mohamad@sysunite.com>
*/
public class NormalizedDeflections {
public static final double[] DXs = {0, 300, 600, 900, 1200, 1500, 1800};
public double D0bt;
public double IDK300bt;
public double[] D0bs = new double[DXs.length];
public static String error; // used for reporting error of latest parse
public static List<NormalizedDeflections> getDeflections(F25File file) {
error = null;
int D = DXs.length;
int[] xIndexes = new int[D];
for (int i = 0; i < D; i++) {
BigDecimal x = new BigDecimal(DXs[i]);
boolean found = false;
for (int j = 0; j < file.plateXpositions.size(); j++) {
BigDecimal xPosition = file.plateXpositions.get(j);
if (Math.abs(x.subtract(xPosition).doubleValue()) < 0.1) {
found = true;
xIndexes[i] = j;
break;
}
}
if (!found) {
error = "Plate x position not found for x=" + x;
return null;
}
}
BigDecimal plateR = file.plateRadius.divide(new BigDecimal(1000));
BigDecimal sref = new BigDecimal(50000).divide(plateR.multiply(plateR), 100, RoundingMode.HALF_UP).divide(new BigDecimal(Math.PI), 100, RoundingMode.HALF_UP).divide(new BigDecimal(1000));
List<NormalizedDeflections> ret = new Vector<>();
try {
for (Measurement m : file.measurements) {
NormalizedDeflections nd = new NormalizedDeflections();
int P = m.peakReadings.size();
for (int i = 0; i < D; i++) {
int index = xIndexes[i];
double sum = 0;
for (int p = 1; p < P; p++) { // reading #1 is ignored?
PeakReadings pr = m.peakReadings.get(p);
BigDecimal v = pr.deflections.get(index);
v = v.multiply(sref.divide(pr.peakLoad, 100, RoundingMode.HALF_UP));
sum += v.doubleValue();
}
double avg = sum / (P - 1);
nd.D0bs[i] = avg;
} // for deflections
double tNorm = m.stationInfo.temperatureAsphalt.subtract(new BigDecimal(20)).doubleValue();
double d0b = nd.D0bs[0];
nd.D0bt = d0b / (1 + 0.013926 * tNorm + 0.0002298 * (tNorm * tNorm));
double idk300b = d0b - nd.D0bs[1];
nd.IDK300bt = idk300b / (1 + 0.043535 * tNorm + 0.00098467 * (tNorm * tNorm));
ret.add(nd);
} // for measurements
} catch (Exception e) {
error = "Error during deflection calculation from peak readings";
return null;
}
return ret;
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.edi.esb.camel/src/test/java/de/metas/edi/esb/route/AbstractEDIRouteTest.java | 5744 | package de.metas.edi.esb.route;
/*
* #%L
* de.metas.edi.esb
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.io.InputStream;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.spi.BrowsableEndpoint;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import de.metas.edi.esb.commons.AbstractEDITest;
import de.metas.edi.esb.commons.Constants;
import de.metas.edi.esb.commons.Util;
import de.metas.edi.esb.route.exports.EDIDesadvRoute;
import de.metas.edi.esb.route.exports.EDIInvoiceRoute;
import de.metas.edi.esb.route.imports.EDIOrderRoute;
public abstract class AbstractEDIRouteTest extends AbstractEDITest
{
@Produce(uri = Constants.EP_JMS_FROM_AD)
private ProducerTemplate inputXMLInvoice;
@EndpointInject(uri = EDIInvoiceRoute.EP_EDI_FILE_INVOICE)
protected BrowsableEndpoint outEDIInvoiceFILE;
@EndpointInject(uri = EDIDesadvRoute.EP_EDI_FILE_DESADV)
protected BrowsableEndpoint outEDIDesadvFILE;
@Produce(uri = EDIOrderRoute.EDI_INPUT_ORDERS)
private ProducerTemplate inputEDIOrder;
@Before
public void setFixedTime()
{
// NOTE: all tests are made using this system time
timeSource.setTime(2013, 2 - 1, 1, 19, 46, 0);
}
/**
*
* @param ediDataEndPoint the EDI-receiving endpoint to verify. Verification is only done if this endpoint is <code>instanceof</code> {@link MockEndpoint}.
* @param xmlInoutResourceName name of the XML resource that is supposed to be transformed to EDI.
* @param ediExpectedOutputResourceName
* @param feedbackResourceName
* @throws Exception
*/
protected void executeXMLToEDIExportRouteExchange(
final BrowsableEndpoint ediDataEndPoint,
final String xmlInoutResourceName,
final String ediExpectedOutputResourceName,
final String feedbackResourceName) throws Exception
{
outJMSADEP.setExpectedMessageCount(1);
// Send XML message
// Note: we send a string, because sending a ressource stream failed
// with an InOutException (stream closed) while trying to unmarshal the XML.
final String xmlInput = AbstractEDITest.getResourceAsString(xmlInoutResourceName);
final Exchange ex = new DefaultExchange(context);
ex.getIn().setBody(xmlInput);
inputXMLInvoice.send(ex);
//
// Test Feedback response
final Exchange exchangeReceived = outJMSADEP.assertExchangeReceived(0);
outJMSADEP.assertIsSatisfied();
final String feedbackExpected = AbstractEDITest.getResourceAsString(feedbackResourceName);
final String feedbackActual = exchangeReceived.getIn().getBody(String.class);
Assert.assertEquals("Invalid XML feedback", Util.fixLineEnding(feedbackExpected), Util.fixLineEnding(feedbackActual));
//
// Test EDI Result
final String expectedEDIOutput = AbstractEDITest.getResourceAsString(ediExpectedOutputResourceName);
if (ediDataEndPoint instanceof MockEndpoint)
{
// we have this if to make it easier for a dev to experiment with endpoint types other than MockEndPoint
final MockEndpoint mockedFILE = (MockEndpoint)ediDataEndPoint;
Assert.assertEquals("EP " + mockedFILE + " did not receive an exchange!", 1, mockedFILE.getReceivedExchanges().size());
final String actualResult = mockedFILE.getReceivedExchanges().get(0).getIn().getBody(String.class);
Assert.assertNotNull(actualResult);
Assert.assertEquals("Invalid EDI result", Util.fixLineEnding(expectedEDIOutput), Util.fixLineEnding(actualResult));
}
}
protected void executeEDIToXMLOrdersRouteExchange(final String ediResourceName, final String xmlResourceName) throws Exception
{
// Send EDI message
final Exchange ex = new DefaultExchange(context);
// Mimic the file component (we're using a direct component in tests)
ex.getIn().setHeader(Exchange.FILE_NAME, ediResourceName);
// Set & send body
final InputStream ediInputStream = getClass().getResourceAsStream(ediResourceName);
Assert.assertNotNull("EDI input stream shall exist for " + ediResourceName, ediInputStream);
ex.getIn().setBody(ediInputStream);
inputEDIOrder.send(ex);
outJMSADEP.assertIsSatisfied();
// We're using one file to evaluate all received XML messages at once (they're supposed to be in the exact same order!)
final StringBuilder actualResultBuilder = new StringBuilder();
for (final Exchange exchange : outJMSADEP.getReceivedExchanges())
{
actualResultBuilder.append(exchange.getIn().getBody(String.class));
}
final String expectedResult = AbstractEDITest.getResourceAsString(xmlResourceName);
final String actualResult = actualResultBuilder.toString();
Assert.assertEquals("Invalid result", Util.fixLineEnding(expectedResult), Util.fixLineEnding(actualResult));
}
protected final void assumeResourceExists(final String resourceName)
{
final InputStream in = getClass().getResourceAsStream(resourceName);
Assume.assumeTrue("Resource shall exist: " + resourceName, in != null);
}
}
| gpl-2.0 |
jorgegalvez/funeralesmodernos | FunerariaEAR/FunerariaEJB/src/java/sv/com/fm/business/entity/PlanPagos.java | 7722 | /*
* ESTE COMPONENTE FUE REALIZADO BAJO LA METODOLOGÍA DE DESARROLLO
* DE FUNERALES MODERNOS Y SE ENCUENTRA PROTEGIDO
* POR LAS LEYES DE DERECHOS DE AUTOR.
* @author Jorge Galvez
* Funerales Modernos 2015
*/
package sv.com.fm.business.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
/**
*
* @author Jorge Galvez
*/
@Entity
@Table(name = "PlanPagos", catalog = "FM", schema = "dbo")
@NamedQueries({
@NamedQuery(name = "PlanPagos.findAll", query = "SELECT p FROM PlanPagos p"),
@NamedQuery(name = "PlanPagos.findByCodigoPlanPagos", query = "SELECT p FROM PlanPagos p WHERE p.codigoPlanPagos = :codigoPlanPagos"),
@NamedQuery(name = "PlanPagos.findByCodigoContrato", query = "SELECT p FROM PlanPagos p WHERE p.codigoContrato.codigoContrato = :codigoContrato ORDER BY p.numeroCuota"),
@NamedQuery(name = "PlanPagos.findByCodigoContratoAndNumCuota", query = "SELECT p FROM PlanPagos p WHERE p.codigoContrato.codigoContrato = :codigoContrato AND p.numeroCuota = :numeroCuota"),
@NamedQuery(name = "PlanPagos.findByNumeroCuota", query = "SELECT p FROM PlanPagos p WHERE p.numeroCuota = :numeroCuota"),
@NamedQuery(name = "PlanPagos.findByGenerado", query = "SELECT p FROM PlanPagos p WHERE p.generado = :generado"),
@NamedQuery(name = "PlanPagos.findByFechaVencimiento", query = "SELECT p FROM PlanPagos p WHERE p.fechaVencimiento = :fechaVencimiento"),
@NamedQuery(name = "PlanPagos.findByFechaBetween", query = "SELECT p FROM PlanPagos p WHERE p.fechaVencimiento BETWEEN :fechaInicio AND :fechaFin"),
@NamedQuery(name = "PlanPagos.findByCuotaCapital", query = "SELECT p FROM PlanPagos p WHERE p.cuotaCapital = :cuotaCapital"),
@NamedQuery(name = "PlanPagos.findByCuotaInteres", query = "SELECT p FROM PlanPagos p WHERE p.cuotaInteres = :cuotaInteres"),
@NamedQuery(name = "PlanPagos.findBySeguroContratante", query = "SELECT p FROM PlanPagos p WHERE p.seguroContratante = :seguroContratante"),
@NamedQuery(name = "PlanPagos.findBySeguroBeneficiarios", query = "SELECT p FROM PlanPagos p WHERE p.seguroBeneficiarios = :seguroBeneficiarios"),
@NamedQuery(name = "PlanPagos.findByCuotaTotal", query = "SELECT p FROM PlanPagos p WHERE p.cuotaTotal = :cuotaTotal"),
@NamedQuery(name = "PlanPagos.findByFechaPagoRealizado", query = "SELECT p FROM PlanPagos p WHERE p.fechaPagoRealizado = :fechaPagoRealizado")})
public class PlanPagos implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CodigoPlanPagos")
private Integer codigoPlanPagos;
@Column(name = "NumeroCuota")
private Integer numeroCuota;
@Column(name = "FechaVencimiento")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaVencimiento;
@Column(name = "CuotaCapital")
private Double cuotaCapital;
@Column(name = "CuotaInteres")
private Double cuotaInteres;
@Column(name = "SeguroContratante")
private Double seguroContratante;
@Column(name = "SeguroBeneficiarios")
private Double seguroBeneficiarios;
@Column(name = "CuotaTotal")
private Double cuotaTotal;
@Column(name = "Generado")
private Boolean generado;
@Column(name = "FechaPagoRealizado")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaPagoRealizado;
@JoinColumn(name = "CodigoContrato", referencedColumnName = "CodigoContrato")
@ManyToOne
private Contratos codigoContrato;
@JoinColumn(name = "CodigoEmpleadoUsuario", referencedColumnName = "CodigoEmpleado")
@ManyToOne
private Empleados codigoEmpleadoUsuario;
@Column(name = "FechaEvento")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaEvento;
public PlanPagos() {
}
public PlanPagos(Integer codigoPlanPagos) {
this.codigoPlanPagos = codigoPlanPagos;
}
public Integer getCodigoPlanPagos() {
return codigoPlanPagos;
}
public void setCodigoPlanPagos(Integer codigoPlanPagos) {
this.codigoPlanPagos = codigoPlanPagos;
}
public Integer getNumeroCuota() {
return numeroCuota;
}
public void setNumeroCuota(Integer numeroCuota) {
this.numeroCuota = numeroCuota;
}
public Date getFechaVencimiento() {
return fechaVencimiento;
}
public void setFechaVencimiento(Date fechaVencimiento) {
this.fechaVencimiento = fechaVencimiento;
}
public Double getCuotaCapital() {
return cuotaCapital;
}
public void setCuotaCapital(Double cuotaCapital) {
this.cuotaCapital = cuotaCapital;
}
public Double getCuotaInteres() {
return cuotaInteres;
}
public void setCuotaInteres(Double cuotaInteres) {
this.cuotaInteres = cuotaInteres;
}
public Double getSeguroContratante() {
return seguroContratante;
}
public void setSeguroContratante(Double seguroContratante) {
this.seguroContratante = seguroContratante;
}
public Double getSeguroBeneficiarios() {
return seguroBeneficiarios;
}
public void setSeguroBeneficiarios(Double seguroBeneficiarios) {
this.seguroBeneficiarios = seguroBeneficiarios;
}
public Double getCuotaTotal() {
return cuotaTotal;
}
public void setCuotaTotal(Double cuotaTotal) {
this.cuotaTotal = cuotaTotal;
}
public Date getFechaPagoRealizado() {
return fechaPagoRealizado;
}
public void setFechaPagoRealizado(Date fechaPagoRealizado) {
this.fechaPagoRealizado = fechaPagoRealizado;
}
public Contratos getCodigoContrato() {
return codigoContrato;
}
public void setCodigoContrato(Contratos codigoContrato) {
this.codigoContrato = codigoContrato;
}
public Empleados getCodigoEmpleadoUsuario() {
return codigoEmpleadoUsuario;
}
public void setCodigoEmpleadoUsuario(Empleados codigoEmpleadoUsuario) {
this.codigoEmpleadoUsuario = codigoEmpleadoUsuario;
}
public Date getFechaEvento() {
return fechaEvento;
}
public void setFechaEvento(Date fechaEvento) {
this.fechaEvento = fechaEvento;
}
public Boolean getGenerado() {
return generado;
}
public void setGenerado(Boolean generado) {
this.generado = generado;
}
@Override
public int hashCode() {
int hash = 0;
hash += (codigoPlanPagos != null ? codigoPlanPagos.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PlanPagos)) {
return false;
}
PlanPagos other = (PlanPagos) object;
if ((this.codigoPlanPagos == null && other.codigoPlanPagos != null) || (this.codigoPlanPagos != null && !this.codigoPlanPagos.equals(other.codigoPlanPagos))) {
return false;
}
return true;
}
@Override
public String toString() {
return "sv.com.fm.business.entity.PlanPagos[ codigoPlanPagos=" + codigoPlanPagos + " ]";
}
} | gpl-2.0 |
qwarnant/CAR-FTPServer | src/fr/univ/lille1/ftp/server/request/control/FtpPwdRequest.java | 1069 | package fr.univ.lille1.ftp.server.request.control;
import java.io.IOException;
import fr.univ.lille1.ftp.server.request.FtpRequest;
import fr.univ.lille1.ftp.server.request.FtpResponse;
import fr.univ.lille1.ftp.util.FtpConstants;
/**
* FtpPwdRequest is the class associated to the PWD ftp request
* PWD allows the user client to print his current directory on the ftp server
*
* @author Quentin Warnant
* @version 1.0
*/
public class FtpPwdRequest extends FtpRequest {
private String currentDirectory;
/**
* Class constructor
*
* @param commandLine String the request client command line
* @param currentDirectory String the user current directory on the ftp server
*/
public FtpPwdRequest(String commandLine, String currentDirectory) {
super(commandLine);
this.currentDirectory = currentDirectory;
}
@Override
public FtpResponse process() throws IOException {
return new FtpResponse(FtpConstants.FTP_REP_PWD_CODE,
"\"" + this.currentDirectory + "\"");
}
}
| gpl-2.0 |
Esleelkartea/aon-employee | aonemployee_v2.3.0_src/paquetes descomprimidos/aon.company-2.1.8-sources/com/code/aon/company/IEntity.java | 495 | package com.code.aon.company;
import java.io.Serializable;
/**
*
* @author Consulting & Development. Iñaki Ayerbe - 30-jan-2007
* @since 1.0
*
*/
public interface IEntity extends Serializable {
/**
* Returns Entity identifier.
*
* @return Integer
*/
Integer getId();
/**
* Accept visitor node and execute its visitant method.
*
* @param visitor INodeVisitor
*/
void accept(IEntityVisitor visitor);
} | gpl-2.0 |
freeplane/freeplane | freeplane_plugin_script/src/main/java/org/freeplane/plugin/script/addons/AddOnInstallerPanel.java | 9485 | package org.freeplane.plugin.script.addons;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.core.ui.LabelAndMnemonicSetter;
import org.freeplane.core.ui.components.UITools;
import org.freeplane.core.util.LogUtils;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.map.MapModel;
import org.freeplane.features.map.mindmapmode.MMapModel;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.mode.ModeController;
import org.freeplane.features.mode.mindmapmode.MModeController;
import org.freeplane.features.url.mindmapmode.MFileManager;
import org.freeplane.main.addons.AddOnProperties;
import org.freeplane.main.addons.AddOnsController;
import org.freeplane.plugin.script.ScriptingEngine;
import org.freeplane.plugin.script.ScriptingPermissions;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
@SuppressWarnings("serial")
public class AddOnInstallerPanel extends JPanel {
private ManageAddOnsPanel manageAddOnsPanel;
private ManageAddOnsPanel manageThemesPanel;
private JButton installButton;
private JTextField urlField;
public AddOnInstallerPanel(final ManageAddOnsPanel manageAddOnsPanel, ManageAddOnsPanel manageThemesPanel) {
this.manageAddOnsPanel = manageAddOnsPanel;
this.manageThemesPanel = manageThemesPanel;
setLayout(new FormLayout(new ColumnSpec[] {
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,}));
//
// Search
//
add(DefaultComponentFactory.getInstance().createSeparator(getTitleText("search")), "1, 2");
add(createVisitAddOnPageButton(), "1, 4, left, default");
add(Box.createVerticalStrut(20), "1, 6");
//
// Install from known location
//
add(DefaultComponentFactory.getInstance().createSeparator(getTitleText("install.from.known.location")), "1, 7");
installButton = createInstallButton();
urlField = createUrlField(installButton);
final JButton selectFile = createFileChooser(urlField);
installButton.addActionListener(createInstallActionListener());
final Box box = Box.createHorizontalBox();
box.add(urlField);
box.add(selectFile);
add(box, "1, 9");
add(installButton, "1, 11, right, default");
// setBackground(Color.WHITE);
}
private static String getText(String key, Object... parameters) {
return ManageAddOnsDialog.getText(key, parameters);
}
private static String getTitleText(final String key) {
final String titleStyle = "<html><b><font size='+1'>";
return titleStyle + getText(key);
}
private JButton createVisitAddOnPageButton() {
try {
final String addOnsUriString = TextUtils.removeTranslateComment(TextUtils.getText("addons.site"));
// parse the URI on creation of the dialog to test the URI syntax early
final URI addOnsUri = new URI(addOnsUriString);
return UITools.createHtmlLinkStyleButton(addOnsUri, getText("visit.addon.page"));
}
catch (URISyntaxException ex) {
// bad translation?
throw new RuntimeException(ex);
}
}
private JButton createInstallButton() {
final JButton installButton = new JButton();
LabelAndMnemonicSetter.setLabelAndMnemonic(installButton, getText("install"));
installButton.setEnabled(false);
// FIXME: get rid of that
installButton.setMargin(new Insets(0, 25, 0, 25));
return installButton;
}
private ActionListener createInstallActionListener() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
final Controller controller = Controller.getCurrentController();
try {
LogUtils.info("installing add-on from " + urlField.getText());
controller.getViewController().setWaitingCursor(true);
final URL url = toURL(urlField.getText());
setStatusInfo(getText("status.installing"));
final ModeController modeController = controller.getModeController(MModeController.MODENAME);
final MFileManager fileManager = (MFileManager) MFileManager.getController(modeController);
MapModel newMap = new MMapModel(modeController.getMapController().duplicator());
if (!fileManager.loadCatchExceptions(url, newMap)) {
LogUtils.warn("can not load " + url);
return;
}
controller.getModeController().getMapController().fireMapCreated(newMap);
AddOnProperties addOn = (AddOnProperties) ScriptingEngine.executeScript(newMap.getRootNode(),
getInstallScriptFile(), ScriptingPermissions.getPermissiveScriptingPermissions());
if (addOn != null) {
setStatusInfo(getText("status.success", addOn.getName()));
AddOnsController.getController().registerInstalledAddOn(addOn);
final ManageAddOnsPanel managementPanel = addOn.isTheme() ? manageThemesPanel
: manageAddOnsPanel;
managementPanel.getTableModel().addAddOn(addOn);
urlField.setText("");
((JTabbedPane)getParent()).setSelectedComponent(managementPanel);
selectLastAddOn(managementPanel);
}
}
catch (Exception ex) {
UITools.errorMessage(getText("error", ex.toString()));
}
finally {
controller.getViewController().setWaitingCursor(false);
}
}
private File getInstallScriptFile() {
final ResourceController resourceController = ResourceController.getResourceController();
final File scriptDir = new File(resourceController.getInstallationBaseDir(), "scripts");
final File installScript = new File(scriptDir, "installScriptAddOn.groovy");
if (!installScript.exists())
throw new RuntimeException("internal error: installer not found at " + installScript);
return installScript;
}
private URL toURL(String urlText) throws MalformedURLException {
try {
return new URL(urlText);
}
catch (Exception e2) {
return new File(urlText).toURI().toURL();
}
}
};
}
private void selectLastAddOn(JComponent managementPanel) {
try {
JTable table = findJTable(managementPanel);
final int row = table.getModel().getRowCount() - 1;
table.getSelectionModel().setSelectionInterval(row, row);
}
catch (Exception e) {
LogUtils.warn("cannot select just installed add-on", e);
}
}
private JTable findJTable(JComponent child) {
for (Component component : child.getComponents()) {
if (component instanceof JTable) {
return (JTable) component;
}
else if (component instanceof JComponent) {
final JTable findResult = findJTable((JComponent) component);
if (findResult != null)
return findResult;
}
}
return null;
}
private JButton createFileChooser(final JTextField urlField) {
final JButton selectFile = new JButton(getText("search.file"),
ResourceController.getResourceController().getIcon("OpenAction.icon"));
final JFileChooser fileChooser = UITools.newFileChooser(null);
selectFile.setToolTipText(getText("select.tooltip"));
selectFile.setMaximumSize(UITools.MAX_BUTTON_DIMENSION);
selectFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fileChooser.showOpenDialog(urlField);
final File selectedFile = fileChooser.getSelectedFile();
if (selectedFile != null)
urlField.setText(selectedFile.getAbsolutePath());
}
});
return selectFile;
}
private JTextField createUrlField(final JButton install) {
final JTextField urlField = new JTextField();
// urlField.setColumns(100);
urlField.setToolTipText(getText("install.tooltip"));
urlField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
updateImpl(e);
}
public void removeUpdate(DocumentEvent e) {
updateImpl(e);
}
public void changedUpdate(DocumentEvent e) {
updateImpl(e);
}
private void updateImpl(DocumentEvent e) {
install.setEnabled(e.getDocument().getLength() > 0);
}
});
urlField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
install.requestFocusInWindow();
install.doClick();
}
}
});
return urlField;
}
JButton getInstallButton() {
return installButton;
}
JTextField getUrlField() {
return urlField;
}
private static void setStatusInfo(final String message) {
Controller.getCurrentController().getViewController().out(message);
}
}
| gpl-2.0 |
chaqui/BibliotecaEnJava | src/java/vistas/ClienteController.java | 6982 | package vistas;
import modulos.Cliente;
import vistas.util.JsfUtil;
import vistas.util.PaginationHelper;
import vistas.ClienteFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
@ManagedBean(name = "clienteController")
@SessionScoped
public class ClienteController implements Serializable {
private Cliente current;
private DataModel items = null;
@EJB
private vistas.ClienteFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public ClienteController() {
}
public Cliente getSelected() {
if (current == null) {
current = new Cliente();
selectedItemIndex = -1;
}
return current;
}
private ClienteFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
@Override
public int getItemsCount() {
return getFacade().count();
}
@Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Cliente) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Cliente();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ClienteCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Cliente) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ClienteUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Cliente) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ClienteDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
@FacesConverter(forClass = Cliente.class)
public static class ClienteControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ClienteController controller = (ClienteController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "clienteController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Cliente) {
Cliente o = (Cliente) object;
return getStringKey(o.getNickName());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Cliente.class.getName());
}
}
}
}
| gpl-2.0 |
Quadx117/FiveHundred | src/fiveHundred/Main.java | 490 | package fiveHundred;
import javax.swing.UIManager;
/**
* This class is the main entry point of the program. It contains
* the main method to launch the game.
*/
public class Main
{
public static void main(String[] args)
{
// Set the Look to the system's look instead of java's default look
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e)
{
e.printStackTrace();
}
Game game = new Game();
game.start();
}
}
| gpl-2.0 |
brdvlps/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/services/SendMessageService.java | 3910 | package de.tum.in.tumcampusapp.services;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import java.util.ArrayList;
import de.tum.in.tumcampusapp.auxiliary.AuthenticationManager;
import de.tum.in.tumcampusapp.auxiliary.Utils;
import de.tum.in.tumcampusapp.exceptions.NoPrivateKey;
import de.tum.in.tumcampusapp.models.TUMCabeClient;
import de.tum.in.tumcampusapp.models.ChatMessage;
import de.tum.in.tumcampusapp.models.managers.ChatMessageManager;
import retrofit.RetrofitError;
/**
* Service used to silence the mobile during lectures
*/
public class SendMessageService extends IntentService {
/**
* Interval in milliseconds to check for current lectures
*/
private static final String SEND_MESSAGE_SERVICE = "SendMessageService";
/**
* default init (run intent in new thread)
*/
public SendMessageService() {
super(SEND_MESSAGE_SERVICE);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
protected void onHandleIntent(Intent intent) {
// Get all unsent messages from database
ArrayList<ChatMessage> unsentMsg = ChatMessageManager.getAllUnsentUpdated(this);
if (unsentMsg.size() == 0) {
return;
}
int numberOfAttempts = 0;
AuthenticationManager am = new AuthenticationManager(this);
//Try to send the message 5 times
while (numberOfAttempts < 5) {
try {
for (ChatMessage message : unsentMsg) {
// Generate signature and store it in the message
message.setSignature(am.sign(message.getText()));
// Send the message to the server
ChatMessage createdMessage;
if (message.getId() == 0) { //If the id is zero then its an new entry otherwise try to update it
createdMessage = TUMCabeClient.getInstance(this).sendMessage(message.getRoom(), message);
Utils.logv("successfully sent message: " + createdMessage.getText());
} else {
createdMessage = TUMCabeClient.getInstance(this).updateMessage(message.getRoom(), message);
Utils.logv("successfully updated message: " + createdMessage.getText());
}
//Update the status on the ui
createdMessage.setStatus(ChatMessage.STATUS_SENT);
ChatMessageManager messageManager = new ChatMessageManager(this, message.getRoom());
messageManager.replaceInto(createdMessage, message.getMember().getId());
messageManager.removeFromUnsent(message);
// Send broadcast to eventually open ChatActivity
Intent i = new Intent("chat-message-received");
Bundle extras = new Bundle();
extras.putString("room", "" + message.getRoom());
extras.putString("member", "" + message.getMember().getId());
i.putExtras(extras);
LocalBroadcastManager.getInstance(this).sendBroadcast(i);
}
//Exit the loop
return;
} catch (RetrofitError e) {
Utils.log(e);
numberOfAttempts++;
} catch (NoPrivateKey noPrivateKey) {
return; //Nothing can be done, just exit
}
//Sleep for five seconds, maybe the server is currently really busy
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | gpl-2.0 |
orlanthi/healpix | src/java/src/healpix/core/base/set/LongRangeIterator.java | 1209 |
/*
* LongRangeSet from Jan Kotek redistributed under GPLv2
*/
package healpix.core.base.set;
/**
* An iterator over ranges which does not require object creation
* <p>
* !!Implementation must return sorted ranges in iterator!!
* * @author Jan Kotek
*/
public interface LongRangeIterator {
/** move to next Range in iterator
* @return true if more ranges are in iterator, false if iterator reached end
*/
boolean moveToNext();
// /**
// * Skip values on RangeIterator until current first is >= to last.
// * Is typically faster then moveToNext() in cycle with condition (uses binary search).
// * This goes only forward, no backward
// * @param last
// * @return true if more ranges are in iterator, false if iterator reached end
// */
// boolean skipTo(long last);
/**
* @return first item in current range (inclusive)
* @throws java.util.NoSuchElementException if no more elements are found
*/
long first();
/**
* @return last item in current range (inclusive)
* @throws java.util.NoSuchElementException if no more elements are found
*/
long last();
} | gpl-2.0 |
quchenhao/spot-auto-scaling | spot-auto-scaling-aws/src/main/java/auto_scaling/configuration/aws/AWSMonitorsLoader.java | 4861 | package auto_scaling.configuration.aws;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import auto_scaling.cloud.UnSupportedResourceException;
import auto_scaling.configuration.ICloudConfiguration;
import auto_scaling.configuration.IMonitorsLoader;
import auto_scaling.monitor.BillingPeriodMonitor;
import auto_scaling.monitor.Metrics;
import auto_scaling.monitor.Monitor;
import auto_scaling.monitor.Monitors;
import auto_scaling.monitor.aws.AWSCloudWatchResourceMonitor;
import auto_scaling.monitor.aws.AWSHealthCheckMonitor;
import auto_scaling.monitor.aws.AWSSpotPriceMonitor;
import auto_scaling.monitor.aws.AWSSpotRequestsMonitor;
import auto_scaling.monitor.aws.AWSVMStatusMonitor;
/**
* @ClassName: AWSMonitorsLoader
* @Description: loaders to load monitors for Amazon AWS
* @author Chenhao Qu
* @date 05/06/2015 2:18:49 pm
*
*/
public class AWSMonitorsLoader implements IMonitorsLoader {
/* (non-Javadoc)
* <p>Title: loadMonitors</p>
* <p>Description: </p>
* @param inputStream
* @param cloudConfiguration
* @return
* @throws IOException
* @throws UnSupportedResourceException
* @see auto_scaling.configuration.IMonitorsLoader#loadMonitors(java.io.InputStream, auto_scaling.configuration.ICloudConfiguration)
*/
@Override
public Map<String, Monitor> loadMonitors(InputStream inputStream, ICloudConfiguration cloudConfiguration) throws IOException, UnSupportedResourceException{
Properties properties = new Properties();
properties.load(inputStream);
List<String> statistics = new ArrayList<String>();
statistics.add("Average");
Map<String, Monitor> monitors = new HashMap<String, Monitor>();
int cpuUtilizationMonitorInterval = Integer.parseInt(properties.getProperty(CPU_UTILIZATION_MONITOR_INTERVAL));
int cpuUtilizationMonitorPeriod = Integer.parseInt(properties.getProperty(CPU_UTILIZATION_MONITOR_PERIOD));
Monitor cpuUtilizationMonitor = new AWSCloudWatchResourceMonitor(cloudConfiguration, Monitors.CPU_UTILIZATION_MONITOR, Metrics.CPU_UTILIZATION, "AWS/EC2", statistics, cpuUtilizationMonitorInterval, cpuUtilizationMonitorPeriod);
monitors.put(Monitors.CPU_UTILIZATION_MONITOR, cpuUtilizationMonitor);
int memoryUtilizationMonitorInterval = Integer.parseInt(properties.getProperty(MEMORY_UTILIZATION_MONITOR_INTERVAL));
int memoryUtilizationMonitorPeriod = Integer.parseInt(properties.getProperty(MEMORY_UTILIZATION_MONITOR_PERIOD));
Monitor memoryUtilizationMonitor = new AWSCloudWatchResourceMonitor(cloudConfiguration, Monitors.MEMORY_UTILIZATION_MONITOR, Metrics.MEMORY_UTILIZATION, "System/Linux", statistics, memoryUtilizationMonitorInterval, memoryUtilizationMonitorPeriod);
monitors.put(Monitors.MEMORY_UTILIZATION_MONITOR, memoryUtilizationMonitor);
int billingPeriodMonitorInterval = Integer.parseInt(properties.getProperty(BILLING_PERIOD_MONITOR_INTERVAL));
int billingPeriodMonitorEndingThreshold = Integer.parseInt(properties.getProperty(BILLING_PERIOD_MONITOR_ENDING_THRESHOLD));
int billingPeriodMonitorSwithModeThreshold = Integer.parseInt(properties.getProperty(BILLING_PERIOD_SWITCH_MODE_THRESHOLD));
Monitor billingPeriodMonitor = new BillingPeriodMonitor(Monitors.BILLING_PERIOD_MONITOR, billingPeriodMonitorInterval, billingPeriodMonitorEndingThreshold, billingPeriodMonitorSwithModeThreshold);
monitors.put(Monitors.BILLING_PERIOD_MONITOR, billingPeriodMonitor);
int healthCheckMonitorInterval = Integer.parseInt(properties.getProperty(HEALTH_CHECK_MONITOR_INTERVAL));
Monitor healthCheckMonitor = new AWSHealthCheckMonitor(cloudConfiguration, Monitors.HEALTH_CHECK_MONITOR, healthCheckMonitorInterval);
monitors.put(Monitors.HEALTH_CHECK_MONITOR, healthCheckMonitor);
int spotPriceMonitorInterval = Integer.parseInt(properties.getProperty(SPOT_PRICE_MONITOR_INTERVAL));
Monitor spotPriceMonitor = new AWSSpotPriceMonitor(cloudConfiguration, Monitors.SPOT_PRICE_MONITOR, spotPriceMonitorInterval);
monitors.put(Monitors.SPOT_PRICE_MONITOR, spotPriceMonitor);
int spotRequestsMonitorInterval = Integer.parseInt(properties.getProperty(SPOT_REQUESTS_MONITOR_INTERVAL));
Monitor spotRequestsMonitor = new AWSSpotRequestsMonitor(cloudConfiguration, Monitors.SPOT_REQUESTS_MONITOR, spotRequestsMonitorInterval);
monitors.put(Monitors.SPOT_REQUESTS_MONITOR, spotRequestsMonitor);
int vmStatusMonitorInterval = Integer.parseInt(properties.getProperty(VM_STATUS_MONITOR_INTERVAL));
Monitor vmStatusMonitor = new AWSVMStatusMonitor(cloudConfiguration, Monitors.VM_STATUS_MONITOR, vmStatusMonitorInterval);
monitors.put(Monitors.VM_STATUS_MONITOR, vmStatusMonitor);
return monitors;
}
}
| gpl-2.0 |
yugandhargangu/JspMyAdmin2 | application/jspmyadmin/src/main/java/com/jspmyadmin/framework/taglib/jma/IfTag.java | 3679 | /**
*
*/
package com.jspmyadmin.framework.taglib.jma;
import javax.servlet.jsp.JspException;
import com.jspmyadmin.framework.constants.Constants;
import com.jspmyadmin.framework.taglib.support.AbstractTagSupport;
/**
* @author Yugandhar Gangu
* @created_at 2016/01/28
*
*/
public class IfTag extends AbstractTagSupport {
private static final long serialVersionUID = 1L;
private String name = null;
private String value = null;
private String scope = null;
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @param value
* the value to set
*/
public void setValue(String value) {
this.value = value;
}
/**
* @param scope
* the scope to set
*/
public void setScope(String scope) {
this.scope = scope;
}
@Override
public int doStartTag() throws JspException {
String[] scopes = new String[2];
if (!isEmpty(scope)) {
scopes = scope.split(Constants.SYMBOL_COMMA);
}
Object temp1 = null;
if (name.startsWith(Constants.SYMBOL_HASH)) {
String[] split = name.substring(1).split(Constants.SYMBOL_DOT_EXPR);
if (Constants.COMMAND.equals(scopes[0])) {
for (int i = 0; i < split.length; i++) {
if (temp1 == null) {
temp1 = pageContext.getRequest().getAttribute(Constants.COMMAND);
}
temp1 = super.getReflectValue(temp1, split[i]);
}
} else if (Constants.REQUEST.equals(scopes[0])) {
for (int i = 0; i < split.length; i++) {
if (temp1 == null) {
temp1 = pageContext.getRequest().getAttribute(split[i]);
} else {
temp1 = super.getReflectValue(temp1, split[i]);
}
}
} else if (Constants.PAGE.equals(scopes[0])) {
for (int i = 0; i < split.length; i++) {
if (temp1 == null) {
temp1 = pageContext.getAttribute(split[i]);
} else {
temp1 = super.getReflectValue(temp1, split[i]);
}
}
} else if (Constants.SESSION.equals(scopes[0])) {
for (int i = 0; i < split.length; i++) {
if (temp1 == null) {
temp1 = pageContext.getSession().getAttribute(split[i]);
} else {
temp1 = super.getReflectValue(temp1, split[i]);
}
}
}
} else {
temp1 = name;
}
Object temp2 = null;
if (value.startsWith(Constants.SYMBOL_HASH)) {
String[] split = value.substring(1).split(Constants.SYMBOL_DOT_EXPR);
if (Constants.COMMAND.equals(scopes[1])) {
for (int i = 0; i < split.length; i++) {
if (temp2 == null) {
temp2 = pageContext.getRequest().getAttribute(Constants.COMMAND);
}
temp2 = super.getReflectValue(temp2, split[i]);
}
} else if (Constants.REQUEST.equals(scopes[1])) {
for (int i = 0; i < split.length; i++) {
if (temp2 == null) {
temp2 = pageContext.getRequest().getAttribute(value.substring(1));
} else {
temp2 = super.getReflectValue(temp2, split[i]);
}
}
} else if (Constants.PAGE.equals(scopes[1])) {
for (int i = 0; i < split.length; i++) {
if (temp2 == null) {
temp2 = pageContext.getAttribute(value.substring(1));
} else {
temp2 = super.getReflectValue(temp2, split[i]);
}
}
} else if (Constants.SESSION.equals(scopes[1])) {
for (int i = 0; i < split.length; i++) {
if (temp2 == null) {
temp2 = pageContext.getSession().getAttribute(value.substring(1));
} else {
temp2 = super.getReflectValue(temp2, split[i]);
}
}
}
} else {
temp2 = value;
}
scopes = null;
if ((temp1 == null && temp2 == null) || (temp1 != null && temp2 != null && temp1.equals(temp2))) {
return EVAL_BODY_INCLUDE;
} else {
return SKIP_BODY;
}
}
}
| gpl-2.0 |
tastybento/askyblock | src/com/wasteofplastic/askyblock/Messages.java | 7412 | /*******************************************************************************
* This file is part of ASkyBlock.
*
* ASkyBlock 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.
*
* ASkyBlock 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 ASkyBlock. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package com.wasteofplastic.askyblock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.wasteofplastic.askyblock.util.Util;
/**
* Handles offline messaging to players and teams
*
* @author tastybento
*
*/
public class Messages {
private final ASkyBlock plugin;
// Offline Messages
private final HashMap<UUID, List<String>> messages = new HashMap<>();
private YamlConfiguration messageStore;
/**
* @param plugin - ASkyBlock plugin object
*/
public Messages(ASkyBlock plugin) {
this.plugin = plugin;
}
/**
* Returns what messages are waiting for the player or null if none
*
* @param playerUUID - the player's UUID - player's UUID
* @return List of messages
*/
public List<String> getMessages(UUID playerUUID) {
return messages.get(playerUUID);
}
/**
* Clears any messages for player
*
* @param playerUUID - the player's UUID - player's UUID
*/
public void clearMessages(UUID playerUUID) {
messages.remove(playerUUID);
}
public void saveMessages(boolean async) {
if (messageStore == null) {
return;
}
plugin.getLogger().info("Saving offline messages...");
try {
// Convert to a serialized string
Map<String, Object> offlineMessages = new HashMap<>();
for (UUID p : messages.keySet()) {
if (p != null) {
offlineMessages.put(p.toString(), messages.get(p));
}
}
// Convert to YAML
messageStore.set("messages", offlineMessages);
Util.saveYamlFile(messageStore, "messages.yml", async);
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean loadMessages() {
plugin.getLogger().info("Loading offline messages...");
try {
messageStore = Util.loadYamlFile("messages.yml");
if (messageStore.getConfigurationSection("messages") == null) {
messageStore.createSection("messages"); // This is only used to
// create
}
HashMap<String, Object> temp = (HashMap<String, Object>) messageStore.getConfigurationSection("messages").getValues(true);
for (String s : temp.keySet()) {
List<String> messageList = messageStore.getStringList("messages." + s);
if (!messageList.isEmpty()) {
messages.put(UUID.fromString(s), messageList);
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Provides the messages for the player
*
* @param playerUUID - the player's UUID - player's UUID
* @return List of messages
*/
public List<String> get(UUID playerUUID) {
return messages.get(playerUUID);
}
/**
* Stores a message for player
*
* @param playerUUID - the player's UUID
* @param playerMessages
*/
public void put(UUID playerUUID, List<String> playerMessages) {
messages.put(playerUUID, playerMessages);
}
/**
* Sends a message to every player in the team that is offline
*
* @param playerUUID - the player's UUID - player's UUID
* @param message - message to send
*/
public void tellOfflineTeam(UUID playerUUID, String message) {
// getLogger().info("DEBUG: tell offline team called");
if (!plugin.getPlayers().inTeam(playerUUID)) {
// getLogger().info("DEBUG: player is not in a team");
return;
}
UUID teamLeader = plugin.getPlayers().getTeamLeader(playerUUID);
List<UUID> teamMembers = plugin.getPlayers().getMembers(teamLeader);
// getLogger().info("DEBUG: trying UUID " + member.toString());
// Offline player
teamMembers.stream().filter(member -> plugin.getServer().getPlayer(member) == null)
.forEach(member -> setMessage(member, message));
}
/**
* Tells all online team members something happened
*
* @param playerUUID - the player's UUID - player's UUID
* @param message - message to send
*/
public void tellTeam(UUID playerUUID, String message) {
// getLogger().info("DEBUG: tell offline team called");
if (!plugin.getPlayers().inTeam(playerUUID)) {
// getLogger().info("DEBUG: player is not in a team");
return;
}
UUID teamLeader = plugin.getPlayers().getTeamLeader(playerUUID);
List<UUID> teamMembers = plugin.getPlayers().getMembers(teamLeader);
for (UUID member : teamMembers) {
// getLogger().info("DEBUG: trying UUID " + member.toString());
if (!member.equals(playerUUID) && plugin.getServer().getPlayer(member) != null) {
// Online player
Util.sendMessage(plugin.getServer().getPlayer(member), message);
}
}
}
/**
* Sets a message for the player to receive next time they login
*
* @param playerUUID - the player's UUID - player's UUID
* @param message - message to set
* @return true if player is offline, false if online
*/
public boolean setMessage(UUID playerUUID, String message) {
// getLogger().info("DEBUG: received message - " + message);
Player player = plugin.getServer().getPlayer(playerUUID);
// Check if player is online
if (player != null) {
if (player.isOnline()) {
// Util.sendMessage(player, message);
return false;
}
}
storeMessage(playerUUID, message);
return true;
}
/**
* Stores a message without any online check
* @param playerUUID - the player's UUID - player's UUID
* @param message - message to store
*/
public void storeMessage(UUID playerUUID, String message) {
List<String> playerMessages = get(playerUUID);
if (playerMessages != null) {
playerMessages.add(message);
} else {
playerMessages = new ArrayList<>(Collections.singletonList(message));
}
put(playerUUID, playerMessages);
}
}
| gpl-2.0 |
bb14521/Atharva-2K15 | app/src/main/java/org/Harmanhutani/techfest/techfest/MainActivity.java | 24296 | package org.Harmanhutani.techfest.techfest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Stack;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks, OnMapReadyCallback{
ImageView tf_logo;
ArrayList<EventSummary> events = new ArrayList<EventSummary>();
Stack<Fragment> fragStack = new Stack<Fragment>();
HashMap<String, Integer[]> layout_desc = new HashMap<String, Integer[]>();
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
SupportMapFragment mapFrag;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
private int mActionBarColor = R.color.actionbar_home;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
((DrawerLayout) findViewById(R.id.drawer_layout)).openDrawer(findViewById(R.id.navigation_drawer));
tf_logo = new ImageView(this);
// Toast.makeText(getApplicationContext(),
// "Enable GPS and Data for Best UX", Toast.LENGTH_LONG).show();
Picasso.with(this).load(R.drawable.tf_logo).fit().centerCrop().into((tf_logo));
events = getIntent().getParcelableArrayListExtra("events");
layout_desc.put("Carnival", new Integer[]{R.layout.details_carnival, R.drawable.vortex, R.color.actionbar_competitions});
layout_desc.put("Our Sponsors", new Integer[]{R.layout.fragment_ssponserss, R.drawable.geo, R.color.actionbar_competitions});
layout_desc.put("Technoholix", new Integer[]{R.layout.details_technoholix, R.drawable.et, R.color.actionbar_technoholix});
layout_desc.put("Lectures", new Integer[]{R.layout.details_lectures, R.drawable.lectures, R.color.actionbar_lectures});
layout_desc.put("Lan Gaming", new Integer[]{R.layout.details_exhibitions, R.drawable.finalssss, R.color.actionbar_exhibitions});
layout_desc.put("Model Exhibition", new Integer[]{R.layout.details_ozone, R.drawable.ozone, R.color.actionbar_ozone});
layout_desc.put("GNE's Cube Challenge", new Integer[]{R.layout.details_game_changer, R.drawable.cube, R.color.actionbar_ideate});
layout_desc.put("Robo Soccer", new Integer[]{R.layout.details_parishram, R.drawable.soccer1, R.color.actionbar_ideate});
layout_desc.put("Car Maze Racing", new Integer[]{R.layout.details_ujjwal, R.drawable.race, R.color.actionbar_ideate});
layout_desc.put("Machine O Founics", new Integer[]{R.layout.details_irc_workshop, R.drawable.gg, R.color.actionbar_workshops
});
layout_desc.put("Bridge Modelling", new Integer[]{R.layout.details_augmented_reality, R.drawable.popsic6, R.color.actionbar_workshops});
layout_desc.put("RCC", new Integer[]{R.layout.details_zero_energy_buildings, R.drawable.rcc, R.color.actionbar_workshops});
layout_desc.put("Water Rock-It", new Integer[]{R.layout.details_arduped, R.drawable.water, R.color.actionbar_workshops});
layout_desc.put("DAM-It", new Integer[]{R.layout.details_cloud_computing, R.drawable.cloud_computing, R.color.actionbar_workshops});
layout_desc.put("Robomania", new Integer[]{R.layout.details_gyrocopter, R.drawable.mania, R.color.actionbar_workshops});
layout_desc.put("Electroclique", new Integer[]{R.layout.details_hacktricks_level_1, R.drawable.hacktricks, R.color.actionbar_workshops});
layout_desc.put("Hacktricks Level 2", new Integer[]{R.layout.details_hacktricks_level_2, R.drawable.hacktricks, R.color.actionbar_workshops});
layout_desc.put("Dev Cops", new Integer[]{R.layout.details_web_development, R.drawable.dev, R.color.actionbar_workshops});
layout_desc.put("Geomorphs", new Integer[]{R.layout.details_swarm_robotics, R.drawable.geo, R.color.actionbar_workshops});
layout_desc.put("Auto Spark ||", new Integer[]{R.layout.details_psoc, R.drawable.haryy, R.color.actionbar_workshops});
layout_desc.put("Digital Drawing", new Integer[]{R.layout.details_propeller_clock, R.drawable.dg, R.color.actionbar_workshops});
layout_desc.put("Drafting Mania", new Integer[]{R.layout.details_unmanned_vehicle, R.drawable.rr, R.color.actionbar_workshops});
layout_desc.put("Hackathon", new Integer[]{R.layout.details_robotic_navigation, R.drawable.hack, R.color.actionbar_workshops});
layout_desc.put("Electrocle3rique", new Integer[]{R.layout.details_sixth_sense_robotics, R.drawable.et, R.color.actionbar_workshops});
layout_desc.put("Decathlon", new Integer[]{R.layout.details_dcathlon,R.drawable.qq,R.color.actionbar_lectures});
layout_desc.put("Game of Thrones", new Integer[]{R.layout.details_got,R.drawable.game,R.color.actionbar_lectures});
layout_desc.put("CSI 3.0", new Integer[]{R.layout.details_csi,R.drawable.csi,R.color.actionbar_lectures});
layout_desc.put("Mock Parliament", new Integer[]{R.layout.details_mock,R.drawable.mock,R.color.actionbar_lectures});
layout_desc.put("Placenario 2.0", new Integer[]{R.layout.details_place,R.drawable.training_placement,R.color.actionbar_lectures});
layout_desc.put("Snazzy Fiesta", new Integer[]{R.layout.details_snazy,R.drawable.hh,R.color.actionbar_lectures});
layout_desc.put("Electroclique", new Integer[]{R.layout.details_dcathlon,R.drawable.qq,R.color.actionbar_lectures});
layout_desc.put("Photography workshop by Nikon", new Integer[] {R.layout.details_camera, R.drawable.log3, R.color.actionbar_technoholix});
layout_desc.put("Ethical Hacking", new Integer[] {R.layout.details_hack, R.drawable.et, R.color.actionbar_technoholix});
layout_desc.put("Workshop by UltraTech Cement", new Integer[] {R.layout.details_cement, R.drawable.au, R.color.actionbar_technoholix});
layout_desc.put("Home Security System", new Integer[] {R.layout.details_home, R.drawable.qwww, R.color.actionbar_technoholix});
layout_desc.put("Image Processing", new Integer[] {R.layout.details_image, R.drawable.im, R.color.actionbar_technoholix});
layout_desc.put("Civil Services Preparation", new Integer[] {R.layout.details_upsc, R.drawable.upsc, R.color.actionbar_technoholix});
addLayoutIDs();
restoreActionBar();
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
// mapFrag=(SupportMapFragment) fragmentManager.findFragmentById(R.id.map_fragment);
Fragment frag = null;
boolean show=false;
position++;
switch (position) {
case 8:
frag = EventListFragment.newInstance(EventListFragment.TYPE_LIST, getString(R.string.title_technoholix),R.color.actionbar_technoholix, R.layout.details_technoholix, filterEvents(getString(R.string.title_technoholix)));
break;
case 31:
// frag = EventListFragment.newInstance(EventListFragment.TYPE_LIST_GROUP, getString(R.string.title_initiatives), R.color.actionbar_initiatives, R.layout.fragment_initiatives, filterEvents(getString(R.string.title_initiatives)));
break;
case 5:
frag = EventListFragment.newInstance(EventListFragment.TYPE_LIST, getString(R.string.title_lectures),R.color.actionbar_lectures, R.layout.details_lectures, filterEvents(getString(R.string.title_lectures)));
break;
case 3:
frag = EventListFragment.newInstance(EventListFragment.TYPE_LIST, getString(R.string.title_competitions),R.color.actionbar_lectures, R.layout.details_carnival, filterEvents(getString(R.string.title_competitions)));
break;
case 7:
for (EventSummary es : events)
if (es.title.equals(getString(R.string.title_exhibitions))) {
frag = EventDetailsFragment.newInstance(es);
}
break;
case 9:
for (EventSummary es : events)
if (es.title.equals(getString(R.string.title_ozone))) {
frag = EventDetailsFragment.newInstance(es);
}
break;
case 6:
/* for (EventSummary es : events)
if (es.title.equals(getString(R.string.title_conference))) {
frag = EventDetailsFragment.newInstance(es);
}*/
frag=EventListFragment.newInstance(EventListFragment.TYPE_LIST_GROUP, "Our Sponsers", R.color.actionbar_home, R.layout.fragment_ssponserss,null);
break;
case 2:
frag = EventListFragment.newInstance(EventListFragment.TYPE_LIST, getString(R.string.title_ideate), R.color.actionbar_ideate, R.layout.details_ideate, filterEvents(getString(R.string.title_ideate)));
break;
case 4:
frag = EventListFragment.newInstance(EventListFragment.TYPE_LIST, getString(R.string.title_workshops), R.color.actionbar_workshops, R.layout.details_workshops, filterEvents(getString(R.string.title_workshops)));
break;
case 10:
//registration
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://docs.google.com/forms/d/1na6WGrtm8ne-XE40Gh0uUn-APzeQgJhWNgwWadHkyEM/viewform?usp=send_form"));
startActivity(i);
return;
case 11:
Intent in = new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse("https://www.google.com/maps/d/edit?mid=zpO2xvnvoSdI.k_f1Ri_IP9JY&usp=sharing"));
startActivity(in);
return;
case 12:
frag=EventListFragment.newInstance(EventListFragment.TYPE_LIST_GROUP, "Big View", R.color.actionbar_home, R.layout.fragment_ourpics,null);
break;
case 13:
frag=EventListFragment.newInstance(EventListFragment.TYPE_LIST_GROUP, getString(R.string.title_developers), R.color.actionbar_developers, R.layout.fragment_developers,null);
break;
default:
frag = EventListFragment.newInstance(EventListFragment.TYPE_LIST_GROUP, getString(R.string.title_home), R.color.actionbar_home, R.layout.fragment_main, null);
// mapFrag.getMapAsync(this);
show=true;
break;
}
fragStack.push(frag);
fragmentManager.beginTransaction()
.replace(R.id.container, frag)
.commit();
}
public ArrayList<EventSummary> filterEvents(String title) {
ArrayList<EventSummary> temp = new ArrayList<EventSummary>();
for (EventSummary es : events) {
String[] categories = es.category.split("\\+");
for (String cat : categories) {
if (cat.equals(title)) {
temp.add(es);
break;
}
}
}
return temp;
}
public void loadDetails(View v) {
EventDetailsFragment eventDetails = EventDetailsFragment.newInstance(events.get(v.getId()));
fragStack.push(eventDetails);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, eventDetails)
.commit();
}
public void loadList(View v) {
String title = (String) v.getTag();
EventListFragment eventList = EventListFragment.newInstance(
EventListFragment.TYPE_LIST,
title,
layout_desc.get(title)[2],
layout_desc.get(title)[0],
filterEvents(title));
fragStack.push(eventList);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, eventList)
.commit();
}
public SupportMapFragment loadMapFragment(){
SupportMapFragment mapFrag = SupportMapFragment.newInstance();
mapFrag.getMapAsync(this);
return mapFrag;
}
public void addLayoutIDs() {
for (EventSummary es : events) {
Integer[] temp_desc = layout_desc.get(es.title);
if (temp_desc != null) {
es.description_layout = temp_desc[0];
es.image_id = temp_desc[1];
es.actionbar_color = temp_desc[2];
} else {
// es.description_layout = R.layout.details_robowars;
}
}
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
public void setReminder(View v) {
EventSummary es = events.get((Integer) v.getTag());
String beginTime=es.time.split("-")[0];
int beginHours = Integer.valueOf(beginTime.split(":")[0]);
int beginMinutes = Integer.valueOf(beginTime.split(":")[1]);
String endTime;
try{endTime=es.time.split("-")[1];}
catch(ArrayIndexOutOfBoundsException e){
endTime=beginTime;
}
int endHours = Integer.valueOf(endTime.split(":")[0]);
int endMinutes = Integer.valueOf(endTime.split(":")[1]);
int year = Integer.valueOf(es.date.split("/")[2]);
int month = Integer.valueOf(es.date.split("/")[1]) - 1;
int day = Integer.valueOf(es.date.split("/")[0].split("\\+")[0]);
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, beginHours, beginMinutes);
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
cal.set(year, month, day, endHours, endMinutes);
intent.putExtra("endTime", cal.getTimeInMillis());
intent.putExtra("title", es.title + " @ " + es.venue);
intent.putExtra("description", es.description);
startActivity(intent);
}
public String getLatLangString(String place) {
if (place.equals(""))
return "19.130739,72.917208";
else if (place.equals("SAC"))
return "19.135369,72.913769";
else if (place.equals("Footer Field"))
return "19.134354,72.912133";
else if (place.equals("VMCC"))
return "19.132506,72.917260";
else if (place.equals("FCK"))
return "19.130484,72.915719";
else if (place.equals("H8 Road"))
return "19.133731,72.911319";
else if (place.equals("KV Grounds"))
return "19.129144,72.918190";
else if (place.equals("SOM"))
return "19.1317237,72.9157796";
else if (place.equals("Convocation Hall"))
return "19.1319587,72.914763";
else if (place.equals("Open Air Theatre"))
return "19.135369,72.913769";
else if (place.equals("Swimming Pool"))
return "19.1351579,72.9126434";
else if (place.equals("LT Back Lawns"))
return "19.1329083,72.9156243";
else if (place.equals("LA Foyer"))
return "19.1307588,72.9170093";
else if (place.equals("GG"))
return "19.1315482,72.9162513";
else if (place.equals("IC"))
return "19.13159,72.9157591";
else if (place.equals("MB Foyer"))
return "19.1324573,72.9153494";
else if (place.equals("ME"))
return "19.1333328,72.9164112";
else if (place.equals("LA"))
return "19.1307588,72.9170093";
else if (place.equals("LT"))
return "19.1323033,72.9156914";
else
return "19.1279852,72.914763";
//Done Till Here adding Geo-Coordinates
// To Add OAT, Swimming Pool, LT Back Lawns, LA Foyer, GG, IC, MB Foyer, ME, LA, LT
}
public LatLng getLatLng(String place){
String str=getLatLangString(place);
return new LatLng(Float.valueOf(str.split(",")[0]),Float.valueOf(str.split(",")[1]));
}
public void getDirections(View v) {
// EventSummary es = events.get((Integer) v.getTag());
Intent in = new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse("https://www.google.com/maps/d/edit?mid=zpO2xvnvoSdI.k_f1Ri_IP9JY&usp=sharing"));
startActivity(in);
return;
}
public void onSectionAttached(String title, int actionbar_color) {
mTitle = title;
mActionBarColor = actionbar_color;
restoreActionBar();
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
if(actionBar==null) return;
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(mActionBarColor)));
}
@Override
public void onBackPressed() {
boolean showMap=false;
if (mNavigationDrawerFragment.isDrawerOpen()) {
mNavigationDrawerFragment.closeDrawer();
} else {
fragStack.pop();
if (fragStack.empty())
super.onBackPressed();
else {
Fragment currFrag = fragStack.peek();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, currFrag)
.commit();
if(currFrag instanceof EventFragment){
if(((EventFragment)currFrag).getTitle().equals("Home"))
showMap=true;
onSectionAttached(((EventFragment) currFrag).getTitle(), ((EventFragment) currFrag).getActionBarColor());
} else if(currFrag instanceof SupportMapFragment) {
((SupportMapFragment) currFrag).getMapAsync(this);
onSectionAttached("Map", R.color.actionbar_home);
}
}
}
}
@Override
public void onMapReady(GoogleMap map) {
for(EventSummary es : events){
map.addMarker(new MarkerOptions()
.position(getLatLng(es.venue))
.title(es.title)
.icon(BitmapDescriptorFactory.fromResource(getSuperIcon(es.actionbar_color))));
}
//Add Utility Icons Here
//Food
// Convo-side
map.addMarker(new MarkerOptions()
.position(getLatLng("19.1314256,72.9143114"))
.title("Food Court Convo")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fastfood_map)));
// SAC-side
map.addMarker(new MarkerOptions()
.position(getLatLng("19.1349975,72.9139439"))
.title("Food Court SAC")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.fastfood_map)));
//Restaurant
map.addMarker(new MarkerOptions()
.position(getLatLng("19.1285848,72.9145769"))
.title("Restaurant")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_map)));
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(19.133709, 72.913284),15));
}
public int getSuperIcon(int abcolor){
//28498a
switch(abcolor){
case R.color.actionbar_lectures:
return R.drawable.lectures_map;
case R.color.actionbar_exhibitions:
return R.drawable.exhibition_map ;
case R.color.actionbar_technoholix:
return R.drawable.technoholix_map ;
case R.color.actionbar_initiatives:
return R.drawable.initiative_map ;
case R.color.actionbar_conference:
return R.drawable.conference_map ;
case R.color.actionbar_competitions:
return R.drawable.competitions_map;
case R.color.actionbar_ozone:
return R.drawable.ozone_map;
case R.color.actionbar_workshops:
return R.drawable.workshops_map ;
case R.color.actionbar_ideate:
return R.drawable.ideate_map;
default:
return R.drawable.icon_wo_bg_1;
}
}
public void fblink(View v){
String name = (String)v.getTag();
// String url = "fb://profile/";
String url = "http://www.facebook.com/";
try{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url+name));
startActivity(i);
} catch (Exception e){
url = "http://www.facebook.com/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url+name));
startActivity(i);
}
}
public void ghlink(View v){
String name = (String)v.getTag();
String url="http://www.github.com/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url+name));
startActivity(i);
}
public void registerLink(TextView tv){
String url="http://www.foreseegame.com/PromotionalActivities.aspx?paramPro=IITBombay1";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
public void launchMarket(View v){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id="+v.getTag()));
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id="+v.getTag()));
startActivity(intent);
}
}
}
| gpl-2.0 |
judgels/jophiel | app/org/iatoki/judgels/jophiel/activity/ActivityLogService.java | 204 | package org.iatoki.judgels.jophiel.activity;
import com.google.inject.ImplementedBy;
@ImplementedBy(ActivityLogServiceImpl.class)
public interface ActivityLogService extends BaseActivityLogService {
}
| gpl-2.0 |
zhangjining9517/zhanglibrary | zhangLibrary/src/com/zhang/zhanglibrary/adapter/Adapter_Base.java | 2132 | package com.zhang.zhanglibrary.adapter;
import java.util.LinkedList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* BaseAdapter的实现类
*
* @param <T>
*/
public abstract class Adapter_Base<T> extends BaseAdapter {
protected Context m_Context;
protected LayoutInflater m_Inflater;
public Adapter_Base(Context ctx) {
this.m_Context = ctx;
m_Inflater = LayoutInflater.from(m_Context);
}
private final List<T> mList = new LinkedList<T>();
/**
* 获取当前List
*
* @return
*/
public List<T> getList() {
return mList;
}
/**
* 添加一个List
*
* @param list
*/
public void appendToList(List<T> list) {
if (list == null) {
return;
}
mList.addAll(list);
notifyDataSetChanged();
}
/**
* 功能:添加一个对象
*
* @param t
*/
public void append(T t) {
if (t == null) {
return;
}
mList.add(t);
notifyDataSetChanged();
}
/**
* 添加一个List到第一个
*
* @param list
*/
public void appendToTopList(List<T> list) {
if (list == null) {
return;
}
mList.addAll(0, list);
notifyDataSetChanged();
}
/**
* 清除List
*/
public void clear() {
mList.clear();
notifyDataSetChanged();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
if (position > mList.size() - 1) {
return null;
}
return mList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (position == getCount() - 1) {
onReachBottom();
}
return getExView(position, convertView, parent);
}
protected abstract View getExView(int position, View convertView,
ViewGroup parent);
/**
* 滑动到底部了
*/
protected void onReachBottom() {
}
}
| gpl-2.0 |
rafaelkalan/metastone | src/main/java/net/demilich/metastone/gui/playmode/GameToken.java | 2945 | package net.demilich.metastone.gui.playmode;
import java.io.IOException;
import javafx.beans.binding.Bindings;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.effect.ColorInput;
import javafx.scene.effect.Effect;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import net.demilich.metastone.gui.DigitFactory;
import net.demilich.metastone.gui.IconFactory;
public class GameToken extends BorderPane {
protected StackPane target;
private ImageView targetButton;
private EventHandler<MouseEvent> existingEventHandler;
public GameToken(String fxml) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/" + fxml));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
createTargetButton();
}
private void createTargetButton() {
target = (StackPane) lookup("#targetAnchor");
Image image = IconFactory.getTargetIcon();
ImageView targetIcon = new ImageView(image);
targetIcon.setClip(new ImageView(image));
ColorAdjust monochrome = new ColorAdjust();
monochrome.setSaturation(-1.0);
Blend red = new Blend(BlendMode.MULTIPLY, monochrome,
new ColorInput(0, 0, targetIcon.getImage().getWidth(), targetIcon.getImage().getHeight(), Color.RED));
Blend green = new Blend(BlendMode.MULTIPLY, monochrome,
new ColorInput(0, 0, targetIcon.getImage().getWidth(), targetIcon.getImage().getHeight(), new Color(0, 1, 0, 0.5)));
targetButton = targetIcon;
targetIcon.effectProperty().bind(Bindings.when(targetButton.hoverProperty()).then((Effect) green).otherwise((Effect) red));
targetButton.setId("target_button");
hideTargetMarker();
target.getChildren().add(targetButton);
}
public StackPane getAnchor() {
return target;
}
public void hideTargetMarker() {
targetButton.setVisible(false);
}
protected void setScoreValue(Group group, int value) {
setScoreValue(group, value, value);
}
protected void setScoreValue(Group group, int value, int baseValue) {
Color color = Color.WHITE;
if (value > baseValue) {
color = Color.GREEN;
} else if (value < baseValue) {
color = Color.RED;
}
DigitFactory.showPreRenderedDigits(group, value, color);
}
public void showTargetMarker(EventHandler<MouseEvent> clickedHander) {
if (existingEventHandler != null) {
targetButton.removeEventHandler(MouseEvent.MOUSE_CLICKED, existingEventHandler);
}
targetButton.addEventHandler(MouseEvent.MOUSE_CLICKED, clickedHander);
targetButton.setVisible(true);
existingEventHandler = clickedHander;
}
}
| gpl-2.0 |