repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
tair/tairwebapp | src/org/tair/processor/microarray/excel/FloatDataCell.java | 2191 | //------------------------------------------------------------------------------
// Copyright (c) 2010 Carnegie Institution for Science. All rights reserved
// $Revision: 1.1 $
// $Date: 2004/07/06 16:27:45 $
//------------------------------------------------------------------------------
package org.tair.processor.microarray.excel;
import jxl.Sheet;
import org.tair.utilities.InvalidCellException;
/**
* FloatDataCell extends ExcelDataCell to retrieve data submitted in
* an Excel column as a Float value.
*/
public class FloatDataCell extends ExcelDataCell {
/**
* Creates an instance of FloatDataCell cell to represent the cell at
* submitted column index.
*
* @param name Display name of column represented by this object
* @param columnIndex Numeric index of column within data sheet
* @param required If <code>true</code> column is a required field
* that must have data; if <code>false</code> column is not a required
* field
*/
public FloatDataCell( String name, int columnIndex, boolean required ) {
super( name, columnIndex, required );
}
/**
* Retrieves and validates data submitted for this column in
* submitted row of data and returns value as a Float object.
*
* <p>
* InvalidCellException will be thrown if submitted data fails superclass
* validation or if data cannot be transformed into a Float value.
*
* @param sheet Sheet object representing Excel data sheet being parsed
* @param row Row to get column data for
* @return Data in cell as a Float object
* @throws InvalidCellException if any validation errors occur
*/
public Object getData( Sheet sheet, int row ) throws InvalidCellException {
// use superclass to get String data to take advantage of
// validation for required data and illegal characters
String contents = (String) super.getData( sheet, row );
Float floatValue = null;
if ( contents != null ) {
try {
floatValue = new Float( contents );
} catch ( NumberFormatException nfe ) {
throw new InvalidCellException( "Invalid number: " + contents );
}
}
return floatValue;
}
}
| gpl-3.0 |
srnsw/xena | plugins/audio/ext/src/tritonus/src/classes/org/tritonus/lowlevel/ogg/StreamState.java | 2952 | /*
* StreamState.java
*
* This file is part of Tritonus: http://www.tritonus.org/
*/
/*
* Copyright (c) 2000 - 2001 by Matthias Pfisterer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
|<--- this code is formatted to fit into 80 columns --->|
*/
package org.tritonus.lowlevel.ogg;
import org.tritonus.share.TDebug;
/** Wrapper for ogg_stream_state.
*/
public class StreamState
{
static
{
Ogg.loadNativeLibrary();
if (TDebug.TraceOggNative)
{
setTrace(true);
}
}
/**
* Holds the pointer to ogg_stream_state
* for the native code.
* This must be long to be 64bit-clean.
*/
@SuppressWarnings("unused")
private long m_lNativeHandle;
public StreamState()
{
if (TDebug.TraceOggNative) { TDebug.out("StreamState.<init>(): begin"); }
int nReturn = malloc();
if (nReturn < 0)
{
throw new RuntimeException("malloc of ogg_stream_state failed");
}
if (TDebug.TraceOggNative) { TDebug.out("StreamState.<init>(): end"); }
}
public void finalize()
{
// TODO: call free()
// call super.finalize() first or last?
// and introduce a flag if free() has already been called?
}
private native int malloc();
public native void free();
/** Calls ogg_stream_init().
*/
public native int init(int nSerialNo);
/** Calls ogg_stream_clear().
*/
public native int clear();
/** Calls ogg_stream_reset().
*/
public native int reset();
/** Calls ogg_stream_destroy().
*/
public native int destroy();
/** Calls ogg_stream_eos().
*/
public native boolean isEOSReached();
/** Calls ogg_stream_packetin().
*/
public native int packetIn(Packet packet);
/** Calls ogg_stream_pageout().
*/
public native int pageOut(Page page);
/** Calls ogg_stream_flush().
*/
public native int flush(Page page);
/** Calls ogg_stream_pagein().
*/
public native int pageIn(Page page);
/** Calls ogg_stream_packetout().
*/
public native int packetOut(Packet packet);
/** Calls ogg_stream_packetpeek().
*/
public native int packetPeek(Packet packet);
private static native void setTrace(boolean bTrace);
}
/*** StreamState.java ***/
| gpl-3.0 |
Ostrich-Emulators/semtool | gui/src/main/java/com/ostrichemulators/semtool/ui/components/IriComboBox.java | 6576 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ostrichemulators.semtool.ui.components;
import com.ostrichemulators.semtool.ui.components.renderers.LabeledPairRenderer;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComboBox.KeySelectionManager;
import com.ostrichemulators.semtool.util.Constants;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
/**
*
* @author ryan
*/
public class IriComboBox extends JComboBox<IRI> {
private static final ValueFactory vf = SimpleValueFactory.getInstance();
public static final IRI MISSING_CONCEPT = vf.createIRI( "error://missing_concept" );
public static final IRI BAD_FILL = vf.createIRI( "error://invalid_fill" );
public static final IRI FETCHING = vf.createIRI( "error://doing_fetch" );
protected IriComboBox.UriModel model = new IriComboBox.UriModel();
protected LabeledPairRenderer urirenderer = LabeledPairRenderer.getUriPairRenderer();
public IriComboBox( IRI[] array ) {
this( Arrays.asList( array ) );
}
public IriComboBox( Collection<IRI> array ) {
this();
model.reset( array );
}
public IriComboBox() {
setModel( model );
setRenderer( urirenderer );
setKeySelectionManager( new IriComboBoxKeySelectionManager() );
}
public Map<IRI, String> getLabelMap() {
return urirenderer.getCachedLabels();
}
public void clear() {
model.removeAllElements();
}
public void setData( Collection<IRI> uris ) {
model.reset( uris );
}
public void setData( Map<IRI, String> uris ) {
List<IriLabelPair> list = new ArrayList<>();
for ( Map.Entry<IRI, String> en : uris.entrySet() ) {
list.add( new IriLabelPair( en.getKey(), en.getValue() ) );
}
Collections.sort( list );
List<IRI> urilist = new ArrayList<>();
for ( IriLabelPair p : list ) {
urilist.add( p.getUri() );
}
model.reset( urilist );
urirenderer.cache( uris );
urirenderer.cache( MISSING_CONCEPT, "Concept Doesn't Exist in DB" );
urirenderer.cache( BAD_FILL, "Invalid Fill Param" );
urirenderer.cache( FETCHING, "Fetching" );
urirenderer.cache( Constants.ANYNODE, "None" );
}
public void addData( IRI uri, String label ) {
model.addElement( uri );
urirenderer.cache( uri, label );
}
public IRI getSelectedIri() {
int idx = getSelectedIndex();
return ( idx >= 0 ? getItemAt( idx ) : null );
}
public UriModel getUriModel() {
return model;
}
public static class UriModel extends DefaultComboBoxModel<IRI> {
private final List<IRI> uris = new ArrayList<>();
private IRI selected;
public UriModel() {
}
public UriModel( IRI[] items ) {
this( Arrays.asList( items ) );
}
public UriModel( Collection<IRI> col ) {
uris.addAll( col );
}
@Override
public void removeAllElements() {
uris.clear();
}
@Override
public void removeElementAt( int index ) {
uris.remove( index );
}
@Override
public void insertElementAt( IRI anObject, int index ) {
uris.add( index, anObject );
}
@Override
public void addElement( IRI anObject ) {
uris.add( anObject );
}
@Override
public int getIndexOf( Object anObject ) {
return uris.indexOf( anObject );
}
@Override
public IRI getElementAt( int index ) {
return uris.get( index );
}
@Override
public int getSize() {
return uris.size();
}
@Override
public Object getSelectedItem() {
return selected;
}
@Override
public void setSelectedItem( Object anObject ) {
selected = IRI.class.cast( anObject );
}
public void reset( Collection<IRI> urilist ) {
uris.clear();
uris.addAll( urilist );
if ( !urilist.isEmpty() ) {
setSelectedItem( uris.get( 0 ) );
}
fireContentsChanged( this, 0, urilist.size() );
}
public Collection<IRI> elements() {
return new ArrayList<>( uris );
}
}
public static class IriLabelPair implements Comparable<IriLabelPair> {
private final IRI uri;
private final String label;
public IriLabelPair( IRI uri, String label ) {
this.uri = uri;
this.label = label;
}
@Override
public int compareTo( IriLabelPair t ) {
return getLabel().compareTo( t.getLabel() );
}
public String getLabel() {
return ( null == label ? uri.getLocalName() : label );
}
public IRI getUri() {
return uri;
}
}
class IriComboBoxKeySelectionManager implements KeySelectionManager, Serializable {
private static final long serialVersionUID = 1L;
@Override
public int selectionForKey( char aKey, ComboBoxModel aModel ) {
int i, c;
int currentSelection = -1;
Object selectedItem = aModel.getSelectedItem();
String v;
String pattern;
if ( selectedItem != null ) {
for ( i = 0, c = aModel.getSize(); i < c; i++ ) {
if ( selectedItem == aModel.getElementAt( i ) ) {
currentSelection = i;
break;
}
}
}
pattern = ( "" + aKey ).toLowerCase();
aKey = pattern.charAt( 0 );
for ( i = ++currentSelection, c = aModel.getSize(); i < c; i++ ) {
Object elem = aModel.getElementAt( i );
if ( !( elem instanceof IRI ) ) {
return -1;
}
IRI uri = IRI.class.cast( elem );
if ( uri != null && uri.getLocalName() != null ) {
v = uri.getLocalName().toLowerCase();
if ( v.length() > 0 && v.charAt( 0 ) == aKey ) {
return i;
}
}
}
for ( i = 0; i < currentSelection; i++ ) {
Object elem = aModel.getElementAt( i );
if ( !( elem instanceof IRI ) ) {
return -1;
}
IRI uri = IRI.class.cast( elem );
if ( uri != null && uri.getLocalName() != null ) {
v = uri.getLocalName().toLowerCase();
if ( v.length() > 0 && v.charAt( 0 ) == aKey ) {
return i;
}
}
}
return -1;
}
}
}
| gpl-3.0 |
winder/Universal-G-Code-Sender | ugs-platform/ugs-platform-gcode-editor/src/main/java/com/willwinder/ugs/nbp/editor/highlight/GcodeHighlightsLayerFactory.java | 2508 | /*
* Copyright (C) 2021 Will Winder
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.willwinder.ugs.nbp.editor.highlight;
import com.willwinder.ugs.nbp.editor.GcodeLanguageConfig;
import org.netbeans.api.editor.mimelookup.MimeRegistration;
import org.netbeans.api.editor.mimelookup.MimeRegistrations;
import org.netbeans.spi.editor.highlighting.HighlightsLayer;
import org.netbeans.spi.editor.highlighting.ZOrder;
import javax.swing.text.Document;
@MimeRegistrations({
@MimeRegistration(mimeType = GcodeLanguageConfig.MIME_TYPE, service = org.netbeans.spi.editor.highlighting.HighlightsLayerFactory.class),
@MimeRegistration(mimeType = GcodeLanguageConfig.MIME_TYPE, service = org.netbeans.spi.editor.highlighting.HighlightsLayerFactory.class)
})
public class GcodeHighlightsLayerFactory implements org.netbeans.spi.editor.highlighting.HighlightsLayerFactory {
/**
* Returns an instance of the "Run from here" highlighter container.
* If it already exists it will be returned, otherwise a new one will be added.
*
* @param doc the current document
* @return an instance of the highlighter
*/
public static RunFromHereHighlightContainer getRunFromHereHighlighter(Document doc) {
RunFromHereHighlightContainer highlighter = (RunFromHereHighlightContainer) doc.getProperty(RunFromHereHighlightContainer.class);
if (highlighter == null) {
highlighter = new RunFromHereHighlightContainer(doc);
doc.putProperty(RunFromHereHighlightContainer.class, highlighter);
}
return highlighter;
}
@Override
public HighlightsLayer[] createLayers(Context context) {
return new HighlightsLayer[]{
HighlightsLayer.create(RunFromHereHighlightContainer.class.getName(), ZOrder.TOP_RACK, true, getRunFromHereHighlighter(context.getDocument()))
};
}
}
| gpl-3.0 |
iTitus/GimmeTime | src/main/java/io/github/iTitus/gimmetime/common/util/StringUtil.java | 200 | package io.github.iTitus.gimmetime.common.util;
public class StringUtil {
public static String makeNDigits(String s, int n, char c) {
while (s.length() < n) {
s = c + s;
}
return s;
}
}
| gpl-3.0 |
ivoanjo/phd-jaspexmls | jaspex-mls/src/test/NewSpecExample36.java | 1219 | /*
* jaspex-mls: a Java Software Speculative Parallelization Framework
* Copyright (C) 2015 Ivo Anjo <ivo.anjo@ist.utl.pt>
*
* This file is part of jaspex-mls.
*
* jaspex-mls 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.
*
* jaspex-mls 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 jaspex-mls. If not, see <http://www.gnu.org/licenses/>.
*/
package test;
/** Testcase para problema de recursão infinita quando se chama o super() **/
public class NewSpecExample36 {
private static class A {
void m() {
System.out.println("Ok!");
}
}
private static class B extends A {
@Override
void m() {
super.m();
f();
}
void f() { }
}
private NewSpecExample36() { }
public static void main(String[] args) {
new B().m();
}
}
| gpl-3.0 |
flower-platform/flower-platform-4 | org.flowerplatform.codesync.regex/src/org/flowerplatform/codesync/regex/controller/RegexWithActionsProcessor.java | 1143 | package org.flowerplatform.codesync.regex.controller;
import static org.flowerplatform.codesync.regex.CodeSyncRegexConstants.FULL_REGEX;
import static org.flowerplatform.core.CoreConstants.NAME;
import org.flowerplatform.core.config_processor.IConfigNodeProcessor;
import org.flowerplatform.core.node.NodeService;
import org.flowerplatform.core.node.remote.Node;
import org.flowerplatform.core.node.remote.ServiceContext;
import org.flowerplatform.util.controller.AbstractController;
import org.flowerplatform.util.regex.RegexConfiguration;
import org.flowerplatform.util.regex.RegexWithActions;
/**
* @author Elena Posea
*/
public class RegexWithActionsProcessor extends AbstractController implements IConfigNodeProcessor<RegexWithActions, RegexConfiguration> {
@Override
public RegexWithActions processConfigNode(Node node, RegexConfiguration parentProcessedDataStructure, ServiceContext<NodeService> context) {
RegexWithActions rwa = new RegexWithActions((String) node.getPropertyValue(NAME),
(String) node.getPropertyValue(FULL_REGEX));
parentProcessedDataStructure.add(rwa);
return rwa;
}
}
| gpl-3.0 |
shengqh/RcpaBioSolution | src/cn/ac/rcpa/bio/tools/modification/IdentifiedPeptideDifferentStateStatisticsCalculatorUI.java | 1771 | package cn.ac.rcpa.bio.tools.modification;
import cn.ac.rcpa.Constants;
import cn.ac.rcpa.bio.processor.AbstractFileProcessorWithArgumentUI;
import cn.ac.rcpa.bio.processor.IFileProcessor;
import cn.ac.rcpa.bio.tools.solution.CommandType;
import cn.ac.rcpa.bio.tools.solution.IRcpaBioToolCommand;
import cn.ac.rcpa.utils.OpenFileArgument;
/**
* Õâ¸ö³ÌÐòÓÃÓÚͳ¼ÆBuildSummaryµÄëĶÎÎļþÖУ¬Í¬Ê±³öÏÖ·ÇÐÞÊκͶàÖÖÐÞÊΣ¬·ÇÐÞÊκÍÒ»ÖÖÐÞÊΣ¬Ö»ÓжàÖÖÐÞÊÎÕâÈýÖÖÀàÐ͵ÄëĶÎÊýÁ¿¡£
*
* @author Quanhu Sheng
*
*/
public class IdentifiedPeptideDifferentStateStatisticsCalculatorUI extends
AbstractFileProcessorWithArgumentUI {
private static final String title = "Identified Peptide Different Modification State Statistic Calculaotr";
public IdentifiedPeptideDifferentStateStatisticsCalculatorUI() {
super(Constants.getSQHTitle(title,
IdentifiedPeptideDifferentStateStatisticsCalculator.version),
new OpenFileArgument("BuildSummary Peptides", "peptides"),
"Modification Aminoacids");
}
public static void main(String[] args) {
new IdentifiedPeptideDifferentStateStatisticsCalculatorUI().showSelf();
}
@Override
protected IFileProcessor getProcessor() {
return new IdentifiedPeptideDifferentStateStatisticsCalculator(
getArgument());
}
public static class Command implements IRcpaBioToolCommand {
public Command() {
}
public String[] getMenuNames() {
return new String[] { CommandType.Modification };
}
public String getCaption() {
return title;
}
public void run() {
IdentifiedPeptideDifferentStateStatisticsCalculatorUI.main(new String[0]);
}
public String getVersion() {
return IdentifiedPeptideDifferentStateStatisticsCalculator.version;
}
}
}
| gpl-3.0 |
afnogueira/Cerberus | source/src/main/java/org/cerberus/service/ILoadTestCaseService.java | 1161 | /*
* Cerberus Copyright (C) 2013 vertigo17
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of Cerberus.
*
* Cerberus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cerberus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cerberus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cerberus.service;
import java.util.List;
import org.cerberus.entity.TestCaseExecution;
import org.cerberus.entity.TCase;
import org.cerberus.entity.TestCaseStep;
/**
* @author bcivel
*/
public interface ILoadTestCaseService {
void loadTestCase(TestCaseExecution tCExecution);
List<TestCaseStep> loadTestCaseStep(TCase testCase);
}
| gpl-3.0 |
RealizedMC/Duels | duels-plugin/src/main/java/me/realized/duels/command/commands/duel/subcommands/DenyCommand.java | 1517 | package me.realized.duels.command.commands.duel.subcommands;
import me.realized.duels.DuelsPlugin;
import me.realized.duels.api.event.request.RequestDenyEvent;
import me.realized.duels.command.BaseCommand;
import me.realized.duels.request.RequestImpl;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class DenyCommand extends BaseCommand {
public DenyCommand(final DuelsPlugin plugin) {
super(plugin, "deny", "deny [player]", "Declines a duel request.", 2, true);
}
@Override
protected void execute(final CommandSender sender, final String label, final String[] args) {
final Player player = (Player) sender;
final Player target = Bukkit.getPlayerExact(args[1]);
if (target == null || !player.canSee(target)) {
lang.sendMessage(sender, "ERROR.player.not-found", "name", args[1]);
return;
}
final RequestImpl request;
if ((request = requestManager.remove(target, player)) == null) {
lang.sendMessage(sender, "ERROR.duel.no-request", "name", target.getName());
return;
}
final RequestDenyEvent event = new RequestDenyEvent(player, target, request);
plugin.getServer().getPluginManager().callEvent(event);
lang.sendMessage(player, "COMMAND.duel.request.deny.receiver", "name", target.getName());
lang.sendMessage(target, "COMMAND.duel.request.deny.sender", "name", player.getName());
}
}
| gpl-3.0 |
tarekauel/WinnerGame | WinnerGame/tests/templates/ConnectionTest.java | 2436 | package templates;
import static org.junit.Assert.assertEquals;
import message.IMessage;
import message.LoginConfirmationMessage;
import message.LoginMessage;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import server.connection.Server;
import client.connection.Client;
import constant.Constant;
public class ConnectionTest {
private static Server server = null;
private static Client client1 = null;
private static Client client2 = null;
private static Client client3 = null;
private static Client client4 = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
String ip = "127.0.0.1";
int port = Constant.Server.TCP_PORT;
server = Server.getServer();
client1 = new Client();
client1.connect(ip, port);
client2 = new Client();
client2.connect(ip, port);
client3 = new Client();
client3.connect(ip, port);
client4 = new Client();
client4.connect(ip, port);
}
@After
public void afterLoginTest() {
server.getPlayerList().clear();
}
@Test
public void loginTest1() {
String name="Max";
String password="123456";
String chosenLocation="Deutschland";
LoginMessage loginMessage = new LoginMessage(name, password, chosenLocation);
client1.writeMessage(loginMessage);
IMessage message = client1.readMessage();
assertEquals("LoginConfirmationMessage", message.getType());
LoginConfirmationMessage loginConfirmationMessage = (LoginConfirmationMessage) message;
assertEquals(true, loginConfirmationMessage.getSuccess());
}
@Test
public void loginTestSameName() {
String name="Michael";
String password="123456";
String chosenLocation="Deutschland";
LoginMessage loginMessage = new LoginMessage(name, password, chosenLocation);
client3.writeMessage(loginMessage);
IMessage message3 = client3.readMessage();
assertEquals("LoginConfirmationMessage", message3.getType());
LoginConfirmationMessage loginConfirmationMessage3 = (LoginConfirmationMessage) message3;
assertEquals(true, loginConfirmationMessage3.getSuccess());
client4.writeMessage(loginMessage);
IMessage message4 = client4.readMessage();
LoginConfirmationMessage loginConfirmationMessage4 = (LoginConfirmationMessage) message4;
assertEquals(false, loginConfirmationMessage4.getSuccess());
}
}
| gpl-3.0 |
TheLanguageArchive/lamus2 | jar/src/main/java/nl/mpi/lamus/service/implementation/LamusWorkspaceService.java | 15996 | /*
* Copyright (C) 2012 Max Planck Institute for Psycholinguistics
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.mpi.lamus.service.implementation;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipInputStream;
import nl.mpi.archiving.corpusstructure.core.NodeNotFoundException;
import nl.mpi.lamus.archive.ArchiveHandleHelper;
import nl.mpi.lamus.dao.WorkspaceDao;
import nl.mpi.lamus.exception.CrawlerInvocationException;
import nl.mpi.lamus.exception.DisallowedPathException;
import nl.mpi.lamus.exception.MetadataValidationException;
import nl.mpi.lamus.exception.NodeAccessException;
import nl.mpi.lamus.exception.PreLockedNodeException;
import nl.mpi.lamus.exception.ProtectedNodeException;
import nl.mpi.lamus.exception.WorkspaceAccessException;
import nl.mpi.lamus.exception.WorkspaceNodeNotFoundException;
import nl.mpi.lamus.exception.WorkspaceNotFoundException;
import nl.mpi.lamus.service.WorkspaceService;
import nl.mpi.lamus.exception.WorkspaceException;
import nl.mpi.lamus.exception.WorkspaceExportException;
import nl.mpi.lamus.exception.WorkspaceImportException;
import nl.mpi.lamus.workspace.exporting.WorkspaceCorpusStructureExporter;
import nl.mpi.lamus.workspace.management.WorkspaceNodeLinkManager;
import nl.mpi.lamus.workspace.management.WorkspaceAccessChecker;
import nl.mpi.lamus.workspace.management.WorkspaceManager;
import nl.mpi.lamus.workspace.management.WorkspaceNodeManager;
import nl.mpi.lamus.workspace.model.Workspace;
import nl.mpi.lamus.workspace.model.WorkspaceNode;
import nl.mpi.lamus.workspace.replace.implementation.LamusNodeReplaceManager;
import nl.mpi.lamus.workspace.upload.WorkspaceUploader;
import nl.mpi.lamus.workspace.importing.implementation.ImportProblem;
import nl.mpi.lamus.workspace.model.WorkspaceNodeType;
import nl.mpi.lamus.workspace.upload.implementation.ZipUploadResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
/**
* @see WorkspaceService
*
* @author guisil
*/
public class LamusWorkspaceService implements WorkspaceService {
private static final Logger logger = LoggerFactory.getLogger(LamusWorkspaceService.class);
private final WorkspaceAccessChecker nodeAccessChecker;
private final ArchiveHandleHelper archiveHandleHelper;
private final WorkspaceManager workspaceManager;
protected final WorkspaceDao workspaceDao;
private final WorkspaceUploader workspaceUploader;
private final WorkspaceNodeLinkManager workspaceNodeLinkManager;
private final WorkspaceNodeManager workspaceNodeManager;
private final LamusNodeReplaceManager nodeReplaceManager;
private final WorkspaceCorpusStructureExporter workspaceCorpusStructureExporter;
public LamusWorkspaceService(WorkspaceAccessChecker aChecker, ArchiveHandleHelper aHandleHelper,
WorkspaceManager wsManager, WorkspaceDao wsDao, WorkspaceUploader wsUploader,
WorkspaceNodeLinkManager wsnLinkManager, WorkspaceNodeManager wsNodeManager,
LamusNodeReplaceManager topNodeReplaceManager, WorkspaceCorpusStructureExporter wsCsExporter) {
this.nodeAccessChecker = aChecker;
this.archiveHandleHelper = aHandleHelper;
this.workspaceManager = wsManager;
this.workspaceDao = wsDao;
this.workspaceUploader = wsUploader;
this.workspaceNodeLinkManager = wsnLinkManager;
this.workspaceNodeManager = wsNodeManager;
this.nodeReplaceManager = topNodeReplaceManager;
this.workspaceCorpusStructureExporter = wsCsExporter;
}
/**
* @see WorkspaceService#createWorkspace(java.lang.String, java.net.URI)
*/
@Override
public Workspace createWorkspace(String userID, URI archiveNodeURI)
throws NodeAccessException, WorkspaceImportException, NodeNotFoundException {
logger.debug("Triggered creation of workspace; userID: " + userID + "; archiveNodeURI: " + archiveNodeURI);
if(userID == null || archiveNodeURI == null) {
throw new IllegalArgumentException("Both userID and archiveNodeURI should not be null");
}
URI archiveUriToUse = this.archiveHandleHelper.getArchiveHandleForNode(archiveNodeURI);
if(archiveUriToUse == null) {
archiveUriToUse = archiveNodeURI;
}
try {
workspaceDao.preLockNode(archiveUriToUse);
this.nodeAccessChecker.ensureWorkspaceCanBeCreated(userID, archiveNodeURI);
return this.workspaceManager.createWorkspace(userID, archiveUriToUse);
} catch(DuplicateKeyException ex) {
throw new PreLockedNodeException("Node " + archiveUriToUse + " already pre-locked", archiveUriToUse);
} finally {
workspaceDao.removeNodePreLock(archiveUriToUse);
}
}
/**
* @see WorkspaceService#deleteWorkspace(java.lang.String, int, boolean)
*/
@Override
public void deleteWorkspace(String userID, int workspaceID, boolean keepUnlinkedFiles)
throws WorkspaceNotFoundException, WorkspaceAccessException, WorkspaceExportException, IOException {
logger.debug("Triggered deletion of workspace; userID: " + userID + "; workspaceID: " + workspaceID);
this.nodeAccessChecker.ensureUserCanDeleteWorkspace(userID, workspaceID);
this.workspaceManager.deleteWorkspace(workspaceID, keepUnlinkedFiles);
}
/**
* @see WorkspaceService#submitWorkspace(java.lang.String, int, boolean)
*/
@Override
public void submitWorkspace(String userID, int workspaceID, boolean keepUnlinkedFiles)
throws WorkspaceNotFoundException, WorkspaceAccessException,
WorkspaceExportException, MetadataValidationException {
logger.debug("Triggered submission of workspace; userID: " + userID + "; workspaceID: " + workspaceID);
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, workspaceID);
this.workspaceManager.submitWorkspace(workspaceID, keepUnlinkedFiles);
}
/**
* @see WorkspaceService#triggerCrawlForWorkspace(java.lang.String, int)
*/
@Override
public void triggerCrawlForWorkspace(String userID, int workspaceID)
throws WorkspaceNotFoundException, WorkspaceAccessException, CrawlerInvocationException {
logger.debug("Triggered crawl of workspace; userID: " + userID + "; workspaceID: " + workspaceID);
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, workspaceID);
this.workspaceCorpusStructureExporter.triggerWorkspaceCrawl(this.workspaceDao.getWorkspace(workspaceID));
}
/**
* @see WorkspaceService#getWorkspace(int)
*/
@Override
public Workspace getWorkspace(int workspaceID)
throws WorkspaceNotFoundException {
logger.debug("Triggered retrieval of workspace; workspaceID: " + workspaceID);
return this.workspaceDao.getWorkspace(workspaceID);
}
/**
* @see WorkspaceService#listUserWorkspaces(java.lang.String)
*/
@Override
public Collection<Workspace> listUserWorkspaces(String userID) {
logger.debug("Triggered retrieval of all workspaces for user; userID: " + userID);
return this.workspaceDao.getWorkspacesForUser(userID);
}
/**
* @see WorkspaceService#listAllWorkspaces()
*/
@Override
public List<Workspace> listAllWorkspaces() {
logger.debug("Triggered retrieval of all workspaces");
return this.workspaceDao.getAllWorkspaces();
}
/**
* @see WorkspaceService#userHasWorkspaces(java.lang.String)
*/
@Override
public boolean userHasWorkspaces(String userID) {
return !listUserWorkspaces(userID).isEmpty();
}
/**
* @see WorkspaceService#openWorkspace(java.lang.String, int)
*/
@Override
public Workspace openWorkspace(String userID, int workspaceID)
throws WorkspaceNotFoundException, WorkspaceAccessException, IOException {
logger.debug("Triggered opening of workspace; userID: " + userID + "; workspaceID: " + workspaceID);
if(userID == null) {
throw new IllegalArgumentException("userID should not be null");
}
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, workspaceID);
return this.workspaceManager.openWorkspace(workspaceID);
}
/**
* @see WorkspaceService#getNode(int)
*/
@Override
public WorkspaceNode getNode(int nodeID)
throws WorkspaceNodeNotFoundException {
logger.debug("Triggered retrieval of node; nodeID: " + nodeID);
return this.workspaceDao.getWorkspaceNode(nodeID);
}
/**
* @see WorkspaceService#getChildNodes(int)
*/
@Override
public Collection<WorkspaceNode> getChildNodes(int nodeID) {
logger.debug("Triggered retrieval of child nodes; nodeID: " + nodeID);
return this.workspaceDao.getChildWorkspaceNodes(nodeID);
}
/**
* @see WorkspaceService#addNode(java.lang.String, nl.mpi.lamus.workspace.model.WorkspaceNode)
*/
@Override
public void addNode(String userID, WorkspaceNode node) throws WorkspaceNotFoundException, WorkspaceAccessException {
logger.debug("Triggered node addition; userID: " + userID + "nodeWorkspaceURL: " + node.getWorkspaceURL());
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, node.getWorkspaceID());
this.workspaceDao.addWorkspaceNode(node);
}
/**
* @see WorkspaceService#linkNodes(java.lang.String, nl.mpi.lamus.workspace.model.WorkspaceNode, nl.mpi.lamus.workspace.model.WorkspaceNode)
*/
@Override
public void linkNodes(String userID, WorkspaceNode parentNode, WorkspaceNode childNode)
throws WorkspaceNotFoundException, WorkspaceAccessException, WorkspaceException, ProtectedNodeException {
logger.debug("Triggered node linking; userID: " + userID + "; parentNodeID: " + parentNode.getWorkspaceNodeID() + "; childNodeID: " + childNode.getWorkspaceNodeID());
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, parentNode.getWorkspaceID());
this.workspaceNodeLinkManager.removeArchiveUriFromUploadedNodeRecursively(childNode, true);
this.workspaceNodeLinkManager.linkNodes(parentNode, childNode, WorkspaceNodeType.RESOURCE_INFO.equals(childNode.getType()));
}
/**
* @see WorkspaceService#unlinkNodes(java.lang.String, nl.mpi.lamus.workspace.model.WorkspaceNode, nl.mpi.lamus.workspace.model.WorkspaceNode)
*/
@Override
public void unlinkNodes(String userID, WorkspaceNode parentNode, WorkspaceNode childNode)
throws WorkspaceNotFoundException, WorkspaceAccessException, WorkspaceException, ProtectedNodeException {
logger.debug("Triggered node unlinking; userID: " + userID + "; parentNodeID: " + parentNode.getWorkspaceNodeID() + "; childNodeID: " + childNode.getWorkspaceNodeID());
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, parentNode.getWorkspaceID());
this.workspaceNodeLinkManager.unlinkNodes(parentNode, childNode);
}
/**
* @see WorkspaceService#deleteNode(java.lang.String, nl.mpi.lamus.workspace.model.WorkspaceNode)
*/
@Override
public void deleteNode(String userID, WorkspaceNode node)
throws WorkspaceNotFoundException, WorkspaceAccessException, WorkspaceException, ProtectedNodeException {
logger.debug("Triggered node deletion; userID: " + userID + "; nodeID: " + node.getWorkspaceNodeID());
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, node.getWorkspaceID());
this.workspaceNodeManager.deleteNodesRecursively(node);
}
/**
* @see WorkspaceService#replaceTree(java.lang.String, nl.mpi.lamus.workspace.model.WorkspaceNode, nl.mpi.lamus.workspace.model.WorkspaceNode)
*/
@Override
public void replaceTree(String userID, WorkspaceNode oldTreeTopNode, WorkspaceNode newTreeTopNode, WorkspaceNode parentNode)
throws WorkspaceNotFoundException, WorkspaceAccessException, WorkspaceException, ProtectedNodeException {
logger.debug("Triggered tree replacement; userID: " + userID + "; oldNodeID: " + oldTreeTopNode.getWorkspaceNodeID() + "; newNodeID: " + newTreeTopNode.getWorkspaceNodeID());
this.nodeAccessChecker.ensureUserHasAccessToWorkspace(userID, oldTreeTopNode.getWorkspaceID());
this.nodeReplaceManager.replaceTree(oldTreeTopNode, newTreeTopNode, parentNode);
}
/**
* @see WorkspaceService#getWorkspaceUploadDirectory(int)
*/
@Override
public File getWorkspaceUploadDirectory(int workspaceID) {
return this.workspaceUploader.getWorkspaceUploadDirectory(workspaceID);
}
/**
* @see WorkspaceService#uploadFileIntoWorkspace(java.lang.String, int, java.io.InputStream, java.lang.String)
*/
@Override
public File uploadFileIntoWorkspace(String userID, int workspaceID, InputStream inputStream, String filename)
throws IOException, DisallowedPathException {
logger.debug("Triggered upload of file into workspace; userID: " + userID + "; workspaceID: " + workspaceID + "; filename: " + filename);
return this.workspaceUploader.uploadFileIntoWorkspace(workspaceID, inputStream, filename);
}
/**
* @see WorkspaceService#uploadZipFileIntoWorkspace(java.lang.String, int, java.util.zip.ZipInputStream, java.lang.String)
*/
@Override
public ZipUploadResult uploadZipFileIntoWorkspace(String userID, int workspaceID, ZipInputStream zipInputStream, String filename)
throws IOException, DisallowedPathException {
logger.debug("Triggered upload of zip file into workspace; userID: " + userID + "; workspaceID: " + workspaceID + "; filename: " + filename);
return this.workspaceUploader.uploadZipFileIntoWorkspace(workspaceID, zipInputStream);
}
/**
* @see WorkspaceService#processUploadedFiles(java.lang.String, int, java.util.Collection)
*/
@Override
public Collection<ImportProblem> processUploadedFiles(String userID, int workspaceID, Collection<File> uploadedFiles)
throws WorkspaceException {
logger.debug("Triggered processing of uploaded files; userID: " + userID + "; workspaceID: " + workspaceID);
return this.workspaceUploader.processUploadedFiles(workspaceID, uploadedFiles);
}
/**
* @see WorkspaceService#getUnlinkedNodes(java.lang.String, int)
*/
@Override
public List<WorkspaceNode> listUnlinkedNodes(String userID, int workspaceID) {
logger.debug("Triggered retrieval of unlinked nodes list; userID: " + userID + "; workspaceID: " + workspaceID);
return this.workspaceDao.getUnlinkedNodes(workspaceID);
}
}
| gpl-3.0 |
n3tmaster/SensorWebHub | swhservices/src/main/java/it/cnr/ibimet/swhservices/entities/Eddy.java | 1192 | package it.cnr.ibimet.swhservices.entities;
import it.cnr.ibimet.dbutils.TDBManager;
import it.lr.libs.DBManager.ParameterType;
import java.io.Serializable;
import java.sql.SQLException;
public class Eddy implements Serializable{
private String nomeEddy;
private int id_bike_sensor;
private TDBManager tdbm;
public Eddy(TDBManager tdbm){
this.tdbm=tdbm;
}
public Eddy(TDBManager tdbm, String nomeEddy) throws SQLException{
this(tdbm);
this.nomeEddy=nomeEddy;
getBikeInfo();
}
public String getNomeEddy() {
return nomeEddy;
}
public void setNomeEddy(String nomeEddy) {
this.nomeEddy = nomeEddy;
}
public int getId_bike_sensor() {
return id_bike_sensor;
}
public void setId_bike_sensor(int id_bike_sensor) {
this.id_bike_sensor = id_bike_sensor;
}
public void getBikeInfo() throws SQLException{
String sqlString = "select id_mobile_station from mobile_stations where nome=? and tipo='E' ";
tdbm.setPreparedStatementRef(sqlString);
tdbm.setParameter(ParameterType.STRING,this.nomeEddy, 1);
tdbm.runPreparedQuery();
if(tdbm.next()){
this.id_bike_sensor=tdbm.getInteger(1);
}else{
this.id_bike_sensor=-1;
}
}
}
| gpl-3.0 |
yeyuqingchen/yc_pick | library/src/main/java/com/weidongjian/meitu/wheelviewdemo/view/MessageHandler.java | 1133 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.weidongjian.meitu.wheelviewdemo.view;
import android.os.Handler;
import android.os.Message;
// Referenced classes of package com.qingchifan.view:
// LoopView
final class MessageHandler extends Handler {
public static final int WHAT_INVALIDATE_LOOP_VIEW = 1000;
public static final int WHAT_SMOOTH_SCROLL = 2000;
public static final int WHAT_ITEM_SELECTED = 3000;
final LoopView loopview;
MessageHandler(LoopView loopview) {
this.loopview = loopview;
}
@Override
public final void handleMessage(Message msg) {
switch (msg.what) {
case WHAT_INVALIDATE_LOOP_VIEW:
loopview.invalidate();
break;
case WHAT_SMOOTH_SCROLL:
loopview.smoothScroll(LoopView.ACTION.FLING);
break;
case WHAT_ITEM_SELECTED:
loopview.onItemSelected();
break;
}
}
}
| gpl-3.0 |
Visualista/Visualista | core/src/main/java/io/github/visualista/visualista/view/ModelToGdxHelper.java | 2016 | package io.github.visualista.visualista.view;
import io.github.visualista.visualista.model.IGetActor;
import io.github.visualista.visualista.model.IGetScene;
import io.github.visualista.visualista.model.IGetTile;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
public enum ModelToGdxHelper {
;
public static Image createImageFor(final IGetTile tile) {
return new Image(createDrawableFor(tile));
}
public static Image createImageFor(final IGetActor actor) {
return new Image(createDrawableFor(actor));
}
public static Image createImageFor(final IGetScene scene) {
return new Image(createDrawableFor(scene));
}
public static TextureRegionDrawable createDrawableFor(final IGetScene scene) {
if (scene == null) {
return null;
}
return createDrawableFor(scene.getImage());
}
public static TextureRegionDrawable createDrawableFor(final IGetTile tile) {
if (tile == null) {
return null;
}
return createDrawableFor(tile.getActor());
}
public static TextureRegionDrawable createDrawableFor(final IGetActor actor) {
if (actor == null) {
return null;
}
return createDrawableFor(actor.getImage());
}
public static TextureRegionDrawable createDrawableFor(
final io.github.visualista.visualista.model.Image image) {
if (image == null) {
return null;
}
return createDrawableFor(image.getFileHandle());
}
public static TextureRegionDrawable createDrawableFor(final FileHandle fileHandle) {
if (fileHandle == null) {
return null;
}
return new TextureRegionDrawable(new TextureRegion(new Texture(
fileHandle)));
}
}
| gpl-3.0 |
NJU-SE/PicMan | src/inter/Pic.java | 1083 | package inter;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.ArrayList;
//这是一个图片信息累用于中间传输,包含了图片二进制流,图片名称,以及图片的评论信息
public class Pic implements Serializable{
private String picname;//图片名称
private String path;//所属相册路径
private ArrayList<Comment> comms;//评论信息
private byte[] pic;
public byte[] getPic() {
return pic;
}
public void setPic(byte[] pic) {
this.pic = pic;
}
public BufferedImage getImage(){
return Message.bytesToImage(pic);
}
public void setImage(BufferedImage image){
Message.imageToBytes(image);
}
public String getPicname() {
return picname;
}
public void setPicname(String picname) {
this.picname = picname;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public ArrayList<Comment> getComms() {
return comms;
}
public void setComms(ArrayList<Comment> comms) {
this.comms = (ArrayList<Comment>) comms.clone();
}
}
| gpl-3.0 |
benplay2/simpleInternetLog | src/simpleInternetLog/iNetLoggerShutdownHook.java | 516 | package simpleInternetLog;
/*
*
* Created by Ben Brust 2017
*/
public class iNetLoggerShutdownHook extends Thread {
private ConnectionMaster master;
public iNetLoggerShutdownHook(ConnectionMaster master){
this.setMaster(master);
}
@Override
public void run() {
//System.out.println("=== my shutdown hook activated");
this.getMaster().endProgram();
}
private void setMaster(ConnectionMaster master){
this.master = master;
}
private ConnectionMaster getMaster(){
return this.master;
}
} | gpl-3.0 |
weltyc/novello | test/com/welty/novello/eval/EvalStrategyTest.java | 8661 | /*
* Copyright (c) 2014 Chris Welty.
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 3,
* as published by the Free Software Foundation.
*
* This file 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.
*
* For the license, see <http://www.gnu.org/licenses/gpl.html>.
*/
package com.welty.novello.eval;
import com.orbanova.common.misc.Vec;
import com.orbanova.common.ramfs.RamFileSystem;
import com.welty.novello.core.BitBoardUtils;
import com.welty.novello.core.Board;
import com.welty.novello.core.Me;
import com.welty.novello.selfplay.Players;
import junit.framework.TestCase;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
/**
*/
public class EvalStrategyTest extends TestCase {
public void testIndicesFromPosition() {
final EvalStrategy strategy = EvalStrategies.eval1;
// All 4 terms share the same feature
assertEquals(1, strategy.nFeatures());
// a sample position.
// square 077 is mover, square 070 is enemy,
// square 007 has mover access, square 000 has enemy access
final long mover = 0x8001010101010100L;
final long enemy = 0x0180808080808000L;
final int[] expected = {2, 1, 5, 4};
assertEquals(new PositionElement(expected, 0), strategy.coefficientIndices(mover, enemy, 0));
}
public void testFeatureCompression() {
final EvalStrategy strategy = new EvalStrategy("test",
TermTest.term1,
TermTest.term1,
TermTest.term2
);
assertEquals(2, strategy.nFeatures());
assertArrayEquals("", new int[]{3, 2}, strategy.nOridsByFeature());
assertEquals(TermTest.feature1.nOrids() + TermTest.feature2.nOrids(), strategy.nCoefficientIndices());
assertArrayEquals("", new int[]{2, 2, 3}, strategy.coefficientIndices(3, 0, 0).indices);
}
public void testWriteRead() throws IOException {
// specific strategy doesn't matter too much for this test, just want it to have
// multiple terms and features.
final EvalStrategy strategy = EvalStrategies.diagonal;
final int nFeatures = strategy.nFeatures();
final double[] coeffs = Vec.increasingDouble(0., 1., strategy.nCoefficientIndices());
final RamFileSystem fs = new RamFileSystem();
final Path coefficientDirectory = fs.getPath("coefficients");
final int nEmpty = 12;
strategy.writeSlice(nEmpty, coeffs, coefficientDirectory);
final short[][] slice = strategy.readSlice(nEmpty, coefficientDirectory);
assertEquals(nFeatures, slice.length);
// test expected result for each feature
int value = 0;
for (int iFeature = 0; iFeature < nFeatures; iFeature++) {
final Feature feature = strategy.getFeature(iFeature);
final int nOrids = feature.nOrids();
short start = (short) value;
short[] increasing = new short[nOrids];
for (short i = 0; i < nOrids; i++) {
increasing[i] = start;
start += 1;
}
value += nOrids;
assertTrue(Arrays.equals(increasing, slice[iFeature]));
// assertEquals(increasing, slice[iFeature]);
}
}
public void testAllReflectionsHaveTheSameEval() {
final Random random = new Random(1337);
final Eval eval = Players.currentEval();
// test with small # of disks on the board
long empty = random.nextLong() | random.nextLong();
long mover = random.nextLong() & ~empty;
testAllReflectionsHaveTheSameEval(eval, mover, ~(empty | mover));
// test with large # of disks on the board
empty = random.nextLong() & random.nextLong();
mover = random.nextLong() & ~empty;
testAllReflectionsHaveTheSameEval(eval, mover, ~(empty | mover));
}
private void testAllReflectionsHaveTheSameEval(Eval eval, long mover, long enemy) {
final Board board = new Board(mover, enemy, true);
final int expected = eval.eval(board);
for (int r = 1; r < 8; r++) {
final Board reflection = board.reflection(r);
assertEquals(expected, eval.eval(reflection));
}
}
public void testAllReflectionsHaveSameOrids() {
for (EvalStrategy strategy : EvalStrategies.knownStrategies()) {
testAllReflectionsHaveTheSameOrids(strategy, Me.early);
testAllReflectionsHaveTheSameOrids(strategy, Me.late);
}
}
public void testGeneratedEvalMatchesEvalByTerms() {
for (EvalStrategy strategy : EvalStrategies.knownStrategies()) {
testGeneratedEval(strategy);
}
}
private void testGeneratedEval(EvalStrategy strategy) {
final short[][] randomCoefficients = strategy.generateRandomCoefficients();
final CoefficientEval eval = new CoefficientEval(strategy, randomCoefficients);
for (Me me : new Me[]{Me.early, Me.mid, Me.late}) {
checkGeneratedEval(strategy, randomCoefficients, eval, me);
}
Random rand = new Random(1234);
for (int i = 0; i < 100; i++) {
checkGeneratedEval(strategy, randomCoefficients, eval, Me.early(rand));
checkGeneratedEval(strategy, randomCoefficients, eval, Me.mid(rand));
checkGeneratedEval(strategy, randomCoefficients, eval, Me.late(rand));
}
}
public void testTemp() {
final EvalStrategy d = EvalStrategies.strategy("j");
final short[][] coeffs = d.generateRandomCoefficients();
final CoefficientEval eval = new CoefficientEval(d, coeffs);
final Me me = new Me(1224979102939791360L, 21224972731027584L);
checkGeneratedEval(d, coeffs, eval, me);
}
private static void checkGeneratedEval(EvalStrategy strategy, short[][] randomCoefficients, CoefficientEval eval, Me me) {
final long moverMoves = me.calcMoves();
final long enemyMoves = me.enemyMoves();
final int evalByTerms;
if (moverMoves == 0) {
evalByTerms = -strategy.evalByTerms(me.enemy, me.mover, enemyMoves, moverMoves, randomCoefficients, false);
} else {
evalByTerms = strategy.evalByTerms(me.mover, me.enemy, moverMoves, enemyMoves, randomCoefficients, false);
}
final int generatedEval = eval.eval(me.mover, me.enemy);
if (evalByTerms != generatedEval) {
strategy.evalByTerms(me.mover, me.enemy, moverMoves, enemyMoves, randomCoefficients, true);
// generate information needed to recreate the failure in a test case
System.out.println();
System.out.println("new Me(" + me.mover + "L, " + me.enemy + "L)");
assertEquals(strategy.toString(), evalByTerms, generatedEval);
}
}
private void testAllReflectionsHaveTheSameOrids(EvalStrategy strategy, Me position) {
final long mover = position.mover;
final long enemy = position.enemy;
PositionElement expected = strategy.coefficientIndices(mover, enemy, 0);
expected.sortIndices();
for (int r = 1; r < 8; r++) {
final long rMover = BitBoardUtils.reflection(mover, r);
final long rEnemy = BitBoardUtils.reflection(enemy, r);
final PositionElement actual = strategy.coefficientIndices(rMover, rEnemy, 0);
actual.sortIndices();
if (!expected.equals(actual)) {
assertEquals(strategy.toString() + r, expected.toString(), actual.toString());
}
assertEquals(strategy.toString(), expected, actual); // in case toString() matches
}
}
public void testEvalJ() {
EvalStrategy j = EvalStrategies.strategy("j");
final long mover = Me.early.mover;
final long enemy = Me.early.enemy;
PositionElement expected = j.coefficientIndices(mover, enemy, 0);
final long rMover = BitBoardUtils.reflection(mover, 1);
final long rEnemy = BitBoardUtils.reflection(enemy, 1);
PositionElement actual = j.coefficientIndices(rMover, rEnemy, 0);
expected.sortIndices();
actual.sortIndices();
assertEquals(expected.toString().replace(",", "\n"), actual.toString().replace(",", "\n"));
}
}
| gpl-3.0 |
arthurtaborda/sbms | server/src/main/java/net/artcoder/service/backup/BackupScheduler.java | 936 | package net.artcoder.service.backup;
import net.artcoder.domain.Backup;
import net.artcoder.domain.IP;
import net.artcoder.domain.exception.AlreadyDisabledException;
import net.artcoder.domain.exception.BackupNotFoundException;
import net.artcoder.domain.exception.AlreadyActiveException;
import net.artcoder.service.backup.task.SendTimeoutTask;
import java.util.Date;
public interface BackupScheduler {
void schedule(Backup backup, IP address, Date date);
void enableBackup(String backupId) throws AlreadyActiveException, BackupNotFoundException;
void disableBackup(String backupId) throws BackupNotFoundException, AlreadyDisabledException;
void deleteBackup(String backupId) throws BackupNotFoundException;
boolean hasTimeOut(String backupId);
boolean hasSchedule(String backupId);
void cancelTimeout(String backupId);
void startTimeoutForBackup(Integer timeout, String backupId, SendTimeoutTask sendTimeoutTask);
}
| gpl-3.0 |
TerrenceMiao/Functional-Java | src/test/java/org/paradise/function/CurryTest.java | 886 | package org.paradise.function;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.Assert.*;
/**
* Created by terrence on 13/04/2016.
*/
public class CurryTest {
@Test
public void testCalculationOptional() throws Exception {
assertEquals("Incorrect result", Optional.of(7), Optional.of(3).map(Curry.calculation(1, 2)));
}
@Test
public void testCalculationStream() throws Exception {
assertEquals("Incorrect result", Optional.of(7), Stream.of(3).map(Curry.calculation(1, 2)).findAny());
assertArrayEquals("Incorrect result", Arrays.asList(7, 9, 11).stream().toArray(Integer[]::new),
Stream.of(3, 4, 5).map(Curry.calculation(1, 2)).toArray());
}
} | gpl-3.0 |
skurski/know-how | src/main/java/know/how/core/jrunner/multithreading/test/WaitTerminateTutor.java | 1910 | package know.how.core.jrunner.multithreading.test;
import org.junit.Test;
public class WaitTerminateTutor {
static StringBuffer buf = new StringBuffer();
static void log(String s) {
buf.append(s+"\n");
}
Thread t1, t2;
Object monitor = new Object();
int runningThreadNumber = 1;
class TestThread implements Runnable {
String threadName;
public boolean shouldTerminate;
public TestThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i=0;;i++) {
log(threadName+":"+i);
synchronized(monitor) {
try {
while (!threadName.equals("t"+runningThreadNumber)) {
log("wait for thread "+"t"+runningThreadNumber);
monitor.wait();
}
} catch (InterruptedException e) {
log("Interrupted: TERMINATED " + threadName + "!");
return;
}
runningThreadNumber++;
if (runningThreadNumber>2) runningThreadNumber=1;
monitor.notifyAll();
if (shouldTerminate) {
log("TERMINATED "+threadName+"!");
return;
}
}
}
}
}
@Test
public void testThread() {
final TestThread testThread1 = new TestThread("t1");
t1 = new Thread(testThread1);
final TestThread testThread2 = new TestThread("t2");
t2 = new Thread(testThread2);
log("Starting threads...");
t1.start();
t2.start();
Thread terminator = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
testThread1.shouldTerminate=true;
// comment this line out and execute
// testThread2.shouldTerminate=true;
t2.interrupt();
}
});
terminator.start();
log("Waiting threads to join...");
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(buf);
}
}
| gpl-3.0 |
simonpatrick/stepbystep-java | hedwig-concurrent/src/main/java/io/hedwig/concurrent/thread/communication/ExchangerDemo.java | 1076 | package io.hedwig.concurrent.thread.communication;
import java.util.concurrent.Exchanger;
@SuppressWarnings("unchecked")
public class ExchangerDemo {
public static void main(String[] args) {
Exchanger exchanger = new Exchanger();
ExchangerRunnable exchangerRunnable1 = new ExchangerRunnable(exchanger, "AAA");
ExchangerRunnable exchangerRunnable2 = new ExchangerRunnable(exchanger, "BBB");
new Thread(exchangerRunnable1).start();
new Thread(exchangerRunnable2).start();
}
}
@SuppressWarnings("unchecked")
class ExchangerRunnable implements Runnable {
Exchanger exchanger = null;
Object object = null;
public ExchangerRunnable(Exchanger exchanger, Object object) {
this.exchanger = exchanger;
this.object = object;
}
@Override
public void run() {
try {
Object previous = object; //之前的
//互换数据
object = exchanger.exchange(object);
System.out.println(
Thread.currentThread().getName() +
" exchanged " + previous +
" for " + object);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| gpl-3.0 |
BukkitPE/BukkitPE | src/main/java/net/BukkitPE/metadata/MetadataStore.java | 2611 | package net.BukkitPE.metadata;
import net.BukkitPE.plugin.Plugin;
import net.BukkitPE.utils.PluginException;
import net.BukkitPE.utils.ServerException;
import java.util.*;
/**
* BukkitPE Project
*/
public abstract class MetadataStore {
private final Map<String, Map<Plugin, MetadataValue>> metadataMap = new HashMap<>();
public void setMetadata(Object subject, String metadataKey, MetadataValue newMetadataValue) {
if (newMetadataValue == null) {
throw new ServerException("Value cannot be null");
}
Plugin owningPlugin = newMetadataValue.getOwningPlugin();
if (owningPlugin == null) {
throw new PluginException("Plugin cannot be null");
}
String key = this.disambiguate((Metadatable) subject, metadataKey);
Map<Plugin, MetadataValue> entry = this.metadataMap.get(key);
if (entry == null) {
entry = new WeakHashMap<>(1);
this.metadataMap.put(key, entry);
}
entry.put(owningPlugin, newMetadataValue);
}
public List<MetadataValue> getMetadata(Object subject, String metadataKey) {
String key = this.disambiguate((Metadatable) subject, metadataKey);
if (this.metadataMap.containsKey(key)) {
Collection values = ((Map) this.metadataMap.get(key)).values();
return Collections.unmodifiableList(new ArrayList<>(values));
}
return Collections.emptyList();
}
public boolean hasMetadata(Object subject, String metadataKey) {
return this.metadataMap.containsKey(this.disambiguate((Metadatable) subject, metadataKey));
}
public void removeMetadata(Object subject, String metadataKey, Plugin owningPlugin) {
if (owningPlugin == null) {
throw new PluginException("Plugin cannot be null");
}
String key = this.disambiguate((Metadatable) subject, metadataKey);
Map entry = (Map) this.metadataMap.get(key);
if (entry == null) {
return;
}
entry.remove(owningPlugin);
if (entry.isEmpty()) {
this.metadataMap.remove(key);
}
}
public void invalidateAll(Plugin owningPlugin) {
if (owningPlugin == null) {
throw new PluginException("Plugin cannot be null");
}
for (Map value : this.metadataMap.values()) {
if (value.containsKey(owningPlugin)) {
((MetadataValue) value.get(owningPlugin)).invalidate();
}
}
}
protected abstract String disambiguate(Metadatable subject, String metadataKey);
}
| gpl-3.0 |
BoD/bikey | wear/src/main/java/org/jraf/android/bikey/wearable/app/display/fragment/SimpleDisplayFragment.java | 1985 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2014 Benoit 'BoD' Lubek (BoD@JRAF.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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.android.bikey.wearable.app.display.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.jraf.android.bikey.R;
import org.jraf.android.bikey.wearable.app.display.DisplayActivity;
import org.jraf.android.util.app.base.BaseFragment;
public abstract class SimpleDisplayFragment extends BaseFragment<DisplayActivity> {
private TextView mTxtValue;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View res = inflater.inflate(getLayoutResId(), container, false);
mTxtValue = (TextView) res.findViewById(R.id.txtValue);
return res;
}
protected void setText(CharSequence text) {
mTxtValue.setText(text);
}
protected void setTextEnabled(boolean enabled) {
mTxtValue.setEnabled(enabled);
}
protected int getLayoutResId() {
return R.layout.display_simple;
}
}
| gpl-3.0 |
gunnarfloetteroed/java | utilities/src/main/java/floetteroed/utilities/EmptyIterator.java | 308 | package floetteroed.utilities;
import java.util.Iterator;
/**
*
* @author Gunnar Flötteröd
*
* @param <T>
*/
public class EmptyIterator<T> implements Iterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
return null;
}
}
| gpl-3.0 |
FranckDemeyer/projet_stage_cdi_java | dadakar-back-run/src/main/java/com/umanteam/dadakar/run/back/entities/SubRun.java | 3850 | package com.umanteam.dadakar.run.back.entities;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
public class SubRun {
/* Variables */
private String subRunId;
private Duration flexibility;
private WayPoint startPlace;
private WayPoint endPlace;
private LocalDate startDate;
private LocalTime startTime;
private LocalDate estimatedEndDate;
private LocalTime estimatedEndTime;
private Integer availableSeats;
private List<Passenger> passengers;
private List<WayPoint> startingPoints;
private List<Toll> tolls;
private Double price;
/* Constructors */
public SubRun() {}
public SubRun(Duration flexibility, WayPoint startPlace, WayPoint endPlace, LocalDate startDate,
LocalTime startTime, LocalDate estimatedEndDate, LocalTime estimatedEndTime, Integer availableSeats,
List<Passenger> passengers, List<WayPoint> startingPoints, List<Toll> tolls, Double price) {
this.flexibility = flexibility;
this.startPlace = startPlace;
this.endPlace = endPlace;
this.startDate = startDate;
this.startTime = startTime;
this.estimatedEndDate = estimatedEndDate;
this.estimatedEndTime = estimatedEndTime;
this.availableSeats = availableSeats;
this.passengers = passengers;
this.startingPoints = startingPoints;
this.tolls = tolls;
this.price = price;
}
/* Getters and Setters */
public String getSubRunId() {
return subRunId;
}
public void setSubRunId(String subRunId) {
this.subRunId = subRunId;
}
public Duration getFlexibility() {
return flexibility;
}
public void setFlexibility(Duration flexibility) {
this.flexibility = flexibility;
}
public WayPoint getStartPlace() {
return startPlace;
}
public void setStartPlace(WayPoint startPlace) {
this.startPlace = startPlace;
}
public WayPoint getEndPlace() {
return endPlace;
}
public void setEndPlace(WayPoint endPlace) {
this.endPlace = endPlace;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalTime getStartTime() {
return startTime;
}
public void setStartTime(LocalTime startTime) {
this.startTime = startTime;
}
public LocalDate getEstimatedEndDate() {
return estimatedEndDate;
}
public void setEstimatedEndDate(LocalDate estimatedEndDate) {
this.estimatedEndDate = estimatedEndDate;
}
public LocalTime getEstimatedEndTime() {
return estimatedEndTime;
}
public void setEstimatedEndTime(LocalTime estimatedEndTime) {
this.estimatedEndTime = estimatedEndTime;
}
public Integer getAvailableSeats() {
return availableSeats;
}
public void setAvailableSeats(Integer availableSeats) {
this.availableSeats = availableSeats;
}
public List<Passenger> getPassengers() {
return passengers;
}
public void setPassengers(List<Passenger> passengers) {
this.passengers = passengers;
}
public List<WayPoint> getStartingPoints() {
return startingPoints;
}
public void setStartingPoints(List<WayPoint> startingPoints) {
this.startingPoints = startingPoints;
}
public List<Toll> getTolls() {
return tolls;
}
public void setTolls(List<Toll> tolls) {
this.tolls = tolls;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
/* Methods */
@Override
public String toString() {
return "SubRun [subRunId=" + subRunId + ", flexibility=" + flexibility + ", startPlace=" + startPlace
+ ", endPlace=" + endPlace + ", startDate=" + startDate + ", startTime=" + startTime
+ ", estimatedEndDate=" + estimatedEndDate + ", estimatedEndTime=" + estimatedEndTime
+ ", availableSeats=" + availableSeats + ", passengers=" + passengers + ", startingPoints="
+ startingPoints + ", tolls=" + tolls + ", price=" + price + "]";
}
}
| gpl-3.0 |
austindlawless/dotCMS | src/com/dotmarketing/image/filter/GammaImageFilter.java | 1176 | package com.dotmarketing.image.filter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.imageio.ImageIO;
import com.dotmarketing.util.Logger;
import com.dotcms.repackage.com_dotmarketing_jhlabs_images_filters.com.dotmarketing.jhlabs.image.GammaFilter;
public class GammaImageFilter extends ImageFilter {
public String[] getAcceptedParameters() {
return new String[] { "g (double) between 0 and 3.0" };
}
public File runFilter(File file, Map<String, String[]> parameters) {
double g = parameters.get(getPrefix() + "g") != null ? Double.parseDouble(parameters.get(getPrefix() + "g")[0])
: 0.0;
float f = new Double(g).floatValue();
File resultFile = getResultsFile(file, parameters);
GammaFilter filter = new GammaFilter();
filter.setGamma(f);
if (!overwrite(resultFile, parameters)) {
return resultFile;
}
try {
BufferedImage src = ImageIO.read(file);
BufferedImage dst = filter.filter(src, null);
ImageIO.write(dst, "png", resultFile);
} catch (IOException e) {
Logger.error(this.getClass(), e.getMessage());
}
return resultFile;
}
}
| gpl-3.0 |
jesusc/eclectic | tests/org.eclectic.test.streaming.largemodels/src/org/eclectic/test/streaming/Java2KDM_Test.java | 91631 | package org.eclectic.test.streaming;
import static es.modelum.morsa.query.dsl.QueryBuilder.SELECT;
import static es.modelum.morsa.query.dsl.QueryBuilder.navigate;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclectic.idc.datatypes.JavaListConverter;
import org.eclectic.idc.jvm.runtime.BasicMethodHandler;
import org.eclectic.idc.jvm.runtime.LocalQueue;
import org.eclectic.idc.jvm.runtime.ModelQueue;
import org.eclectic.idc.jvm.runtime.QoolTransformationBase;
import org.eclectic.modeling.emf.BasicEMFModel;
import org.eclectic.modeling.emf.EMFHandler;
import org.eclectic.modeling.emf.EMFLoader;
import org.eclectic.modeling.emf.IModel;
import org.eclectic.modeling.emf.IStreamedModel;
import org.eclectic.modeling.emf.ModelManager;
import org.eclectic.modeling.emf.Util;
import org.eclectic.streamdesc.StreamDescription;
import org.eclectic.streaming.fragments.EmfFragment;
import org.eclectic.streaming.fragments.EmfFragmentFactory;
import org.eclectic.streaming.fragments.StreamedEmfModel;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EFactory;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import Core.CorePackage;
import DOM.DOMPackage;
import PrimitiveTypes.PrimitiveTypesPackage;
import es.modelum.morsa.MorsaResource;
import es.modelum.morsa.MorsaResourceFactoryImpl;
import es.modelum.morsa.backend.mongodb.MongoDBMorsaBackendFactory;
import es.modelum.morsa.query.BOOLEQ;
import es.modelum.morsa.query.Condition;
import es.modelum.morsa.query.REF;
import es.modelum.morsa.query.STREQ;
import es.modelum.morsa.query.dsl.MorsaQuery;
/**
* Test class for MorsaResource. The following tests have been implemented: full
* save, full load, single load on demand, partial load on demand, Grabats query
* with single load on demand and Grabats query with partial load on demand
*
* From the console, execute the main method without arguments to show help
*
*
*/
public class Java2KDM_Test {
static {
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
}
/**
* Flag for breadth first traversal
*/
static public final int BREADTH_FIRST_ORDER = 0;
/**
* Flag for depth first traversal
*/
static public final int DEPTH_FIRST_ORDER = 1;
static private Map<EObject, MorsaQuery> morsaQueries = new HashMap<EObject, MorsaQuery>();
static private MorsaQuery typeDeclarationQuery;
private static void transformToKdm(Collection<EObject> root, List<EPackage> pkgs2)
throws IOException {
QoolTransformationBase transformation = new eclectic.jdt2kdm();
Util.registerResourceFactory();
// Load meta-model
/*
ArrayList<EPackage> pkgs = new ArrayList<EPackage>();
ResourceSet rs = new ResourceSetImpl();
Resource mmr = rs.getResource(
URI.createFileURI(withDir("model/JDTAST.ecore")), true);
for (EObject o : mmr.getContents()) {
EPackage pkg = (EPackage) o;
pkgs.add(pkg);
EPackage.Registry.INSTANCE.put(pkg.getNsURI(), pkg);
}
*/
for (EPackage ePackage : pkgs2) {
EPackage.Registry.INSTANCE.put(ePackage.getNsURI(), ePackage);
}
String streamDesc = withDir("src/org/eclectic/test/streaming/jdt.streamdesc");
IModel<?, ?> in = getStreamedModel(pkgs2, streamDesc);
ModelManager manager = new ModelManager();
EMFLoader loader = new EMFLoader(new JavaListConverter());
BasicEMFModel out = loader.basicEmptyModelFromFile(
withDir("model/kdm.ecore"),
withDir("tmp_/kdm_output_streaming.xmi"));
in.registerMethodHandler(new BasicMethodHandler(manager));
out.registerMethodHandler(new BasicMethodHandler(manager));
manager.register("jdt", in);
manager.register("kdm", out);
transformation.setModelManager(manager);
transformation.configureStreamingMode("jdt", (IStreamedModel) in);
transformation.configure_();
transformation.start_();
// EmfFragmentFactory factory = new EmfFragmentFactory(pkgs);
int i = 0;
for (EObject eObject : root) {
// EmfFragment frg = factory.createFragment();
i++;
MorsaFragment fragment = new MorsaFragment();
fragment.addObject(eObject);
/*
System.out.println("Getting elements " + ++i);
TreeIterator<EObject> contents = eObject.eAllContents();
while ( contents.hasNext() ) {
fragment.addObject(contents.next());
}
*/
System.out.println("Transforming " + i);
transformation.receiveStreamedFragment("jdt", fragment);
((LocalQueue) transformation.getQueue("BodyQ")).clean();
LinkedList<Object> objects = ((ModelQueue) transformation.getQueue("mMethodDeclaration")).getObjects();
for (Object object : objects) {
((IStreamedModel) in).remove(object);
}
((ModelQueue) transformation.getQueue("mFieldDeclaration")).getObjects();
for (Object object : objects) {
((IStreamedModel) in).remove(object);
}
((ModelQueue) transformation.getQueue("mMethodDeclaration")).clean();
((ModelQueue) transformation.getQueue("mFieldDeclaration")).clean();
// System.out.println(eObject);
// Object superclass =
// eObject.eGet(eObject.eClass().getEStructuralFeature("superclassType"));
// System.out.println("Superclass: " + superclass);
/*
* TreeIterator<EObject> contents = eObject.eAllContents(); while (
* contents.hasNext() ) { EObject obj = contents.next();
* System.out.println(obj); } break;
*/
}
transformation.printPending();
out.serialize();
}
public static IModel<?, ?> getStreamedModel(List<EPackage> pkgs, String streamDesc)
throws IOException {
JavaListConverter converter = new JavaListConverter();
EMFHandler handler = createModelHandler(pkgs);
StreamDescription desc = (StreamDescription) new org.eclectic.streamdesc.StreamDescLanguageLoader()
.load(streamDesc);
StreamedEmfModel model = new StreamedEmfModel(handler, desc, converter);
model.setExplicitKeyMode();
model.setLazyLoading();
return model;
}
private static EMFHandler createModelHandler(List<EPackage> pkgs) {
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
"xmi", new XMIResourceFactoryImpl());
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
"ecore", new XMIResourceFactoryImpl());
ResourceSetImpl rs = new ResourceSetImpl();
/*
* rs.getPackageRegistry().put(PrimitiveTypesPackage.eINSTANCE.getNsURI()
* , PrimitiveTypesPackage.eINSTANCE);
* rs.getPackageRegistry().put(DOMPackage.eINSTANCE.getNsURI(),
* DOMPackage.eINSTANCE);
* rs.getPackageRegistry().put(CorePackage.eINSTANCE.getNsURI(),
* CorePackage.eINSTANCE);
*/
Resource resource = rs.createResource(Util
.createURI("tmp_/input_model.xmi"));
EMFHandler handler = new EMFHandler(pkgs, resource);
return handler;
}
public static String withDir(String f) {
return new File(".").getAbsolutePath() + File.separator + f;
}
// Morsa stuff
static public void main(String[] args) {
Map<String, String> argMap = mapArgs(args);
if (args.length != 0) {
ResourceSet rs = new ResourceSetImpl();
rs.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("ecore", new EcoreResourceFactoryImpl());
rs.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("xmi", new XMIResourceFactoryImpl());
rs.getResourceFactoryRegistry()
.getProtocolToFactoryMap()
.put("morsa",
new MorsaResourceFactoryImpl(
new MongoDBMorsaBackendFactory()));
String operation = argMap.get("op");
String engine = argMap.get("engine");
String mode = argMap.get("mode");
String queryEngine = argMap.get("qengine");
String sourceFile = argMap.get("file");
String morsaURI = argMap.get("uri");
String backendURI = argMap.get("db");
boolean printTrace = argMap.containsKey("ptrace") ? Boolean
.parseBoolean(argMap.get("ptrace")) : false;
boolean discardSaved = argMap.containsKey("discard") ? Boolean
.parseBoolean(argMap.get("discard")) : true;
int clusterSize = argMap.containsKey("clsize") ? Integer
.parseInt(argMap.get("clsize")) : 0;
int order = argMap.containsKey("order")
&& argMap.get("order").equals("depth") ? DEPTH_FIRST_ORDER
: BREADTH_FIRST_ORDER;
String cachePolicy = argMap.get("capol");
int cacheSize = argMap.containsKey("casize") ? Integer
.parseInt(argMap.get("casize")) : 0;
float flushFactor = argMap.containsKey("caff") ? Float
.parseFloat(argMap.get("caff")) : 0.0f;
boolean readOnly = argMap.containsKey("ronly") ? Boolean
.parseBoolean(argMap.get("ronly")) : true;
int clusterDepth = argMap.containsKey("cldep") ? Integer
.parseInt(argMap.get("cldep")) : -1;
int clusterBreadth = argMap.containsKey("clbr") ? Integer
.parseInt(argMap.get("clbr")) : -1;
boolean getAll = argMap.containsKey("all") ? Boolean
.parseBoolean(argMap.get("all")) : true;
boolean isRoot = argMap.containsKey("root") ? Boolean
.parseBoolean(argMap.get("root")) : true;
if (operation.equals("save")) {
if (engine.equals("xmi")) {
testSaveXMI(rs, sourceFile);
} else if (engine.equals("morsa")) {
if (mode.equals("full")) {
testFullSave(rs, sourceFile, morsaURI, backendURI,
cacheSize, printTrace);
} else {
if (mode.equals("inc")) {
testIncrementalSave(rs, sourceFile, morsaURI,
backendURI, cacheSize, printTrace,
discardSaved, clusterSize);
} else if (mode.equals("upd")) {
testIncrementalSaveByUpdate(rs, sourceFile,
morsaURI, backendURI, cacheSize,
printTrace, discardSaved);
}
}
}
}
else if (operation.equals("load")) {
if (engine.equals("xmi")) {
testLoadXMI(rs, sourceFile, order);
} else if (engine.equals("morsa")) {
if (mode.equals("full")) {
testFullLoad(rs, morsaURI, backendURI, printTrace,
order);
} else if (mode.equals("single")) {
testSingleLoad(rs, morsaURI, backendURI, cachePolicy,
order, cacheSize, flushFactor, printTrace,
readOnly);
} else if (mode.equals("partial")) {
testPartialLoad(rs, morsaURI, backendURI, cachePolicy,
order, cacheSize, flushFactor, clusterDepth,
clusterBreadth, printTrace, readOnly);
}
}
}
else if (operation.equals("update")) {
if (engine.equals("xmi")) {
testUpdateXMI(rs, sourceFile);
} else if (engine.equals("morsa")) {
if (mode.equals("full")) {
testUpdateFullLoad(rs, morsaURI, backendURI, printTrace);
} else if (mode.equals("single")) {
testUpdateSingleLoad(rs, morsaURI, backendURI,
cachePolicy, cacheSize, flushFactor, printTrace);
} else if (mode.equals("partial")) {
testUpdatePartialLoad(rs, morsaURI, backendURI,
cachePolicy, cacheSize, flushFactor,
clusterDepth, clusterBreadth, printTrace);
}
}
}
else if (operation.equals("query")) {
if (engine.equals("xmi")) {
testGrabatsXMI(rs, sourceFile, queryEngine);
} else if (engine.equals("morsa")) {
if (mode.equals("full")) {
if (queryEngine.equals("emfquery"))
throw new UnsupportedOperationException();
else
testGrabatsFullLoad(rs, morsaURI, backendURI,
printTrace, queryEngine, readOnly);
} else if (mode.equals("single")) {
if (queryEngine.equals("emfquery"))
throw new UnsupportedOperationException();
else
testGrabatsSingleLoad(rs, morsaURI, backendURI,
cachePolicy, cacheSize, flushFactor,
printTrace, queryEngine, readOnly);
} else if (mode.equals("partial")) {
if (queryEngine.equals("emfquery"))
throw new UnsupportedOperationException();
else
testGrabatsPartialLoad(rs, morsaURI, backendURI,
cachePolicy, cacheSize, flushFactor,
clusterDepth, clusterBreadth, printTrace,
queryEngine, readOnly);
}
}
}
else if (operation.equals("delete")) {
testDelete(rs, morsaURI, backendURI, printTrace, isRoot);
}
else if (operation.equals("referencers")) {
boolean queryAsCode = queryEngine.equals("emf");
if (engine.equals("xmi")) {
testReferencersXMI(rs, sourceFile, queryAsCode, getAll);
} else if (engine.equals("morsa")) {
if (mode.equals("full")) {
if (queryEngine.equals("emfquery")) {
} else
testReferencersFullLoad(rs, morsaURI, backendURI,
printTrace, queryAsCode, readOnly, getAll);
} else if (mode.equals("single")) {
if (queryEngine.equals("-emfquery")) {
} else
testReferencersSingleLoad(rs, morsaURI, backendURI,
cachePolicy, cacheSize, flushFactor,
printTrace, queryAsCode, readOnly, getAll);
} else if (mode.equals("partial")) {
if (queryEngine.equals("-emfquery")) {
} else
testReferencersPartialLoad(rs, morsaURI,
backendURI, cachePolicy, cacheSize,
flushFactor, clusterDepth, clusterBreadth,
printTrace, queryAsCode, readOnly, getAll);
}
}
}
else if (operation.equals("inclusion")) {
boolean queryAsCode = queryEngine.equals("emf");
if (engine.equals("xmi")) {
testReferencersXMI(rs, sourceFile, queryAsCode, getAll);
} else if (engine.equals("morsa")) {
if (mode.equals("full")) {
if (queryEngine.equals("emfquery")) {
} else
testInclusionFullLoad(rs, morsaURI, backendURI,
printTrace, queryAsCode, readOnly, getAll);
} else if (mode.equals("single")) {
if (queryEngine.equals("-emfquery")) {
} else
testInclusionSingleLoad(rs, morsaURI, backendURI,
cachePolicy, cacheSize, flushFactor,
printTrace, queryAsCode, readOnly, getAll);
} else if (mode.equals("partial")) {
if (queryEngine.equals("-emfquery")) {
} else
testInclusionPartialLoad(rs, morsaURI, backendURI,
cachePolicy, cacheSize, flushFactor,
clusterDepth, clusterBreadth, printTrace,
queryAsCode, readOnly, getAll);
}
}
}
} else {
// TODO print howto
}
}
/**
* Tests the full save of a model from an XMI file
*
* @param rs
* the ResourceSet
* @param sourceFile
* the path to the source file of the model
*/
static public void testSaveXMI(ResourceSet rs, String sourceFile) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
List<EObject> roots = r.getContents();
long l = System.currentTimeMillis();
File otherf = new File(sourceFile.replace(".xmi", "_test.xmi"));
Resource otherr = rs.createResource(URI.createFileURI(otherf
.getAbsolutePath()));
for (EObject root : roots) {
otherr.getContents().add(root);
}
try {
otherr.save(null);
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("SAVE TIME: " + (System.currentTimeMillis() - l));
}
/**
* Tests the full load of a model from an XMI file
*
* @param rs
* the ResourceSet
* @param sourceFile
* the path to the source file of the model
* @param order
* the traversal order (DEPTH_FIRST_ORDER for depth first,
* BREADTH_FIRST_ORDER for breadth first)
*/
static public void testLoadXMI(ResourceSet rs, String sourceFile, int order) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
long l = System.currentTimeMillis();
int objectCount = traverseModel(r, order);
System.out.println("LOAD TIME: " + (System.currentTimeMillis() - l)
+ " FOR " + objectCount + " OBJECTS");
}
/**
* Tests the update of an XMI file. The update executes the Grabats query
* over a model and depending on the number of results it performs one of
* the following actions:
*
* 1. If the result size is 0, it does nothing 2. If the result size is 1,
* that object is deleted 3. If the result size is 2, parents are exchanged
* between both objects 4. If the result size is greater than 2, parents are
* exchanged between the first and the last objects and the object in the
* middle is deleted
*
* This update can only be executed on a model that conforms to the
* metamodel defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet
* @param sourceFile
* the XMI file
*/
static public void testUpdateXMI(ResourceSet rs, String sourceFile) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
long l = System.currentTimeMillis();
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
File destFile = new File(sourceFile.replace(".xmi", "_test.xmi"));
Resource d = rs.createResource(URI.createFileURI(destFile
.getAbsolutePath()));
d.getContents().addAll(r.getContents());
Iterator<EObject> contentIterator = d.getAllContents();
EPackage dom = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.dom");
EClass typeDeclarationClass = (EClass) dom
.getEClassifier("TypeDeclaration");
EClass methodDeclarationClass = (EClass) dom
.getEClassifier("MethodDeclaration");
EClass modifierClass = (EClass) dom.getEClassifier("Modifier");
EClass simpleNameClass = (EClass) dom.getEClassifier("SimpleName");
List<EObject> foundObjs = new LinkedList<EObject>();
while (contentIterator.hasNext()) {
EObject content = contentIterator.next();
if (content.eClass().equals(typeDeclarationClass)) {
EObject typeDeclaration = content;
EObject typeName = (EObject) typeDeclaration
.eGet(typeDeclarationClass
.getEStructuralFeature("name"));
if (typeName == null)
continue;
String typeQName = (String) typeName.eGet(typeName.eClass()
.getEStructuralFeature("fullyQualifiedName"));
EReference bodyDeclarationsRef = (EReference) typeDeclarationClass
.getEStructuralFeature("bodyDeclarations");
Object o = typeDeclaration.eGet(bodyDeclarationsRef);
if (o != null) {
List<EObject> bodyDeclarationList = (List<EObject>) o;
boolean found = false;
for (int j = 0; j < bodyDeclarationList.size() && !found; j++) {
EObject bodyDeclaration = bodyDeclarationList.get(j);
if (bodyDeclaration.eClass() == methodDeclarationClass) {
EReference modifiersRef = (EReference) methodDeclarationClass
.getEStructuralFeature("modifiers");
Object o2 = bodyDeclaration.eGet(modifiersRef);
if (o2 != null) {
List<EObject> modifiersList = (List<EObject>) o2;
boolean foundStatic = false;
boolean foundPublic = false;
for (int k = 0; k < modifiersList.size(); k++) {
EObject modifier = modifiersList.get(k);
if (modifier.eClass() == modifierClass) {
boolean isStatic = (Boolean) modifier
.eGet(modifierClass
.getEStructuralFeature("static"));
boolean isPublic = (Boolean) modifier
.eGet(modifierClass
.getEStructuralFeature("public"));
if (isStatic)
foundStatic = true;
if (isPublic)
foundPublic = true;
}
}
if (foundStatic && foundPublic) {
EReference returnTypeRef = (EReference) methodDeclarationClass
.getEStructuralFeature("returnType");
Object o3 = bodyDeclaration
.eGet(returnTypeRef);
if (o3 != null) {
EObject returnType = (EObject) o3;
EReference typeNameRef = (EReference) returnType
.eClass()
.getEStructuralFeature("name");
if (typeNameRef != null) {
EObject returnTypeName = (EObject) returnType
.eGet(typeNameRef);
if (returnTypeName != null) {
String returnTypeQName = (String) returnTypeName
.eGet(returnTypeName
.eClass()
.getEStructuralFeature(
"fullyQualifiedName"));
if (returnTypeQName
.equals(typeQName)) {
EObject simpleName = (EObject) bodyDeclaration
.eGet(methodDeclarationClass
.getEStructuralFeature("name"));
System.out
.println(typeQName
+ " : "
+ simpleName
.eGet(simpleNameClass
.getEStructuralFeature("fullyQualifiedName")));
found = true;
foundObjs
.add(typeDeclaration);
}
}
}
}
}
}
}
}
}
}
}
if (foundObjs.size() > 0) {
l = System.currentTimeMillis();
EObject firstResult = foundObjs.get(0);
EReference firstContainingFeature = (EReference) firstResult
.eContainingFeature();
EObject firstContainer = firstResult.eContainer();
if (foundObjs.size() > 1) {
EObject lastResult = foundObjs.get(foundObjs.size() - 1);
EReference lastContainingFeature = (EReference) lastResult
.eContainingFeature();
EObject lastContainer = lastResult.eContainer();
if (firstResult.eContainingFeature().isMany()) {
((List<EObject>) firstContainer
.eGet(firstContainingFeature)).set(
((List<EObject>) firstContainer
.eGet(firstContainingFeature))
.indexOf(firstResult), lastResult);
} else {
firstContainer.eSet(firstResult.eContainingFeature(),
lastResult);
}
if (lastContainingFeature.isMany()) {
((List<EObject>) lastContainer.eGet(lastContainingFeature))
.add(firstResult);
} else {
lastContainer.eSet(lastContainingFeature, firstResult);
}
if (foundObjs.size() > 2) {
EObject middleResult = foundObjs
.get((foundObjs.size() - 1) / 2);
EObject middleContainer = middleResult.eContainer();
if (middleResult.eContainingFeature().isMany()) {
((List<EObject>) middleContainer.eGet(middleResult
.eContainingFeature())).remove(middleResult);
} else {
middleContainer.eUnset(middleResult
.eContainingFeature());
}
}
}
else {
if (firstResult.eContainingFeature().isMany()) {
((List<EObject>) firstContainer.eGet(firstResult
.eContainingFeature())).remove(firstResult);
} else {
firstContainer.eUnset(firstResult.eContainingFeature());
}
}
try {
d.save(null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("UPDATE TIME: "
+ (System.currentTimeMillis() - l));
}
}
/**
* Tests the Grabats query against an XMI file.
*
* The query finds all classes (TypeDeclaration) that declare static public
* methods (MethodDeclaration) whose return type is the same class
*
* This query can only be executed on a model that conforms to the metamodel
* defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet
* @param sourceFile
* the source XMI file
* @param queryAsCode
* TODO
*/
static public void testGrabatsXMI(ResourceSet rs, String sourceFile,
String queryEngine) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long l = System.currentTimeMillis();
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
EPackage dom = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.dom");
EClass typeDeclarationClass = (EClass) dom
.getEClassifier("TypeDeclaration");
System.out.println("LOAD TIME: " + (System.currentTimeMillis() - l));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
l = System.currentTimeMillis();
Iterator<EObject> contentIterator = r.getAllContents();
while (contentIterator.hasNext()) {
EObject content = contentIterator.next();
if (content.eClass().equals(typeDeclarationClass)) {
EObject typeDeclaration = content;
if (queryEngine.equals("emf"))
checkTypeDeclaration(typeDeclaration);
}
}
System.out.println("QUERY TIME 1: " + (System.currentTimeMillis() - l));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
l = System.currentTimeMillis();
contentIterator = r.getAllContents();
while (contentIterator.hasNext()) {
EObject content = contentIterator.next();
if (content.eClass().equals(typeDeclarationClass)) {
EObject typeDeclaration = content;
if (queryEngine.equals("emf"))
checkTypeDeclaration(typeDeclaration);
}
}
System.out.println("QUERY TIME 2: " + (System.currentTimeMillis() - l));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static public void testReferencersXMI(ResourceSet rs, String sourceFile,
boolean queryAsCode, boolean all) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
long l = System.currentTimeMillis();
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
EPackage dom = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.core");
EClass typeClass = (EClass) dom.getEClassifier("IType");
Iterator<EObject> contentIterator = r.getAllContents();
while (contentIterator.hasNext()) {
EObject content = contentIterator.next();
if (content.eClass().equals(typeClass)) {
EObject type = content;
if (queryAsCode)
referencersQueryAsCode(type, r, all);
else {
}
}
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
/**
* Tests the full save of a model
*
* @param rs
* the ResourceSet
* @param sourceFile
* the path to the source file of the model
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param saveCacheSize
* the size of the save chace
* @param printTrace
* flag for trace print
*/
static public void testFullSave(ResourceSet rs, String sourceFile,
String morsaURI, String backendURI, int saveCacheSize,
boolean printTrace) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
List<EObject> roots = new ArrayList<EObject>(r.getContents());
long l = System.currentTimeMillis();
Resource morsaResource = rs.createResource(URI.createURI(morsaURI));
for (EObject root : roots) {
morsaResource.getContents().add(root);
}
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
if (saveCacheSize > 0)
options.put(MorsaResource.OPTION_MAX_SAVE_CACHE_SIZE,
saveCacheSize);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
morsaResource.save(options);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("FULL SAVE TIME: "
+ (System.currentTimeMillis() - l));
}
/**
* Tests the incremental save of a model.
*
* The model is traversed in breadth-first order, when the size of the
* traversed objects is greater than or equals to the size of the cluster,
* they are saved in the repository and then discarded from memory.
*
* @param rs
* the ResourceSet
* @param sourceFile
* the path to the source file of the model
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param saveCacheSize
* the size of the save cache
* @param printTrace
* flag for trace print
* @param discardSaved
* true to unload already saved objects, false to keep them in
* memory
* @param clusterSize
* the size of the cluster of objects that is saved in each step
*/
static public void testIncrementalSave(ResourceSet rs, String sourceFile,
String morsaURI, String backendURI, int saveCacheSize,
boolean printTrace, boolean discardSaved, int clusterSize) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
long l = System.currentTimeMillis();
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
Resource morsaResource = rs.createResource(URI.createURI(morsaURI));
System.err.println("XMI LOADED: " + (System.currentTimeMillis() - l));
l = System.currentTimeMillis();
EObject[] contents = (EObject[]) r.getContents().toArray();
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
if (saveCacheSize > 0)
options.put(MorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, saveCacheSize);
options.put(MorsaResource.OPTION_SAVE_CLUSTER_SIZE, 1);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
morsaResource.getContents().addAll(r.getContents());
try {
System.err.println("SAVING NO. 1");
morsaResource.save(options);
} catch (IOException e) {
e.printStackTrace();
}
morsaResource.getContents().clear();
options.put(MorsaResource.OPTION_OVERWRITE_ROOTS, false);
options.put(MorsaResource.OPTION_DISCARD_SAVED, discardSaved);
int currentClusterSize = 0;
int saveCount = 2;
for (EObject content : contents) {
List<EObject> children = new LinkedList<EObject>();
children.addAll(content.eContents());
while (!children.isEmpty()) {
EObject child = children.remove(0);
children.addAll(0, child.eContents());
morsaResource.getContents().add(child);
if (currentClusterSize++ >= clusterSize) {
System.err.println("SAVING NO. " + saveCount++);
try {
morsaResource.save(options);
if (!discardSaved)
morsaResource.getContents().clear();
} catch (IOException e) {
e.printStackTrace();
}
currentClusterSize = 0;
}
}
}
if (currentClusterSize++ > 0) {
System.err.println("SAVING NO. " + saveCount++);
try {
morsaResource.save(options);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("INCREMENTAL SAVE TIME: "
+ (System.currentTimeMillis() - l));
}
/**
* Tests the incremental save of a model by update.
*
* The root of the model is initially saved and then each branch contained
* by the root is saved incrementally by updating the already saved model
*
* @param rs
* the ResourceSet
* @param sourceFile
* the path to the source file of the model
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param saveCacheSize
* the size of the save cache
* @param printTrace
* flag for trace print
* @param discardSaved
* true to unload already saved objects, false to keep them in
* memory
*/
@SuppressWarnings({ "unchecked", "unchecked", "rawtypes" })
static public void testIncrementalSaveByUpdate(ResourceSet rs,
String sourceFile, String morsaURI, String backendURI,
int saveCacheSize, boolean printTrace, boolean discardSaved) {
File f = new File(sourceFile);
for (File mm : f.getParentFile().listFiles()) {
if (mm.getAbsolutePath().endsWith(".ecore")) {
Resource mmr = rs.getResource(
URI.createFileURI(mm.getAbsolutePath()), true);
for (EObject o : mmr.getContents()) {
registerPackages((EPackage) o);
}
}
}
Resource r = rs
.getResource(URI.createFileURI(new File(sourceFile)
.getAbsolutePath()), true);
List<EObject> roots = new ArrayList<EObject>(r.getContents());
long l = System.currentTimeMillis();
Resource morsaResource = rs.createResource(URI.createURI(morsaURI));
Map<EObject, Map<EReference, List<EObject>>> removedObjects = new HashMap<EObject, Map<EReference, List<EObject>>>();
for (EObject root : roots) {
for (EReference ref : root.eClass().getEAllContainments()) {
if (ref.isMany() && root.eGet(ref) != null
&& !((List<EObject>) root.eGet(ref)).isEmpty()) {
if (!removedObjects.containsKey(root)) {
removedObjects.put(root,
new HashMap<EReference, List<EObject>>());
}
Map<EReference, List<EObject>> removedObjectsByRef = removedObjects
.get(root);
if (!removedObjectsByRef.containsKey(ref)) {
removedObjectsByRef.put(ref, new LinkedList<EObject>());
}
List<EObject> removedObjectsList = removedObjectsByRef
.get(ref);
for (EObject o : (List<EObject>) root.eGet(ref)) {
removedObjectsList.add(o);
}
((Collection<EObject>) root.eGet(ref)).clear();
}
}
morsaResource.getContents().add(root);
}
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
if (saveCacheSize > 0)
options.put(MorsaResource.OPTION_MAX_SAVE_CACHE_SIZE, saveCacheSize);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_DISCARD_SAVED, discardSaved);
try {
morsaResource.save(options);
} catch (IOException e) {
e.printStackTrace();
}
System.err.println("FIRST SAVE DONE: "
+ (System.currentTimeMillis() - l));
morsaResource.getContents().clear();
int count = 1;
for (EObject root : removedObjects.keySet()) {
EObject removedRoot = EcoreUtil.resolve(root, morsaResource);
for (EReference ref : removedObjects.get(root).keySet()) {
List<EObject> refObjs = removedObjects.get(root).get(ref);
while (!refObjs.isEmpty()) {
EObject removedObject = refObjs.remove(0);
System.err.println("SAVE NO. " + (count++) + " FOR "
+ ref.getName());
((List<EObject>) removedRoot.eGet(ref)).add(removedObject);
try {
morsaResource.getContents().add(removedRoot);
morsaResource.save(options);
} catch (IOException e) {
e.printStackTrace();
}
System.err.println("DONE IN "
+ (System.currentTimeMillis() - l));
}
}
}
System.out.println("INCREMENTAL SAVE TIME: "
+ (System.currentTimeMillis() - l));
}
/**
* Tests the full load of a model
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param printTrace
* flag for trace print
* @param order
* the traversal order (DEPTH_FIRST_ORDER for depth first,
* BREADTH_FIRST_ORDER for breadth first)
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testFullLoad(ResourceSet rs, String morsaURI,
String backendURI, boolean printTrace, int order) {
Resource morsaResource = rs.createResource(URI.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_DEMAND_LOAD, false);
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
morsaResource.load(options);
int objectCount = traverseModel(morsaResource, order);
System.out.println("LOAD TIME: " + (System.currentTimeMillis() - l)
+ " FOR " + objectCount + " OBJECTS");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests a single load on demand of a model
*
* The model is fully traversed on depth first or breadth first order
*
* @param rs
* the ResourceSet in which the MorsaResource is contained
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param cachePolicy
* the name of the cache policy class
* @param order
* the traversal order (DEPTH_FIRST_ORDER for depth first,
* BREADTH_FIRST_ORDER for breadth first)
* @param cacheSize
* the size of the cache
* @param flushFactor
* the flush factor of the cache
* @param printTrace
* flag for trace print
* @param readOnly
* flag for read only mode
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testSingleLoad(ResourceSet rs, String morsaURI,
String backendURI, String cachePolicy, int order, int cacheSize,
float flushFactor, boolean printTrace, boolean readOnly) {
Resource morsaResource = rs.createResource(URI.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
morsaResource.load(options);
int objectCount = traverseModel(morsaResource, order);
System.out.println("LOAD TIME: " + (System.currentTimeMillis() - l)
+ " FOR " + objectCount + " OBJECTS");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests a partial load on demand of a model.
*
* The model is fully traversed on depth first or breadth first order
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param cachePolicy
* the name of the cache policy class
* @param order
* the traversal order (DEPTH_FIRST_ORDER for depth first,
* BREADTH_FIRST_ORDER for breadth first)
* @param cacheSize
* the size of the cache
* @param flushFactor
* the flush factor of the cache
* @param clusterDepth
* the depth of the partial load on demand cluster
* @param clusterBreadth
* the breadth of the partial load on demand cluster
* @param printTrace
* flag for trace print
* @param readOnly
* flag for read only mode
*/
static public void testPartialLoad(ResourceSet rs, String morsaURI,
String backendURI, String cachePolicy, int order, int cacheSize,
float flushFactor, int clusterDepth, int clusterBreadth,
boolean printTrace, boolean readOnly) {
Resource morsaResource = rs.createResource(URI.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_PARTIAL_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_DEPTH,
clusterDepth);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_BREADTH,
clusterBreadth);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
morsaResource.load(options);
int objectCount = traverseModel(morsaResource, order);
System.out.println("LOAD TIME: " + (System.currentTimeMillis() - l)
+ " FOR " + objectCount + " OBJECTS");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests the update of a model using the Morsa repository with full load.
* The update executes the Grabats query over a model and depending on the
* number of results it performs one of the following actions:
*
* 1. If the result size is 0, it does nothing 2. If the result size is 1,
* that object is deleted 3. If the result size is 2, parents are exchanged
* between both objects 4. If the result size is greater than 2, parents are
* exchanged between the first and the last objects and the object in the
* middle is deleted
*
* This update can only be executed on a model that conforms to the
* metamodel defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param printTrace
* flag for trace print
*/
static public void testUpdateFullLoad(ResourceSet rs, String morsaURI,
String backendURI, boolean printTrace) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_DEMAND_LOAD, false);
options.put(MorsaResource.OPTION_OVERWRITE_ROOTS, false);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_READ_ONLY_MODE, false);
morsaResource.load(options);
update(morsaResource, options);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests the update of a model using the Morsa repository with single load
* on demand. The update executes the Grabats query over a model and
* depending on the number of results it performs one of the following
* actions:
*
* 1. If the result size is 0, it does nothing 2. If the result size is 1,
* that object is deleted 3. If the result size is 2, parents are exchanged
* between both objects 4. If the result size is greater than 2, parents are
* exchanged between the first and the last objects and the object in the
* middle is deleted
*
* This update can only be executed on a model that conforms to the
* metamodel defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param cachePolicy
* the name of the cache policy class
* @param cacheSize
* the size of the cache
* @param flushFactor
* the flush factor of the cache
* @param printTrace
* flag for trace print
*/
static public void testUpdateSingleLoad(ResourceSet rs, String morsaURI,
String backendURI, String cachePolicy, int cacheSize,
float flushFactor, boolean printTrace) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_OVERWRITE_ROOTS, false);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_READ_ONLY_MODE, false);
morsaResource.load(options);
update(morsaResource, options);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests the update of a model using the Morsa repository with partial load
* on demand. The update executes the Grabats query over a model and
* depending on the number of results it performs one of the following
* actions:
*
* 1. If the result size is 0, it does nothing 2. If the result size is 1,
* that object is deleted 3. If the result size is 2, parents are exchanged
* between both objects 4. If the result size is greater than 2, parents are
* exchanged between the first and the last objects and the object in the
* middle is deleted
*
* This update can only be executed on a model that conforms to the
* metamodel defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param cachePolicy
* the name of the cache policy class
* @param cacheSize
* the size of the cache
* @param flushFactor
* the flush factor of the cache
* @param clusterDepth
* the depth of the partial load cluster
* @param clusterBreadth
* the breadth of the partial load cluster
* @param printTrace
* flag for trace print
*/
static public void testUpdatePartialLoad(ResourceSet rs, String morsaURI,
String backendURI, String cachePolicy, int cacheSize,
float flushFactor, int clusterDepth, int clusterBreadth,
boolean printTrace) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_PARTIAL_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_DEPTH,
clusterDepth);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_BREADTH,
clusterBreadth);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_OVERWRITE_ROOTS, false);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_READ_ONLY_MODE, false);
morsaResource.load(options);
update(morsaResource, options);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests the Grabats query on a model with full load.
*
* The query finds all classes (TypeDeclaration) that declare static public
* methods (MethodDeclaration) whose return type is the same class
*
* This query can only be executed on a model that conforms to the metamodel
* defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet in which the MorsaResource is contained
* @param morsaURI
* the Morsa URI of the model
* @param printTrace
* true if trace must be printed, false if not
* @param queryAsCode
* true if the query must be executed with raw EMF code, false if
* it must be executed with the dedicated query DSL
* @param readOnly
* flag for read only mode
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testGrabatsFullLoad(ResourceSet rs, String morsaURI,
String backendURI, boolean printTrace, String queryEngine,
boolean readOnly) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_DEMAND_LOAD, false);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage dom = morsaResource.loadMetamodel("org.amma.dsl.jdt.dom");
List<EPackage> pkgs = registerPackages(dom);
testGrabatsMorsa_Transformation(morsaResource, queryEngine, pkgs);
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
/**
* Tests the Grabats query on a model with partial load on demand
*
* The query finds all classes (TypeDeclaration) that declare static public
* methods (MethodDeclaration) whose return type is the same class
*
* This query can only be executed on a model that conforms to the metamodel
* defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param cachePolicy
* the name of the cache policy class
* @param cacheSize
* the size of the cache
* @param flushFactor
* the flush factor of the cache
* @param clusterDepth
* the depth of the partial load on demand cluster
* @param clusterBreadth
* the breadth of the partial load on demand cluster
* @param printTrace
* flag for trace print
* @param queryAsCode
* true if the query must be executed with raw EMF code, false if
* it must be executed with the dedicated query DSL
* @param readOnly
* flag for read only mode
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testGrabatsPartialLoad(ResourceSet rs, String morsaURI,
String backendURI, String cachePolicy, int cacheSize,
float flushFactor, int clusterDepth, int clusterBreadth,
boolean printTrace, String queryEngine, boolean readOnly) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_PARTIAL_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_DEPTH, clusterDepth);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_BREADTH,
clusterBreadth);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage dom = morsaResource.loadMetamodel("org.amma.dsl.jdt.dom");
List<EPackage> pkgs = registerPackages(dom);
testGrabatsMorsa_Transformation(morsaResource, queryEngine, pkgs);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
/**
* Tests the Grabats query on a model with single load on demand
*
* The query finds all classes (TypeDeclaration) that declare static public
* methods (MethodDeclaration) whose return type is the same class
*
* This query can only be executed on a model that conforms to the metamodel
* defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param rs
* the ResourceSet in which the MorsaResource is contained
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param cachePolicy
* the name of the cache policy class
* @param cacheSize
* the size of the cache
* @param flushFactor
* the flush factor of the cache
* @param printTrace
* true if trace must be printed, false if not
* @param queryAsCode
* true if the query must be executed with raw EMF code, false if
* it must be executed with the dedicated query DSL
* @param readOnly
* flag for read only mode
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testGrabatsSingleLoad(ResourceSet rs, String morsaURI,
String backendURI, String cachePolicy, int cacheSize,
float flushFactor, boolean printTrace, String queryEngine,
boolean readOnly) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage dom = morsaResource.loadMetamodel("org.amma.dsl.jdt.dom");
List<EPackage> pkgs = registerPackages(dom);
System.out
.println("LOAD TIME: " + (System.currentTimeMillis() - l));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
l = System.currentTimeMillis();
testGrabatsMorsa_Transformation(morsaResource, queryEngine, pkgs);
System.out.println("QUERY TIME 1: "
+ (System.currentTimeMillis() - l));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
l = System.currentTimeMillis();
testGrabatsMorsa_Transformation(morsaResource, queryEngine, pkgs);
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("QUERY TIME 2: " + (System.currentTimeMillis() - l));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Tests the special features of Morsa: loading a specific object, obtaining
* the conainer of an object, deleting single objects and updating the
* model.
*
* This test moves an object from one container to another and removes the
* old container from the model
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the model
* @param backendURI
* the URI of the repository backend
* @param objectURI
* the Morsa URI of the object that will be moved
* @param newContainerURI
* the Morsa URI of the object that will contained the moved
* object
* @param cachePolicy
* the name of the cache policy class
* @param cacheSize
* the size of the cache
* @param flushFactor
* the flush factor of the cache
* @param clusterDepth
* the depth of the partial load cluster
* @param clusterBreadth
* the breadth of the partial load cluster
* @param printTrace
* flag for trace print
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testFeatures(ResourceSet rs, String morsaURI,
String backendURI, String objectURI, String newContainerURI,
String cachePolicy, int cacheSize, float flushFactor,
int clusterDepth, int clusterBreadth, boolean printTrace) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_PARTIAL_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_DEPTH,
clusterDepth);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_BREADTH,
clusterBreadth);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_OVERWRITE_ROOTS, false);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
long l = System.currentTimeMillis();
morsaResource.load(options);
EObject obj = morsaResource.loadObject(objectURI);
System.out.println("OBJECT FOUND: " + obj);
EObject newContainer = morsaResource.loadObject(newContainerURI);
System.out.println("NEW CONTAINER FOUND: " + newContainer);
EReference containmentFeature = null;
for (EReference ref : newContainer.eClass().getEAllContainments()) {
if (obj.eClass().equals(ref.getEType())
|| obj.eClass().getEAllSuperTypes()
.contains(ref.getEType())) {
containmentFeature = ref;
break;
}
}
if (containmentFeature.isMany()) {
((List<EObject>) newContainer.eGet(containmentFeature))
.add(obj);
} else
newContainer.eSet(containmentFeature, obj);
EObject oldContainer = morsaResource.loadObject(objectURI
.substring(0, objectURI.lastIndexOf("/@")));
System.out.println("OLD CONTAINER FOUND: " + oldContainer);
EObject ancestor = morsaResource.getContainer(oldContainer);
EcoreUtil.remove(oldContainer);
morsaResource.save(options);
System.out.println("QUERY TIME: "
+ (System.currentTimeMillis() - l));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tests the deletion of a single object or a model
*
* @param rs
* the ResourceSet
* @param morsaURI
* the Morsa URI of the object to delete
* @param backendURI
* the URI of the repository backend
* @param printTrace
* trace print flag
* @param isRoot
* true if the morsaURI corresponds to a (meta)model, false if it
* corresponds to a single object
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testDelete(ResourceSet rs, String morsaURI,
String backendURI, boolean printTrace, boolean isRoot) {
Resource morsaResource = rs.createResource(URI.createURI(morsaURI));
try {
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_OVERWRITE_ROOTS, false);
long l = System.currentTimeMillis();
if (!isRoot) {
morsaResource.load(options);
((MorsaResource) morsaResource).deleteEObject(morsaURI);
morsaResource.save(options);
} else
morsaResource.delete(options);
// Thread.sleep(10000);
System.out.println("DELETE TIME: "
+ (System.currentTimeMillis() - l));
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testReferencersFullLoad(ResourceSet rs, String morsaURI,
String backendURI, boolean printTrace, boolean queryAsCode,
boolean readOnly, boolean all) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_DEMAND_LOAD, false);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage core = morsaResource
.loadMetamodel("org.amma.dsl.jdt.core");
registerPackages(core);
testReferencersMorsa(morsaResource, all, queryAsCode);
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testReferencersPartialLoad(ResourceSet rs,
String morsaURI, String backendURI, String cachePolicy,
int cacheSize, float flushFactor, int clusterDepth,
int clusterBreadth, boolean printTrace, boolean queryAsCode,
boolean readOnly, boolean all) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_PARTIAL_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_DEPTH, clusterDepth);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_BREADTH,
clusterBreadth);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage core = morsaResource
.loadMetamodel("org.amma.dsl.jdt.core");
registerPackages(core);
testReferencersMorsa(morsaResource, all, queryAsCode);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testReferencersSingleLoad(ResourceSet rs,
String morsaURI, String backendURI, String cachePolicy,
int cacheSize, float flushFactor, boolean printTrace,
boolean queryAsCode, boolean readOnly, boolean all) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage core = morsaResource
.loadMetamodel("org.amma.dsl.jdt.core");
registerPackages(core);
testReferencersMorsa(morsaResource, all, queryAsCode);
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testInclusionFullLoad(ResourceSet rs, String morsaURI,
String backendURI, boolean printTrace, boolean queryAsCode,
boolean readOnly, boolean all) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_DEMAND_LOAD, false);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage core = morsaResource
.loadMetamodel("org.amma.dsl.jdt.core");
registerPackages(core);
testInclusionMorsa(morsaResource, queryAsCode);
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testInclusionPartialLoad(ResourceSet rs,
String morsaURI, String backendURI, String cachePolicy,
int cacheSize, float flushFactor, int clusterDepth,
int clusterBreadth, boolean printTrace, boolean queryAsCode,
boolean readOnly, boolean all) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_PARTIAL_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_DEPTH, clusterDepth);
options.put(MorsaResource.OPTION_DEFAULT_CLUSTER_BREADTH,
clusterBreadth);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage core = morsaResource
.loadMetamodel("org.amma.dsl.jdt.core");
registerPackages(core);
testInclusionMorsa(morsaResource, queryAsCode);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static public void testInclusionSingleLoad(ResourceSet rs, String morsaURI,
String backendURI, String cachePolicy, int cacheSize,
float flushFactor, boolean printTrace, boolean queryAsCode,
boolean readOnly, boolean all) {
MorsaResource morsaResource = (MorsaResource) rs.createResource(URI
.createURI(morsaURI));
Map options = new HashMap();
options.put(MorsaResource.OPTION_SERVER_URI, backendURI);
options.put(MorsaResource.OPTION_CACHE_POLICY, cachePolicy);
options.put(MorsaResource.OPTION_MAX_CACHE_SIZE, cacheSize);
options.put(MorsaResource.OPTION_CACHE_FLUSH_FACTOR, flushFactor);
options.put(MorsaResource.OPTION_DEMAND_LOAD_STRATEGY,
MorsaResource.OPTION_SINGLE_LOAD_STRATEGY);
options.put(MorsaResource.OPTION_DEMAND_LOAD, true);
options.put(MorsaResource.OPTION_PRINT_TRACE, printTrace);
if (readOnly)
options.put(MorsaResource.OPTION_READ_ONLY_MODE, true);
long l = System.currentTimeMillis();
try {
morsaResource.load(options);
EPackage core = morsaResource
.loadMetamodel("org.amma.dsl.jdt.core");
registerPackages(core);
testInclusionMorsa(morsaResource, queryAsCode);
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println("QUERY TIME: " + (System.currentTimeMillis() - l));
}
static private void checkTypeDeclaration(EObject typeDeclaration) {
EPackage dom = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.dom");
EClass typeDeclarationClass = (EClass) dom
.getEClassifier("TypeDeclaration");
EClass methodDeclarationClass = (EClass) dom
.getEClassifier("MethodDeclaration");
EClass modifierClass = (EClass) dom.getEClassifier("Modifier");
EClass simpleNameClass = (EClass) dom.getEClassifier("SimpleName");
EObject typeName = (EObject) typeDeclaration.eGet(typeDeclarationClass
.getEStructuralFeature("name"));
if (typeName == null)
return;
String typeQName = (String) typeName.eGet(typeName.eClass()
.getEStructuralFeature("fullyQualifiedName"));
EReference bodyDeclarationsRef = (EReference) typeDeclarationClass
.getEStructuralFeature("bodyDeclarations");
Object o = typeDeclaration.eGet(bodyDeclarationsRef);
if (o != null) {
List<EObject> bodyDeclarationList = (List<EObject>) o;
boolean found = false;
for (int j = 0; j < bodyDeclarationList.size() && !found; j++) {
EObject bodyDeclaration = bodyDeclarationList.get(j);
if (bodyDeclaration.eClass() == methodDeclarationClass) {
EReference modifiersRef = (EReference) methodDeclarationClass
.getEStructuralFeature("modifiers");
Object o2 = bodyDeclaration.eGet(modifiersRef);
if (o2 != null) {
List<EObject> modifiersList = (List<EObject>) o2;
boolean foundStatic = false;
boolean foundPublic = false;
for (int k = 0; k < modifiersList.size(); k++) {
EObject modifier = modifiersList.get(k);
if (modifier.eClass() == modifierClass) {
boolean isStatic = (Boolean) modifier
.eGet(modifierClass
.getEStructuralFeature("static"));
boolean isPublic = (Boolean) modifier
.eGet(modifierClass
.getEStructuralFeature("public"));
if (isStatic)
foundStatic = true;
if (isPublic)
foundPublic = true;
}
}
if (foundStatic && foundPublic) {
EReference returnTypeRef = (EReference) methodDeclarationClass
.getEStructuralFeature("returnType");
Object o3 = bodyDeclaration.eGet(returnTypeRef);
if (o3 != null) {
EObject returnType = (EObject) o3;
EReference typeNameRef = (EReference) returnType
.eClass().getEStructuralFeature("name");
if (typeNameRef != null) {
EObject returnTypeName = (EObject) returnType
.eGet(typeNameRef);
if (returnTypeName != null) {
String returnTypeQName = (String) returnTypeName
.eGet(returnTypeName
.eClass()
.getEStructuralFeature(
"fullyQualifiedName"));
if (returnTypeQName.equals(typeQName)) {
EObject simpleName = (EObject) bodyDeclaration
.eGet(methodDeclarationClass
.getEStructuralFeature("name"));
System.out
.println(typeQName
+ " : "
+ simpleName
.eGet(simpleNameClass
.getEStructuralFeature("fullyQualifiedName")));
found = true;
}
}
}
}
}
}
}
}
}
}
/**
* Executes the Grabats query on a model using the Morsa Query DSL
*
* The query finds all classes (TypeDeclaration) that declare static public
* methods (MethodDeclaration) whose return type is the same class
*
* This query can only be executed on a model that conforms to the metamodel
* defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param morsaResource
* the Morsa resource that holds the model
*/
static private void grabatsQuery(MorsaResource morsaResource) {
EPackage dom = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.dom");
EClass typeDeclarationClass = (EClass) dom
.getEClassifier("TypeDeclaration");
EClass methodDeclarationClass = (EClass) dom
.getEClassifier("MethodDeclaration");
EClass simpleNameClass = (EClass) dom.getEClassifier("SimpleName");
if (typeDeclarationQuery == null) {
typeDeclarationQuery = SELECT(
"org.amma.dsl.jdt.dom/TypeDeclaration").FROM(morsaResource)
.asProxies().includeSubtypes().done();
}
Collection<EObject> typeDeclarationList = morsaResource
.query(typeDeclarationQuery);
for (EObject typeDeclaration : typeDeclarationList) {
EObject typeDeclarationName = (EObject) typeDeclaration
.eGet(typeDeclarationClass.getEStructuralFeature("name"));
String typeDeclarationQName = (String) typeDeclarationName
.eGet(typeDeclarationName.eClass().getEStructuralFeature(
"fullyQualifiedName"));
MorsaQuery query;
if (morsaQueries.containsKey(typeDeclaration)) {
query = morsaQueries.get(typeDeclaration);
} else {
query = SELECT("org.amma.dsl.jdt.dom/MethodDeclaration")
.FROM(typeDeclaration)
.WHERE(navigate("returnType")
.ofType("org.amma.dsl.jdt.dom/SimpleType")
.navigate("name")
.ofType("org.amma.dsl.jdt.dom/SimpleName")
.STREQ("fullyQualifiedName",
typeDeclarationQName))
.AND(navigate("modifiers").ofType(
"org.amma.dsl.jdt.dom/Modifier").BOOLEQ(
"static", true))
.AND(navigate("modifiers").ofType(
"org.amma.dsl.jdt.dom/Modifier").BOOLEQ(
"public", true)).asProxies().includeSubtypes()
.done();
morsaQueries.put(typeDeclaration, query);
}
Collection<EObject> result = morsaResource.query(query);
if (!result.isEmpty()) {
EObject obj = result.iterator().next();
EObject simpleName = (EObject) obj.eGet(methodDeclarationClass
.getEStructuralFeature("name"));
System.out.println("FOUND: "
+ typeDeclarationQName
+ " : "
+ simpleName.eGet(simpleNameClass
.getEStructuralFeature("fullyQualifiedName")));
}
}
}
/**
* Executes the Grabats query on a model using EMF code
*
* The query finds all classes (TypeDeclaration) that declare static public
* methods (MethodDeclaration) whose return type is the same class
*
* This query can only be executed on a model that conforms to the metamodel
* defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param morsaResource
* the Morsa resource that holds the model
*/
static private void grabatsQueryAsCode(
Collection<EObject> typeDeclarationList, String queryEngine) {
Iterator<EObject> typeDeclarationIterator = typeDeclarationList
.iterator();
while (typeDeclarationIterator.hasNext()) {
EObject typeDeclaration = typeDeclarationIterator.next();
if (queryEngine.equals("emf"))
checkTypeDeclaration(typeDeclaration);
}
}
static private void testInclusionMorsa(MorsaResource morsaResource,
boolean queryAsCode) {
if (queryAsCode) {
Collection<EObject> typeList = morsaResource.loadObjects(
"org.amma.dsl.jdt.dom", "Type", true, true);
inclusionQueryAsCode(typeList);
} else {
inclusionQuery(morsaResource);
}
}
static private void inclusionQuery(MorsaResource morsaResource) {
EPackage core = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.core");
Collection<EObject> typeList = SELECT("org.amma.dsl.jdt.dom/Type")
.FROM(morsaResource).asProxies().find();
for (EObject type : typeList) {
System.out.println(type + " :: "
+ morsaResource.include(typeList, type) + " :: "
+ morsaResource.include(typeList, core));
}
typeList = SELECT("org.amma.dsl.jdt.dom/Type").FROM(morsaResource)
.asProxies().find();
for (EObject type : typeList) {
Collection<EObject> methods = (Collection<EObject>) type.eGet(type
.eClass().getEStructuralFeature("methods"));
if (methods != null && !methods.isEmpty()) {
System.out.println(type
+ " :: "
+ morsaResource.include(type, "methods", methods
.iterator().next()) + " :: "
+ morsaResource.include(type, "methods", type));
}
}
}
static private void inclusionQueryAsCode(Collection<EObject> typeList) {
EPackage core = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.core");
for (EObject type : typeList) {
System.out.println(type + " :: " + typeList.contains(type) + " :: "
+ typeList.contains(core));
}
for (EObject type : typeList) {
Collection<EObject> methods = (Collection<EObject>) type.eGet(type
.eClass().getEStructuralFeature("methods"));
if (methods != null && !methods.isEmpty()) {
System.out.println(type
+ " :: "
+ methods.contains((methods.iterator().next()) + " :: "
+ methods.contains(type)));
}
}
}
static private void referencersQuery(MorsaResource morsaResource,
boolean all) {
Collection<EObject> typeList = SELECT("org.amma.dsl.jdt.core/IType")
.FROM(morsaResource).asProxies().find();
for (EObject type : typeList) {
Collection<EObject> refs = all ? morsaResource.getReferencers(type,
true) : SELECT("org.amma.dsl.jdt.core/ICompilationUnit")
.FROM(morsaResource)
.WHERE(navigate("types").ofType(
"org.amma.dsl.jdt.core/IType").CONTAINS(type))
.asProxies().includeSubtypes().find();
if (!refs.isEmpty())
System.out.println(type);
for (EObject ref : refs) {
System.out.println("\t" + ref);
}
}
}
static private void testReferencersMorsa(MorsaResource morsaResource,
boolean all, boolean queryAsCode) {
if (queryAsCode) {
Collection<EObject> typeList = SELECT("org.amma.dsl.jdt.core/IType")
.FROM(morsaResource).asProxies().find();
for (EObject type : typeList)
referencersQueryAsCode(type, morsaResource, all);
} else
referencersQuery(morsaResource, all);
}
static private void referencersQueryAsCode(EObject type, Resource resource,
boolean all) {
EPackage core = EPackage.Registry.INSTANCE
.getEPackage("org.amma.dsl.jdt.core");
EClass compilationUnitClass = (EClass) core
.getEClassifier("ICompilationUnit");
System.out.println(type);
Iterator<EObject> it = resource.getAllContents();
while (it.hasNext()) {
EObject obj = it.next();
if (all) {
for (EReference ref : obj.eClass().getEAllReferences()) {
if (ref.getEReferenceType().isSuperTypeOf(
compilationUnitClass)) {
List<EObject> refValues = ref.isMany() ? (List<EObject>) obj
.eGet(ref) : Collections
.singletonList((EObject) obj.eGet(ref));
if (refValues.contains(type)) {
System.out.println("\t" + obj);
}
}
}
System.out.println("\t" + obj);
} else if (obj.eClass().equals(compilationUnitClass)
&& ((List<EObject>) obj.eGet(compilationUnitClass
.getEStructuralFeature("types"))).contains(type)) {
System.out.println("\t" + obj);
}
}
}
/**
* Registers an EPackage and all its subpackages in the global package
* registry
*
* @param root
* the EPackage
*/
static private List<EPackage> registerPackages(EPackage root) {
ArrayList<EPackage> result = new ArrayList<EPackage>();
result.add(root);
if (!root.getNsURI().equals(EcorePackage.eNS_URI)) {
EPackage.Registry.INSTANCE.put(root.getNsURI(), root);
for (EPackage pkg : root.getESubpackages()) {
List<EPackage> pkgs = registerPackages(pkg);
result.addAll(pkgs);
}
}
return result;
}
static private void testGrabatsMorsa_Transformation(MorsaResource morsaResource,
String queryEngine, List<EPackage> pkgs) throws IOException {
if (queryEngine.equals("emf") || queryEngine.equals("ocl")) {
if (typeDeclarationQuery == null) {
typeDeclarationQuery = SELECT(
"org.amma.dsl.jdt.dom/TypeDeclaration")
.FROM(morsaResource).asProxies().includeSubtypes()
.done();
}
Collection<EObject> typeDeclarationList = morsaResource
.query(typeDeclarationQuery);
int i = 0;
for (EObject eObject : typeDeclarationList) {
// System.out.println(eObject);
i++;
}
System.out.println(i);
transformToKdm(typeDeclarationList, pkgs);
// grabatsQueryAsCode(typeDeclarationList, queryEngine);
} else
grabatsQuery(morsaResource);
}
/**
* Traverses a model in depth first or breadth first order
*
* @param morsaResource
* the resource that contains the model
*
* @param order
* DEPTH_FIRST_ORDER for depth first order, BREADTH_FIRST_ORDER
* for breadth first order
* @return
*/
static private int traverseModel(Resource morsaResource, int order) {
int objectCount = 0;
EObject[] contents = (EObject[]) morsaResource.getContents().toArray();
for (EObject content : contents) {
List<EObject> children = new LinkedList<EObject>();
children.add(content);
while (!children.isEmpty()) {
EObject child = children.remove(0);
switch (order) {
case DEPTH_FIRST_ORDER:
children.addAll(0, child.eContents());
break;
case BREADTH_FIRST_ORDER:
children.addAll(child.eContents());
break;
}
// if (child.eIsProxy()) {
// System.out.println("FAILED. PROXY UNRESOLVED: "
// + ((InternalEObject) child).eProxyURI().fragment());
// }
if (!child.eIsProxy())
objectCount++;
}
}
return objectCount;
}
/**
* Executes the update of a model using the Morsa repository. The update
* executes the Grabats query over a model and depending on the number of
* results it performs one of the following actions:
*
* 1. If the result size is 0, it does nothing 2. If the result size is 1,
* that object is deleted 3. If the result size is 2, parents are exchanged
* between both objects 4. If the result size is greater than 2, parents are
* exchanged between the first and the last objects and the object in the
* middle is deleted
*
* This update can only be executed on a model that conforms to the
* metamodel defined by the following EPackages: org.amma.dsl.jdt.dom,
* org.amma.dsl.jdt.ast, org.amma.dsl.jdt.primitiveTypes
*
* @param morsaResource
* the Morsa EMF Resource
* @param options
* the options for the Morsa EMF Resource the ResourceSet
*/
static private void update(MorsaResource morsaResource, Map options) {
List<EObject> foundObjs = new LinkedList<EObject>();
EPackage dom = morsaResource.loadMetamodel("org.amma.dsl.jdt.dom");
EClass typeDeclarationClass = (EClass) dom
.getEClassifier("TypeDeclaration");
EClass methodDeclarationClass = (EClass) dom
.getEClassifier("MethodDeclaration");
EClass modifierClass = (EClass) dom.getEClassifier("Modifier");
EClass simpleNameClass = (EClass) dom.getEClassifier("SimpleName");
EClass simpleTypeClass = (EClass) dom.getEClassifier("SimpleType");
Collection<EObject> typeDeclarationList = morsaResource.loadObjects(
typeDeclarationClass, false, -1, true);
for (EObject typeDeclaration : typeDeclarationList) {
EObject typeDeclarationName = (EObject) typeDeclaration
.eGet(typeDeclarationClass.getEStructuralFeature("name"));
String typeDeclarationQName = (String) typeDeclarationName
.eGet(typeDeclarationName.eClass().getEStructuralFeature(
"fullyQualifiedName"));
Condition condition = new REF(methodDeclarationClass, "returnType",
new REF(simpleTypeClass, "name", new STREQ(simpleNameClass,
"fullyQualifiedName", typeDeclarationQName)))
.AND(new REF(methodDeclarationClass, "modifiers",
new BOOLEQ(modifierClass, "static", true))
.AND(new REF(methodDeclarationClass, "modifiers",
new BOOLEQ(modifierClass, "public", true))));
// Collection<EObject> result = morsaResource.query(typeDeclaration,
// condition, true, -1, -1, true);
// if (!result.isEmpty()) {
// System.err.println("FOUND " + typeDeclaration);
// foundObjs.add(typeDeclaration);
// }
}
if (foundObjs.size() > 0) {
long l = System.currentTimeMillis();
EObject firstResult = foundObjs.get(0);
EReference firstContainingFeature = (EReference) firstResult
.eContainingFeature();
EObject firstContainer = firstResult.eContainer();
if (foundObjs.size() > 1) {
EObject lastResult = foundObjs.get(foundObjs.size() - 1);
EReference lastContainingFeature = (EReference) lastResult
.eContainingFeature();
EObject lastContainer = lastResult.eContainer();
if (firstResult.eContainingFeature().isMany()) {
((List<EObject>) firstContainer
.eGet(firstContainingFeature)).set(
((List<EObject>) firstContainer
.eGet(firstContainingFeature))
.indexOf(firstResult), lastResult);
} else {
firstContainer.eSet(firstResult.eContainingFeature(),
lastResult);
}
if (lastContainingFeature.isMany()) {
((List<EObject>) lastContainer.eGet(lastContainingFeature))
.add(firstResult);
} else {
lastContainer.eSet(lastContainingFeature, firstResult);
}
if (foundObjs.size() > 2) {
EObject middleResult = foundObjs
.get((foundObjs.size() - 1) / 2);
EObject middleContainer = middleResult.eContainer();
if (middleResult.eContainingFeature().isMany()) {
((List<EObject>) middleContainer.eGet(middleResult
.eContainingFeature())).remove(middleResult);
} else {
middleContainer.eUnset(middleResult
.eContainingFeature());
}
}
}
else {
if (firstResult.eContainingFeature().isMany()) {
((List<EObject>) firstContainer.eGet(firstResult
.eContainingFeature())).remove(firstResult);
} else {
firstContainer.eUnset(firstResult.eContainingFeature());
}
}
try {
morsaResource.save(options);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("UPDATE TIME: "
+ (System.currentTimeMillis() - l));
}
}
static private Map<String, String> mapArgs(String[] args) {
Map<String, String> argMap = new HashMap<String, String>();
for (String arg : args) {
String[] splittedArg = arg.split("=");
argMap.put(splittedArg[0], splittedArg[1]);
}
return argMap;
}
}
| gpl-3.0 |
sokratis12GR/ModFetcher | src/main/java/com/sokratis12gr/modfetcher/commands/CommandHelp.java | 1729 | package com.sokratis12gr.modfetcher.commands;
import com.sokratis12gr.modfetcher.CommandHandler;
import com.sokratis12gr.modfetcher.ModFetcher;
import com.sokratis12gr.modfetcher.util.Utilities;
import sx.blah.discord.handle.obj.IMessage;
import java.util.Map.Entry;
import static com.sokratis12gr.modfetcher.util.EmbedBase.getEmbed;
import static com.sokratis12gr.modfetcher.util.Utilities.sendPrivateMessage;
public class CommandHelp extends CommandUser {
@Override
public void processCommand(IMessage message, String[] args) {
String descriptions = "";
if (args.length > 1)
for (int index = 1; index < args.length; index++) {
final Command cmd = CommandHandler.getCommand(args[index]);
if (cmd != null && cmd.isValidUsage(message))
descriptions += ModFetcher.COMMAND_KEY + args[index] + " - " + cmd.getDescription() + Utilities.SEPERATOR + Utilities.SEPERATOR;
}
else
for (final Entry<String, Command> command : CommandHandler.getCommands().entrySet())
if (command.getValue().isValidUsage(message))
descriptions += ModFetcher.COMMAND_KEY + command.getKey() + " - " + command.getValue().getDescription() + Utilities.SEPERATOR + Utilities.SEPERATOR;
getEmbed().withDesc(descriptions);
sendPrivateMessage(message.getAuthor(), "", getEmbed().build());
}
@Override
public String getDescription() {
return "Lists all commands available to the user, along with a basic description of each command. You can run the command with other command names as additional arguments to get a more thorough description of the command.";
}
} | gpl-3.0 |
zuonima/sql-utils | src/main/java/com/alibaba/druid/sql/dialect/db2/visitor/DB2OutputVisitor.java | 2585 | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.sql.dialect.db2.visitor;
import com.alibaba.druid.sql.JdbcConstants;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOperator;
import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.alibaba.druid.sql.dialect.db2.ast.stmt.DB2SelectQueryBlock;
import com.alibaba.druid.sql.dialect.db2.ast.stmt.DB2ValuesStatement;
import com.alibaba.druid.sql.visitor.SQLASTOutputVisitor;
public class DB2OutputVisitor extends SQLASTOutputVisitor implements DB2ASTVisitor {
public DB2OutputVisitor(Appendable appender){
super(appender, JdbcConstants.DB2);
}
public DB2OutputVisitor(Appendable appender, boolean parameterized){
super(appender, parameterized);
this.dbType = JdbcConstants.DB2;
}
@Override
public boolean visit(DB2SelectQueryBlock x) {
this.visit((SQLSelectQueryBlock) x);
if (x.isForReadOnly()) {
println();
print0(ucase ? "FOR READ ONLY" : "for read only");
}
if (x.getIsolation() != null) {
println();
print0(ucase ? "WITH " : "with ");
print0(x.getIsolation().name());
}
if (x.getOptimizeFor() != null) {
println();
print0(ucase ? "OPTIMIZE FOR " : "optimize for ");
x.getOptimizeFor().accept(this);
}
return false;
}
@Override
public void endVisit(DB2SelectQueryBlock x) {
}
@Override
public boolean visit(DB2ValuesStatement x) {
print0(ucase ? "VALUES " : "values ");
x.getExpr().accept(this);
return false;
}
@Override
public void endVisit(DB2ValuesStatement x) {
}
protected void printOperator(SQLBinaryOperator operator) {
if (operator == SQLBinaryOperator.Concat) {
print0(ucase ? "CONCAT" : "concat");
} else {
print0(ucase ? operator.name : operator.name_lcase);
}
}
}
| gpl-3.0 |
Metalcon/bootstrap | src/main/java/de/metalcon/bootstrap/parsers/TrackCsvParser.java | 1547 | package de.metalcon.bootstrap.parsers;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import de.metalcon.bootstrap.domain.entities.Track;
public class TrackCsvParser extends CsvParser<Track> {
public TrackCsvParser(
String filePath) throws FileNotFoundException {
super(filePath);
}
@Override
protected List<Track> parse() throws IOException {
List<Track> tracks = new LinkedList<Track>();
String[] track;
long legacyId;
int trackNumber;
String trackName;
int duration;
long discId;
long bandId;
reader.readLine();
while ((track = getEntry()) != null) {
// [0] ID
legacyId = Long.valueOf(track[0]);
// [1] Number
trackNumber = Integer.valueOf(track[1]);
// [2] Title
trackName = track[2];
// [3] Duration*
if (!isNull(track[3])) {
duration = Integer.valueOf(track[3]);
} else {
duration = 0;
}
// [4] Disc_ID
discId = Long.valueOf(track[4]);
// [5] Band_ID*
if (!isNull(track[5])) {
bandId = Long.valueOf(track[4]);
} else {
bandId = 0;
}
tracks.add(new Track(legacyId, trackName, trackNumber, duration,
discId, bandId));
}
return tracks;
}
}
| gpl-3.0 |
gralog/gralog | gralog-first-order-logic/src/main/java/gralog/firstorderlogic/formula/FirstOrderAnd.java | 3570 | /* This file is part of Gralog, Copyright (c) 2016-2018 LaS group, TU Berlin.
* License: https://www.gnu.org/licenses/gpl.html GPL version 3 or later. */
package gralog.firstorderlogic.formula;
import gralog.finitegame.structure.*;
import gralog.progresshandler.ProgressHandler;
import gralog.structure.Structure;
import gralog.structure.Vertex;
import java.util.HashMap;
import gralog.rendering.Vector2D;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
public class FirstOrderAnd extends FirstOrderFormula {
FirstOrderFormula subformula1;
FirstOrderFormula subformula2;
public FirstOrderAnd(FirstOrderFormula subformula1,
FirstOrderFormula subformula2) {
this.subformula1 = subformula1;
this.subformula2 = subformula2;
}
@Override
public String toString(FormulaPosition pos, FormulaEndPosition endPos) {
String result = subformula1.toString(FormulaPosition.AndLeft, FormulaEndPosition.MIDDLE) + " ∧ "
+ subformula2.toString(FormulaPosition.AndRight, endPos);
if (pos == FormulaPosition.Not || pos == FormulaPosition.AndRight)
return "(" + result + ")";
return result;
}
@Override
public boolean evaluate(Structure s, HashMap<String, Vertex> varassign,
ProgressHandler onprogress) throws Exception {
if (!subformula1.evaluate(s, varassign, onprogress))
return false;
return subformula2.evaluate(s, varassign, onprogress);
}
@Override
public Subformula evaluateProver(Structure s, HashMap<String, Vertex> varassign,
ProgressHandler onprogress) throws Exception {
Subformula b = new Subformula();
Subformula b1 = subformula1.evaluateProver(s, varassign, onprogress);
b1.assignment = new HashMap<>(varassign);
b1.subformula = subformula1.toString();
b.children.add(b1);
Subformula b2 = subformula2.evaluateProver(s, varassign, onprogress);
b2.assignment = b1.assignment;
b2.subformula = subformula2.toString();
b.children.add(b2);
b.value = (b1.value && b2.value);
return b;
}
@Override
public GameGraphResult constructGameGraph(Structure s,
HashMap<String, Vertex> varassign, FiniteGame game,
Vector2D coor) {
FiniteGamePosition parent = game.addVertex();
parent.setCoordinates(coor);
parent.label = toString() + ", "
+ FirstOrderFormula.variableAssignmentToString(varassign);
// "and", so this is a player 1 position.
parent.player1Position = true;
GameGraphResult c1 = subformula1.constructGameGraph(
s, varassign, game, new Vector2D(coor.getX() + X_OFFSET, coor.getY()));
game.addEdge(parent, c1.position);
GameGraphResult c2 = subformula2.constructGameGraph(
s, varassign, game, new Vector2D(coor.getX() + X_OFFSET, coor.getY() + c1.height + 1));
FiniteGamePosition w2 = game.addVertex();
game.addEdge(parent, c2.position);
return new GameGraphResult(parent, c1.height + c2.height + 1);
}
@Override
public Set<String> variables() throws Exception {
Set<String> result = new HashSet<>();
result.addAll(subformula1.variables());
result.addAll(subformula2.variables());
return result;
}
@Override
public String substitute(HashMap<String, String> replace) throws Exception {
return subformula1.substitute(replace) + " \\wedge " + subformula1.substitute(replace);
}
}
| gpl-3.0 |
Echtzeitsysteme/mindroid | impl/serverApp/src/main/java/se/vidstige/jadb/managers/PropertyManager.java | 1696 | package se.vidstige.jadb.managers;
import se.vidstige.jadb.JadbDevice;
import se.vidstige.jadb.JadbException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A class which works with properties, uses getprop and setprop methods of android shell
*/
public class PropertyManager {
private final Pattern pattern = Pattern.compile("^\\[([a-zA-Z0-9_.-]*)\\]:.\\[([^\\[\\]]*)\\]");
private final JadbDevice device;
public PropertyManager(JadbDevice device) {
this.device = device;
}
public Map<String, String> getprop() throws IOException, JadbException {
try (BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(device.executeShell("getprop")))) {
return parseProp(bufferedReader);
}
}
private Map<String, String> parseProp(BufferedReader bufferedReader) throws IOException {
HashMap<String, String> result = new HashMap<>();
String line;
Matcher matcher = pattern.matcher("");
while ((line = bufferedReader.readLine()) != null) {
matcher.reset(line);
if (matcher.find()) {
if (matcher.groupCount() < 2) {
System.err.println("Property line: " + line + " does not match patter. Ignoring");
continue;
}
String key = matcher.group(1);
String value = matcher.group(2);
result.put(key, value);
}
}
return result;
}
}
| gpl-3.0 |
gama-platform/gama | ummisco.gama.ui.shared/src/ummisco/gama/ui/resources/IGamaIcons.java | 3183 | /*********************************************************************************************
*
* 'IGamaIcons.java, in plugin ummisco.gama.ui.shared, is part of the source code of the GAMA modeling and simulation
* platform. (v. 1.8.1)
*
* (c) 2007-2020 UMI 209 UMMISCO IRD/UPMC & Partners
*
* Visit https://github.com/gama-platform/gama for license information and developers contact.
*
*
**********************************************************************************************/
package ummisco.gama.ui.resources;
/**
* Class IStrings.
*
* @author drogoul
* @since 13 sept. 2013
*
*/
public interface IGamaIcons {
// Display toolbar
String DISPLAY_TOOLBAR_PAUSE = "display.pause3";
String DISPLAY_TOOLBAR_SYNC = "display.sync3";
String DISPLAY_TOOLBAR_SNAPSHOT = "display.snapshot2";
String DISPLAY_TOOLBAR_ZOOMIN = "display.zoomin2";
String DISPLAY_TOOLBAR_CSVEXPORT = "menu.saveas2";
String DISPLAY_TOOLBAR_ZOOMOUT = "display.zoomout2";
String DISPLAY_TOOLBAR_ZOOMFIT = "display.zoomfit2";
// Menus
String MENU_BROWSE = "menu.browse2";;
String MENU_POPULATION = "display.agents2";
String MENU_AGENT = "menu.agent2";
String MENU_INSPECT = "menu.inspect2";;
String MENU_HIGHLIGHT = "menu.highlight2";
String MENU_KILL = "menu.kill2";
String MENU_FOCUS = "menu.focus2";
String MENU_FOLLOW = "menu.follow2";
String MENU_ADD_MONITOR = "menu.monitor2";
String MENU_RUN_ACTION = "menu.action2";
// Layers
String LAYER_GRID = "layer.grid2";
String LAYER_SPECIES = "layer.species2";
String LAYER_AGENTS = "layer.agents2";
String LAYER_GRAPHICS = "layer.graphics2";
String LAYER_IMAGE = "layer.image2";
String LAYER_CHART = "layer.chart2";
// Actions
String ACTION_REVERT = "action.revert2";
String ACTION_CLEAR = "action.clear2";
// User Panels
String PANEL_CONTINUE = "panel.continue2";
String PANEL_INSPECT = MENU_INSPECT;
// Preferences tabs. 24x24
String PREFS_GENERAL = "prefs/prefs.general2";
String PREFS_EDITOR = "prefs/prefs.editor2";
String PREFS_LIBS = "prefs/prefs.libraries2";
// Navigator
String FOLDER_BUILTIN = "navigator/folder.library2";
String FOLDER_PLUGIN = "navigator/folder.plugin2";
String FOLDER_TEST = "navigator/folder.test2";
String FOLDER_PROJECT = "navigator/folder.user2";
String FOLDER_MODEL = "navigator/folder.model3";
String FOLDER_RESOURCES = "navigator/folder.resources2";
String FILE_ICON = "navigator/file.icon2";
String FOLDER_USER = "navigator/folder.user";
// Editor specific
String BUTTON_GUI = "small.run";
String BUTTON_BATCH = "small.batch";
String BUTTON_BACK = "small.run.and.back";
// Small Icons
String SMALL_PLUS = "small.plus";
String SMALL_MINUS = "small.minus";
String SMALL_EXPAND = "small.expand";
String SMALL_COLLAPSE = "small.collapse";
String SMALL_PAUSE = "small.pause";
String SMALL_RESUME = "small.resume";
String SMALL_CLOSE = "small.close";
// Overlays
String OVERLAY_OK = "navigator/overlay.ok2";
// Viewers
String CHECKED = "viewers/checked";
String UNCHECKED = "viewers/unchecked";
String STYLE = "viewers/style";
String FEATURE = "viewers/feature";
String UP = "viewers/up";
String DOWN = "viewers/down";
}
| gpl-3.0 |
arraydev/snap-desktop | snap-ui/src/main/java/org/esa/snap/framework/ui/product/SourceProductList.java | 10757 | /*
* Copyright (C) 2014 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.framework.ui.product;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.core.Assert;
import com.bc.ceres.swing.binding.ComponentAdapter;
import org.esa.snap.framework.datamodel.Product;
import org.esa.snap.framework.datamodel.ProductNode;
import org.esa.snap.framework.ui.AppContext;
import org.esa.snap.framework.ui.UIUtils;
import org.esa.snap.framework.ui.tool.ToolButtonFactory;
import org.esa.snap.util.Debug;
import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataListener;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* Enables clients to create a component for choosing source products. The list of source products can arbitrarily be
* composed of
* <ul>
* <li>currently opened products</li>
* <li>single products anywhere in the file system</li>
* <li>whole directories anywhere in the file system and</li>
* <li>recursive directories anywhere in the file system</li>
* </ul>
* <p>
* The file paths the user chooses are stored as objects of type {@link java.io.File} within the property that is passed
* into the constructor. Products that are chosen from the product tree can be retrieved via
* {@link #getSourceProducts()}. So, clients of these must take care that the value in the given property is taken into
* account as well as the return value of that method.
*
* The property that serves as target container for the source product paths must be of type
* <code>String[].class</code>. Changes in the list are synchronised with the property. If the changes of the property
* values outside this component shall be synchronised with the list, it is necessary that the property lies within a
* property container.
*
* @author thomas
*/
public class SourceProductList extends ComponentAdapter {
private final AppContext appContext;
private final InputListModel listModel;
private final JList inputPathsList;
private String lastOpenInputDir;
private String lastOpenedFormat;
private boolean xAxis;
private JComponent[] components;
/**
* Constructor.
*
* @param appContext The context of the app using this component.
*
*/
public SourceProductList(AppContext appContext) {
this.appContext = appContext;
this.listModel = new InputListModel();
this.inputPathsList = createInputPathsList(listModel);
this.lastOpenInputDir = "org.esa.snap.framework.ui.product.lastOpenInputDir";
this.lastOpenedFormat = "org.esa.snap.framework.ui.product.lastOpenedFormat";
this.xAxis = true;
}
/**
* Creates an array of two JPanels. The first panel contains a list displaying the chosen products. The second panel
* contains buttons for adding and removing products, laid out in vertical direction. Note that it makes only sense
* to use both components.
*
* @return an array of two JPanels.
*/
@Override
public JComponent[] getComponents() {
if (components == null) {
components = createComponents();
}
return components;
}
/**
* Creates an array of two JPanels. The first panel contains a list displaying the chosen products. The second panel
* contains buttons for adding and removing products, laid out in configurable direction. Note that it makes only sense
* to use both components.
*
* @return an array of two JPanels.
*/
private JComponent[] createComponents() {
JPanel listPanel = new JPanel(new BorderLayout());
final JScrollPane scrollPane = new JScrollPane(inputPathsList);
scrollPane.setPreferredSize(new Dimension(100, 50));
listPanel.add(scrollPane, BorderLayout.CENTER);
final JPanel addRemoveButtonPanel = new JPanel();
int axis = this.xAxis ? BoxLayout.X_AXIS : BoxLayout.Y_AXIS;
final BoxLayout buttonLayout = new BoxLayout(addRemoveButtonPanel, axis);
addRemoveButtonPanel.setLayout(buttonLayout);
addRemoveButtonPanel.add(createAddInputButton());
addRemoveButtonPanel.add(createRemoveInputButton());
JPanel[] panels = new JPanel[2];
panels[0] = listPanel;
panels[1] = addRemoveButtonPanel;
return panels;
}
/**
* Clears the list of source products.
*/
public void clear() {
listModel.clear();
}
/**
* Allows clients to add single products.
*
* @param product A product to add.
*/
public void addProduct(Product product) {
if (product != null) {
try {
listModel.addElements(product);
} catch (ValidationException ve) {
Debug.trace(ve);
}
}
}
/**
* Returns those source products that have been chosen from the product tree.
*
* @return An array of source products.
*/
public Product[] getSourceProducts() {
return listModel.getSourceProducts();
}
private JList<Object> createInputPathsList(InputListModel inputListModel) {
JList<Object> list = new JList<>(inputListModel);
list.setCellRenderer(new SourceProductListRenderer());
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
return list;
}
private AbstractButton createAddInputButton() {
final AbstractButton addButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Plus24.gif"),
false);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final JPopupMenu popup = new JPopupMenu("Add");
final Rectangle buttonBounds = addButton.getBounds();
popup.add(new AddProductAction(appContext, listModel));
popup.add(new AddFileAction(appContext, listModel, lastOpenInputDir, lastOpenedFormat));
popup.add(new AddDirectoryAction(appContext, listModel, false, lastOpenInputDir));
popup.add(new AddDirectoryAction(appContext, listModel, true, lastOpenInputDir));
popup.show(addButton, 1, buttonBounds.height + 1);
}
});
return addButton;
}
private AbstractButton createRemoveInputButton() {
final AbstractButton removeButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Minus24.gif"),
false);
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
listModel.removeElementsAt(inputPathsList.getSelectedIndices());
}
});
return removeButton;
}
@Override
public void bindComponents() {
String propertyName = getBinding().getPropertyName();
Property property = getBinding().getContext().getPropertySet().getProperty(propertyName);
Assert.argument(property.getType().equals(String[].class), "property '" + propertyName +"' must be of type String[].class");
listModel.setProperty(property);
}
@Override
public void unbindComponents() {
listModel.setProperty(null);
}
@Override
public void adjustComponents() {
}
/**
* Add a listener that is informed every time the list's contents change.
* @param changeListener the listener to add
*/
public void addChangeListener(ListDataListener changeListener) {
listModel.addListDataListener(changeListener);
}
/**
* Remove a change listener
* @param changeListener the listener to remove
*/
public void removeChangeListener(ListDataListener changeListener) {
listModel.removeListDataListener(changeListener);
}
/**
* Setter for property name indicating the last directory the user has opened
*
* @param lastOpenedFormat property name indicating the last directory the user has opened
*/
public void setLastOpenedFormat(String lastOpenedFormat) {
this.lastOpenedFormat = lastOpenedFormat;
}
/**
* Setter for property name indicating the last product format the user has opened
* @param lastOpenInputDir property name indicating the last product format the user has opened
*/
public void setLastOpenInputDir(String lastOpenInputDir) {
this.lastOpenInputDir = lastOpenInputDir;
}
/**
* Setter for xAxis property.
*
* @param xAxis <code>true</code> if the buttons on the second panel shall be laid out in horizontal direction
*/
public void setXAxis(boolean xAxis) {
this.xAxis = xAxis;
}
private static class SourceProductListRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
String text;
if (value instanceof File) {
text = ((File) value).getAbsolutePath();
} else {
text = ((ProductNode) value).getDisplayName();
}
label.setText(text);
label.setToolTipText(text);
return label;
}
}
}
| gpl-3.0 |
potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/db4ounit/common/events/DeletionEventsTestCase.java | 1933 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.db4ounit.common.events;
import com.db4o.config.*;
import com.db4o.events.*;
import db4ounit.*;
public class DeletionEventsTestCase extends EventsTestCaseBase {
protected void configure(Configuration config) {
config.activationDepth(1);
}
public void testDeletionEvents() {
if (isEmbedded()) {
// TODO: something wrong when embedded c/s is run as part
// of the full test suite
return;
}
final EventLog deletionLog = new EventLog();
serverEventRegistry().deleting().addListener(new EventListener4() {
public void onEvent(Event4 e, EventArgs args) {
deletionLog.xing = true;
assertItemIsActive(args);
}
});
serverEventRegistry().deleted().addListener(new EventListener4() {
public void onEvent(Event4 e, EventArgs args) {
deletionLog.xed = true;
assertItemIsActive(args);
}
});
db().delete(retrieveOnlyInstance(Item.class));
db().commit();
Assert.isTrue(deletionLog.xing);
Assert.isTrue(deletionLog.xed);
}
private void assertItemIsActive(EventArgs args) {
Assert.areEqual(1, itemForEvent(args).id);
}
private Item itemForEvent(EventArgs args) {
return ((Item)((ObjectEventArgs)args).object());
}
}
| gpl-3.0 |
hu-team/coproco-deelteam1 | src/main/java/nl/hu/coproco/service/export/XmlExport.java | 4143 | package nl.hu.coproco.service.export;
import nl.hu.coproco.Main;
import nl.hu.coproco.domain.Pattern;
import nl.hu.coproco.service.PatternService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class XmlExport implements Export {
private Document document = null;
private Element rootElement = null;
public XmlExport() {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
this.document = documentBuilder.newDocument();
this.rootElement = this.document.createElement("export");
this.document.appendChild(rootElement);
}catch(Exception e) {
e.printStackTrace();
}
}
@Override
public boolean saveExport(File file) {
// We need to convert to xml first.
Element application = this.document.createElement("application");
this.rootElement.appendChild(application);
application.setAttribute("build", "" + Main.BUILD);
application.setAttribute("version", Main.VERSION);
// The list will go here
Element patterns = this.document.createElement("patterns");
// Add to root
this.rootElement.appendChild(patterns);
// Will loop
this.exportToElement(patterns);
// Will export to file
return this.exportXmlToFile(file);
}
private boolean exportXmlToFile(File originalFile) {
// Add extension
File file = new File(originalFile.getAbsoluteFile() + ".xml");
try {
// Transformers
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(this.document);
StreamResult stream = new StreamResult(file);
// Transform now.
transformer.transform(source, stream);
}catch(Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void exportToElement(Element root) {
// Loop patterns
for(Pattern pattern: PatternService.getAllPatterns()) {
Element p = this.document.createElement("pattern");
Element pName = this.document.createElement("name");
pName.appendChild(this.document.createCDATASection(pattern.getName()));
Element pProblem = this.document.createElement("problem");
pProblem.appendChild(this.document.createCDATASection(pattern.getProblem()));
Element pSolution = this.document.createElement("solution");
pSolution.appendChild(this.document.createCDATASection(pattern.getSolution()));
Element pConsequences = this.document.createElement("consequences");
pConsequences.appendChild(this.document.createCDATASection(pattern.getConsequences()));
Element pScope = this.document.createElement("scope");
pScope.appendChild(this.document.createTextNode(pattern.getScope().getName()));
Element pPurpose = this.document.createElement("purpose");
pPurpose.appendChild(this.document.createTextNode(pattern.getPurpose().getName()));
Element pDiagram = this.document.createElement("diagram");
pDiagram.appendChild(this.document.createCDATASection(pattern.getDiagram().getEncodedImage()));
p.appendChild(pName);
p.appendChild(pProblem);
p.appendChild(pSolution);
p.appendChild(pConsequences);
p.appendChild(pScope);
p.appendChild(pPurpose);
p.appendChild(pDiagram);
root.appendChild(p);
}
}
}
| gpl-3.0 |
flankerhqd/JAADAS | soot/generated/sablecc/soot/jimple/parser/node/ALongBaseType.java | 1806 | /* This file was generated by SableCC (http://www.sablecc.org/). */
package soot.jimple.parser.node;
import soot.jimple.parser.analysis.*;
@SuppressWarnings("nls")
public final class ALongBaseType extends PBaseType
{
private TLong _long_;
public ALongBaseType()
{
// Constructor
}
public ALongBaseType(
@SuppressWarnings("hiding") TLong _long_)
{
// Constructor
setLong(_long_);
}
@Override
public Object clone()
{
return new ALongBaseType(
cloneNode(this._long_));
}
public void apply(Switch sw)
{
((Analysis) sw).caseALongBaseType(this);
}
public TLong getLong()
{
return this._long_;
}
public void setLong(TLong node)
{
if(this._long_ != null)
{
this._long_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._long_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._long_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._long_ == child)
{
this._long_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._long_ == oldChild)
{
setLong((TLong) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| gpl-3.0 |
jorgevasquezp/mucommander | src/main/com/mucommander/text/Translator.java | 22326 | /*
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2012 Maxence Bernard
*
* muCommander 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.
*
* muCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.text;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mucommander.commons.file.util.ResourceLoader;
import com.mucommander.commons.io.bom.BOMReader;
import com.mucommander.conf.MuConfigurations;
import com.mucommander.conf.MuPreference;
/**
* This class takes care of all text localization issues by loading all text entries from a dictionary file on startup
* and translating them into the current language on demand.
*
* <p>All public methods are static to make it easy to call them throughout the application.</p>
*
* <p>See dictionary file for more information about th dictionary file format.</p>
*
* @author Maxence Bernard
*/
public class Translator {
private static final Logger LOGGER = LoggerFactory.getLogger(Translator.class);
/** Contains key/value pairs for the current language */
private static Map<String, String> dictionary;
/** Contains key/value pairs for the default language, for entries that are not defined in the current language */
private static Map<String, String> defaultDictionary;
/** List of all available languages in the dictionary file */
private static List<String> availableLanguages;
/** Current language */
private static String language;
/** Default language */
private final static String DEFAULT_LANGUAGE = "EN";
/** Key for available languages */
private final static String AVAILABLE_LANGUAGES_KEY = "available_languages";
/**
* Prevents instance creation.
*/
private Translator() {}
/**
* Determines and sets the current language based on the given list of available languages
* and the current language set in the preferences if it has been set, else on the system's language.
* <p>
* If the language set in the preferences or the system's language is not available, the default language as
* defined by {@link #DEFAULT_LANGUAGE} will be used.
* </p>
*
* @param availableLanguages list of available languages
*/
private static void setCurrentLanguage(List<String> availableLanguages) {
String lang = MuConfigurations.getPreferences().getVariable(MuPreference.LANGUAGE);
if(lang==null) {
// language is not set in preferences, use system's language
// Try to match language with the system's language, only if the system's language
// has values in dictionary, otherwise use default language (English).
lang = Locale.getDefault().getLanguage();
LOGGER.info("Language not set in preferences, trying to match system's language ("+lang+")");
}
else {
LOGGER.info("Using language set in preferences: "+lang);
}
// Determines if the list of available languages contains the language (case-insensitive)
boolean containsLanguage = false;
for (String availableLanguage : availableLanguages) {
if (availableLanguage.equalsIgnoreCase(lang)) {
containsLanguage = true;
lang = availableLanguage; // Use the proper case variation
break;
}
}
// Determines if language is one of the languages declared as available
if(containsLanguage) {
// Language is available
Translator.language = lang;
LOGGER.debug("Language "+lang+" is available.");
}
else {
// Language is not available, fall back to default language (English)
Translator.language = DEFAULT_LANGUAGE;
LOGGER.debug("Language "+lang+" is not available, falling back to default language "+DEFAULT_LANGUAGE);
}
// Set preferred language in configuration file
MuConfigurations.getPreferences().setVariable(MuPreference.LANGUAGE, Translator.language);
LOGGER.debug("Current language has been set to "+Translator.language);
}
/**
* Loads the default dictionary file.
*
* @throws IOException thrown if an IO error occurs.
*/
public static void loadDictionaryFile() throws IOException {
loadDictionaryFile(com.mucommander.RuntimeConstants.DICTIONARY_FILE);
}
/**
* Loads the specified dictionary file, which contains localized text entries.
*
* @param filePath path to the dictionary file
* @throws IOException thrown if an IO error occurs.
*/
public static void loadDictionaryFile(String filePath) throws IOException {
availableLanguages = new ArrayList<>();
dictionary = new HashMap<>();
defaultDictionary = new HashMap<>();
BufferedReader br = new BufferedReader(new BOMReader(ResourceLoader.getResourceAsStream(filePath)));
String line;
String keyLC;
String lang;
String text;
StringTokenizer st;
while((line = br.readLine())!=null) {
if (!line.trim().startsWith("#") && !line.trim().equals("")) {
st = new StringTokenizer(line);
try {
// Sets delimiter to ':'
keyLC = st.nextToken(":").trim().toLowerCase();
// Special key that lists available languages, must
// be defined before any other entry
if(Translator.language==null && keyLC.equals(AVAILABLE_LANGUAGES_KEY)) {
// Parse comma separated languages
st = new StringTokenizer(st.nextToken(), ",\n");
while(st.hasMoreTokens())
availableLanguages.add(st.nextToken().trim());
LOGGER.debug("Available languages= "+availableLanguages);
// Determines current language based on available languages and preferred language (if set) or system's language
setCurrentLanguage(availableLanguages);
continue;
}
lang = st.nextToken().trim();
// Delimiter is now line break
text = st.nextToken("\n");
text = text.substring(1, text.length());
// Replace "\n" strings in the text by \n characters
int pos = 0;
while ((pos = text.indexOf("\\n", pos))!=-1)
text = text.substring(0, pos)+"\n"+text.substring(pos+2, text.length());
// Replace "\\uxxxx" unicode strings by the designated character
pos = 0;
while ((pos = text.indexOf("\\u", pos))!=-1)
text = text.substring(0, pos)+(char)(Integer.parseInt(text.substring(pos+2, pos+6), 16))+text.substring(pos+6, text.length());
// Add entry for current language, or for default language if a value for current language wasn't already set
if(lang.equalsIgnoreCase(language)) {
dictionary.put(keyLC, text);
// Remove the default dictionary entry as it will not be used (saves some memory).
defaultDictionary.remove(keyLC);
}
else if(lang.equalsIgnoreCase(DEFAULT_LANGUAGE) && dictionary.get(keyLC)==null) {
defaultDictionary.put(keyLC, text);
}
}
catch(Exception e) {
LOGGER.info("error in line " + line + " (" + e + ")");
throw new IOException("Syntax error in line " + line);
}
}
}
br.close();
}
/**
* Returns the current language as a language code ("EN", "FR", "pt_BR", ...).
*
* @return lang a language code
*/
public static String getLanguage() {
return language;
}
/**
* Returns an array of available languages, expressed as language codes ("EN", "FR", "pt_BR"...).
* The returned array is sorted by language codes in case insensitive order.
*
* @return an array of language codes.
*/
public static String[] getAvailableLanguages() {
String[] languages = availableLanguages.toArray(new String[availableLanguages.size()]);
Arrays.sort(languages, String.CASE_INSENSITIVE_ORDER);
return languages;
}
/**
* Returns <code>true</code> if the given entry's key has a value in the current language.
* If the <code>useDefaultLanguage</code> parameter is <code>true</code>, entries that have no value in the
* {@link #getLanguage() current language} but one in the {@link #DEFAULT_LANGUAGE} will be considered as having
* a value (<code>true</code> will be returned).
*
* @param key key of the requested dictionary entry (case-insensitive)
* @param useDefaultLanguage if <code>true</code>, entries that have no value in the {@link #getLanguage() current
* language} but one in the {@link #DEFAULT_LANGUAGE} will be considered as having a value
* @return <code>true</code> if the given key has a corresponding value in the current language.
*/
public static boolean hasValue(String key, boolean useDefaultLanguage) {
return dictionary.get(key.toLowerCase())!=null
|| (useDefaultLanguage && defaultDictionary.get(key.toLowerCase())!=null);
}
/**
* Returns the localized text String for the given key expressd in the current language, or in the default language
* if there is no value for the current language. Entry parameters (%1, %2, ...), if any, are replaced by the
* specified values.
*
* @param key key of the requested dictionary entry (case-insensitive)
* @param paramValues array of parameters which will be used as values for variables.
* @return the localized text String for the given key expressed in the current language
*/
public static String get(String key, String... paramValues) {
// Returns the localized text
String text = dictionary.get(key.toLowerCase());
if (text == null) {
text = defaultDictionary.get(key.toLowerCase());
if (text == null) {
LOGGER.debug("No value for "+key+", returning key");
return key;
} else {
LOGGER.debug("No value for "+key+" in language "+language+", using "+DEFAULT_LANGUAGE+" value");
// Don't return yet, parameters need to be replaced
}
}
// Replace %1, %2 ... parameters by their value
if (paramValues != null) {
int pos = -1;
for(int i=0; i<paramValues.length; i++) {
while(++pos<text.length()-1 && (pos = text.indexOf("%"+(i+1), pos))!=-1)
text = text.substring(0, pos)+paramValues[i]+text.substring(pos+2, text.length());
}
}
// Replace $[key] occurrences by their value
int pos = 0;
while ((pos = text.indexOf("$[", pos)) >= 0) {
int pos2 = text.indexOf("]", pos+1);
String variable = text.substring(pos+2, pos2);
text = text.substring(0, pos) + get(variable, paramValues)+text.substring(pos2+1, text.length());
}
return text;
}
/**
* Based on the number of supplied command line parameters, this method either :
* <ul>
* <li>Looks for and reports any missing or unused dictionary entry,
* using the supplied source folder path to look inside source files
* for references to dictionary entries.
* <li>Merges a new language's entries from a dictionary file into a new one.
* </ul>
*/
public static void main(String args[]) throws IOException {
/*
// Looks for missing and unused entries
if(args.length<4) {
Enumeration languages = dictionaries.keys();
Vector langsV = new Vector();
while(languages.hasMoreElements())
langsV.add(languages.nextElement());
String langs[] = new String[langsV.size()];
langsV.toArray(langs);
com.mucommander.commons.file.AbstractFile sourceFolder = com.mucommander.commons.file.AbstractFile.getFile(args[0]);
System.out.println("\n##### Looking for missing entries #####");
checkMissingEntries(sourceFolder, langs);
System.out.println("\n##### Looking for unused entries #####");
checkUnusedEntries(sourceFolder, langs);
}
// Integrates a new language into the dictionary
else {
*/
// Parameters order: originalFile newLanguageFile resultingFile newLanguage
if(args.length<4) {
System.out.println("usage: Translator originalFile newLanguageFile mergedFile newLanguage");
return;
}
addLanguageToDictionary(args[0], args[1], args[2], args[3]);
/*
}
*/
}
/**
* Checks for missing dictionary entries in the given file or folder and reports them on the standard output.
* If the given file is a folder, recurse on each file that it contains, if it's a 'regular' file and the
* extension is '.java', looks for any calls to {@link #Translator.get(String), Translator.get()} and checks
* that the request entry has a value in each language's dictionary.
*/
/*
private static void checkMissingEntries(com.mucommander.commons.file.AbstractFile file, String languages[]) throws IOException {
if(file.isDirectory()) {
com.mucommander.commons.file.AbstractFile children[] = file.ls();
for(int i=0; i<children.length; i++)
checkMissingEntries(children[i], languages);
}
else if(file.getName().endsWith(".java")) {
BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line;
int pos;
String entry;
String value;
String language;
while((line=br.readLine())!=null) {
if(!line.trim().startsWith("//") && (pos=line.indexOf("Translator.get(\""))!=-1) {
try {
entry = line.substring(pos+16, line.indexOf("\"", pos+16));
for(int i=0; i<languages.length; i++) {
language = languages[i];
if((String)((Hashtable)dictionaries.get(language)).get(entry)!=null || (!language.equalsIgnoreCase("en") && (value=(String)((Hashtable)dictionaries.get("en")).get(entry))!=null && value.startsWith("$")))
continue;
System.out.println("Missing "+language.toUpperCase()+" entry '"+entry+"' in "+file.getAbsolutePath());
}
}
catch(Exception e) {
}
}
}
br.close();
}
}
*/
/**
* Checks all enties in all dictionaries, checks that they are used in at least one source file
* in or under the supplied folder, and reports unused entries on the standard output.
*/
/*
private static void checkUnusedEntries(com.mucommander.commons.file.AbstractFile sourceFolder, String languages[]) throws IOException {
Enumeration entries;
String entry;
for(int i=0; i<languages.length; i++) {
entries = ((Hashtable)dictionaries.get(languages[i])).keys();
while(entries.hasMoreElements()) {
entry = (String)entries.nextElement();
if(!isEntryUsed(entry, sourceFolder))
System.out.println("Unused "+languages[i].toUpperCase()+" entry "+entry);
}
}
}
*/
/**
* Checks if the given entry is used in the supplied file or folder.
*/
/*
private static boolean isEntryUsed(String entry, com.mucommander.commons.file.AbstractFile file) throws IOException {
if(file.isDirectory()) {
com.mucommander.commons.file.AbstractFile children[] = file.ls();
for(int i=0; i<children.length; i++)
if(isEntryUsed(entry, children[i]))
return true;
return false;
}
else if(file.getName().endsWith(".java")) {
BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line;
int pos;
while((line=br.readLine())!=null) {
if(!line.trim().startsWith("//") && (pos=line.indexOf("\""+entry+"\""))!=-1) {
br.close();
return true;
}
}
br.close();
return false;
}
return false;
}
*/
/**
* Merges a dictionary file with another one, adding entries of the specified new language.
* <p>This method is used to merge dictionary files sent by contributors.
*
* @param originalFile current version of the dictionary file
* @param newLanguageFile dictionary file containing new language entries
* @param resultingFile merged dictionary file
* @param newLanguage new language
* @throws IOException if an I/O error occurred
*/
private static void addLanguageToDictionary(String originalFile, String newLanguageFile, String resultingFile, String newLanguage) throws IOException {
// Initialize streams
BufferedReader originalFileReader = new BufferedReader(new BOMReader(new FileInputStream(originalFile)));
BufferedReader newLanguageFileReader = new BufferedReader(new BOMReader(new FileInputStream(newLanguageFile)));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(resultingFile), "UTF-8"));
// Parse new language's entries
String line;
int lineNum = 0;
String key;
String lang;
String text;
StringTokenizer st;
Map<String, String> newLanguageEntries = new HashMap<>();
while ((line = newLanguageFileReader.readLine())!=null) {
try {
if (!line.trim().startsWith("#") && !line.trim().equals("")) {
st = new StringTokenizer(line);
// Sets delimiter to ':'
key = st.nextToken(":");
lang = st.nextToken();
if(lang.equalsIgnoreCase(newLanguage)) {
// Delimiter is now line break
text = st.nextToken("\n");
text = text.substring(1, text.length());
newLanguageEntries.put(key, text);
}
}
lineNum++;
}
catch(Exception e) {
LOGGER.warn("caught "+e+" at line "+lineNum);
return;
}
}
// Insert new language entries in resulting file
boolean keyProcessedForNewLanguage = false;
String currentKey = null;
while ((line = originalFileReader.readLine())!=null) {
boolean emptyLine = line.trim().startsWith("#") || line.trim().equals("");
if (!keyProcessedForNewLanguage && (emptyLine || (currentKey!=null && !line.startsWith(currentKey+":")))) {
if(currentKey!=null) {
String newLanguageValue = newLanguageEntries.get(currentKey);
if(newLanguageValue!=null) {
// Insert new language's entry in resulting file
LOGGER.info("New language entry for key="+currentKey+" value="+newLanguageValue);
pw.println(currentKey+":"+newLanguage+":"+newLanguageValue);
}
keyProcessedForNewLanguage = true;
}
}
if(!emptyLine) {
// Parse entry
st = new StringTokenizer(line);
// Set delimiter to ':'
key = st.nextToken(":");
lang = st.nextToken();
if(!key.equals(currentKey)) {
currentKey = key;
keyProcessedForNewLanguage = false;
}
if(lang.equalsIgnoreCase(newLanguage)) {
// Delimiter is now line break
String existingNewLanguageValue = st.nextToken("\n");
existingNewLanguageValue = existingNewLanguageValue.substring(1, existingNewLanguageValue.length());
String newLanguageValue = newLanguageEntries.get(currentKey);
if(newLanguageValue!=null) {
if(!existingNewLanguageValue.equals(newLanguageValue))
LOGGER.warn("Warning: found an updated value for key="+currentKey+", using new value="+newLanguageValue+" existing value="+existingNewLanguageValue);
pw.println(currentKey+":"+newLanguage+":"+newLanguageValue);
}
else {
LOGGER.warn("Existing dictionary has a value for key="+currentKey+" that is missing in the new dictionary file, using existing value= "+existingNewLanguageValue);
pw.println(currentKey+":"+newLanguage+":"+existingNewLanguageValue);
}
keyProcessedForNewLanguage = true;
}
else {
pw.println(line);
}
}
else {
pw.println(line);
}
}
newLanguageFileReader.close();
originalFileReader.close();
pw.close();
}
}
| gpl-3.0 |
CodeCranachan/Asteroid-Push | src/main/java/org/codecranachan/asteroidpush/content/actors/ScenarioBorderFactory.java | 4625 | // Asteroid Push - A game featuring selfmade spaceships and pompous physics
// Copyright (C) 2013 Christian Meyer, Silvan Wegmann
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package org.codecranachan.asteroidpush.content.actors;
import java.util.Collection;
import java.util.LinkedList;
import org.codecranachan.asteroidpush.base.simulation.Actor;
import org.codecranachan.asteroidpush.base.simulation.ActorFactory;
import org.codecranachan.asteroidpush.base.simulation.Hull;
import org.codecranachan.asteroidpush.base.simulation.Material;
import org.codecranachan.asteroidpush.base.simulation.Primitive;
import org.codecranachan.asteroidpush.base.simulation.RigidBody;
import org.codecranachan.asteroidpush.base.simulation.RigidBodyFactory;
import org.codecranachan.asteroidpush.base.visuals.BodyTrackingOffsetRepresentation;
import org.codecranachan.asteroidpush.base.visuals.Representation;
import org.codecranachan.asteroidpush.content.visuals.BorderRepresentation;
import org.codecranachan.asteroidpush.utils.Arrow;
import org.codecranachan.asteroidpush.utils.NewtonianState;
import org.jbox2d.common.Vec2;
public class ScenarioBorderFactory implements ActorFactory {
final private float borderThickness = 10.0f;
private float fieldHeight;
private float fieldWidth;
private RigidBodyFactory bodyFactory;
public ScenarioBorderFactory(float fieldWidth, float fieldHeight) {
this.fieldWidth = fieldWidth;
this.fieldHeight = fieldHeight;
bodyFactory = null;
}
public void setBodyFactory(RigidBodyFactory factory) {
bodyFactory = factory;
}
public Actor createActor(NewtonianState initialState) {
RigidBody body = bodyFactory.createStaticBody(initialState);
for (Primitive primitive : getPrimitives()) {
Hull hull = new Hull(new Arrow(), primitive, Material.METAL);
body.addHull(hull, null);
}
Representation border = new BorderRepresentation(fieldWidth, fieldHeight);
Representation rep = new BodyTrackingOffsetRepresentation(border, body);
return new PassiveObject(body, rep);
}
private Collection<Primitive> getPrimitives() {
Collection<Primitive> primitives = new LinkedList<Primitive>();
Vec2 border = new Vec2(borderThickness, borderThickness);
Vec2 innerDiagonal = new Vec2(fieldWidth / 2.0f, fieldHeight / 2.0f);
Vec2 outerDiagonal = innerDiagonal.add(border);
Primitive newPrimitive;
newPrimitive = new Primitive();
newPrimitive.AddVertex(new Vec2(innerDiagonal.x, innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(innerDiagonal.x, -innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(outerDiagonal.x, -innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(outerDiagonal.x, innerDiagonal.y));
primitives.add(newPrimitive);
newPrimitive = new Primitive();
newPrimitive.AddVertex(new Vec2(-innerDiagonal.x, innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(-outerDiagonal.x, innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(-outerDiagonal.x, -innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(-innerDiagonal.x, -innerDiagonal.y));
primitives.add(newPrimitive);
newPrimitive = new Primitive();
newPrimitive.AddVertex(new Vec2(outerDiagonal.x, outerDiagonal.y));
newPrimitive.AddVertex(new Vec2(-outerDiagonal.x, outerDiagonal.y));
newPrimitive.AddVertex(new Vec2(-outerDiagonal.x, innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(outerDiagonal.x, innerDiagonal.y));
primitives.add(newPrimitive);
newPrimitive = new Primitive();
newPrimitive.AddVertex(new Vec2(outerDiagonal.x, -innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(-outerDiagonal.x, -innerDiagonal.y));
newPrimitive.AddVertex(new Vec2(-outerDiagonal.x, -outerDiagonal.y));
newPrimitive.AddVertex(new Vec2(outerDiagonal.x, -outerDiagonal.y));
primitives.add(newPrimitive);
return primitives;
}
}
| gpl-3.0 |
0xnm/BTC-e-client-for-Android | BTCeClient/src/main/java/com/QuarkLabs/BTCeClient/tasks/GetExchangeInfoTask.java | 1170 | package com.QuarkLabs.BTCeClient.tasks;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import com.QuarkLabs.BTCeClient.api.Api;
import com.QuarkLabs.BTCeClient.api.CallResult;
import com.QuarkLabs.BTCeClient.api.ExchangeInfo;
public class GetExchangeInfoTask extends AsyncTask<Void, Void, CallResult<ExchangeInfo>> {
@NonNull
private final Api api;
@NonNull
private final ApiResultListener<ExchangeInfo> resultListener;
public GetExchangeInfoTask(@NonNull Api api,
@NonNull ApiResultListener<ExchangeInfo> resultListener) {
this.api = api;
this.resultListener = resultListener;
}
@Override
protected CallResult<ExchangeInfo> doInBackground(Void... params) {
return api.getExchangeInfo();
}
@Override
protected void onPostExecute(CallResult<ExchangeInfo> result) {
if (result.isSuccess()) {
//noinspection ConstantConditions
resultListener.onSuccess(result.getPayload());
} else {
//noinspection ConstantConditions
resultListener.onError(result.getError());
}
}
}
| gpl-3.0 |
gunnarfloetteroed/java | experimental/src/main/java/stockholm/wum/malin/PersonInVehicleTracker.java | 3083 | /*
* Copyright 2018 Gunnar Flötteröd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* contact: gunnar.flotterod@gmail.com
*
*/
package stockholm.wum.malin;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.events.PersonEntersVehicleEvent;
import org.matsim.api.core.v01.events.PersonLeavesVehicleEvent;
import org.matsim.api.core.v01.events.handler.PersonEntersVehicleEventHandler;
import org.matsim.api.core.v01.events.handler.PersonLeavesVehicleEventHandler;
import org.matsim.api.core.v01.population.Person;
import org.matsim.vehicles.Vehicle;
/**
* Keeps track of when every single passenger enters which transit vehicle.
*
* @author Gunnar Flötteröd
*
*/
class PersonVehicleTracker implements PersonEntersVehicleEventHandler, PersonLeavesVehicleEventHandler {
// -------------------- MEMBERS --------------------
private final Predicate<Id<Person>> personChecker;
private final Predicate<Id<Vehicle>> vehicleChecker;
private final Map<Id<Vehicle>, Set<Id<Person>>> vehicleId2personIds = new LinkedHashMap<>();
// -------------------- CONSTRUCTION --------------------
PersonVehicleTracker(final Predicate<Id<Person>> personChecker, final Predicate<Id<Vehicle>> vehicleChecker) {
this.personChecker = personChecker;
this.vehicleChecker = vehicleChecker;
}
// -------------------- IMPLEMENTATION OF *EventHandler --------------------
@Override
public void handleEvent(final PersonEntersVehicleEvent event) {
if (this.personChecker.test(event.getPersonId()) && this.vehicleChecker.test(event.getVehicleId())) {
Set<Id<Person>> personIds = this.vehicleId2personIds.get(event.getVehicleId());
if (personIds == null) {
personIds = new LinkedHashSet<>();
this.vehicleId2personIds.put(event.getVehicleId(), personIds);
}
personIds.add(event.getPersonId());
}
}
@Override
public void handleEvent(final PersonLeavesVehicleEvent event) {
if (this.personChecker.test(event.getPersonId()) && this.vehicleChecker.test(event.getVehicleId())) {
Set<Id<Person>> personIds = this.vehicleId2personIds.get(event.getVehicleId());
personIds.remove(event.getPersonId());
if (personIds.isEmpty()) {
this.vehicleId2personIds.remove(event.getVehicleId());
}
}
}
}
| gpl-3.0 |
0359xiaodong/droidplanner | Core/src/org/droidplanner/core/helpers/geoTools/PolylineTools.java | 579 | package org.droidplanner.core.helpers.geoTools;
import java.util.List;
import org.droidplanner.core.helpers.coordinates.Coord2D;
import org.droidplanner.core.helpers.units.Length;
public class PolylineTools {
/**
* Total length of the polyline in meters
*
* @param gridPoints
* @return
*/
public static Length getPolylineLength(List<Coord2D> gridPoints) {
double lenght = 0;
for (int i = 1; i < gridPoints.size(); i++) {
lenght += GeoTools.getDistance(gridPoints.get(i),
gridPoints.get(i - 1)).valueInMeters();
}
return new Length(lenght);
}
}
| gpl-3.0 |
NuenoB/OpenBlocks_UCHILE | src/openblocks/shapes/shapesgenerators/simpleShapeFactory/SimpleWallGeneratorNS.java | 535 | package openblocks.shapes.shapesgenerators.simpleShapeFactory;
import java.util.ArrayList;
import net.minecraft.block.Block;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.world.World;
import openblocks.shapes.BlockRepresentation;
import openmods.shapes.IShapeable;
public class SimpleWallGeneratorNS extends AbstractSimpleWallGenerator {
@Override
public void setBlockAux(int xSize, int ySize, int zSize, int y, int z, IShapeable shapeable) {
shapeable.setBlock(xSize, ySize + y, zSize + z - 1);
}
}
| gpl-3.0 |
marvertin/geokuk | src/main/java/cz/geokuk/plugins/kesoid/importek/InformaceOZdrojich.java | 5019 | package cz.geokuk.plugins.kesoid.importek;
import java.io.File;
import java.util.*;
import cz.geokuk.util.file.*;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class InformaceOZdrojich {
public class Builder {
/**
* Tady postupně budujeme stromy načítaných zdrojů.
*
* @param aJmenoZdroje
* @param nacteno
* @return
*/
public InformaceOZdroji add(final KeFile aJmenoZdroje, final boolean nacteno) {
// TODO : perhaps it's not needed to bother with the whole path to root...
// Maybe canonical path and longest
// common prefix will do?
Strom strom = stromy.get(aJmenoZdroje.root);
if (strom == null) {
strom = new Strom();
stromy.put(aJmenoZdroje.root, strom);
}
InformaceOZdroji ioz = strom.map.get(aJmenoZdroje);
if (ioz == null) {
ioz = new InformaceOZdroji(aJmenoZdroje, nacteno);
strom.map.put(aJmenoZdroje, ioz);
InformaceOZdroji last = ioz;
KeFile parent = aJmenoZdroje.getParent();
while (parent != null) {
InformaceOZdroji parentIoz = strom.map.get(parent);
if (parentIoz != null) {
parentIoz.addChild(last);
last.parent = parentIoz;
break;
}
parentIoz = new InformaceOZdroji(parent, false);
parentIoz.addChild(last);
last.parent = parentIoz;
strom.map.put(parent, parentIoz);
last = parentIoz;
parent = parent.getParent();
}
if (parent == null) {
strom.root = last;
}
}
return ioz;
}
/** Objekt je hotov */
public InformaceOZdrojich done() {
// našvindlený root
final File pseudoFile = new File("[gc]");
root = new InformaceOZdroji(new KeFile(new FileAndTime(pseudoFile, 0), new Root(pseudoFile, new Root.Def(0, null, null))), false);
for (final Strom strom : stromy.values()) {
root.addChild(strom.root);
strom.root.parent = root;
}
setřepáníNevětvenýchCest(root);
root.spocitejSiPocetWaipointuChildren();
print();
return InformaceOZdrojich.this;
}
private void setřepáníNevětvenýchCest(final InformaceOZdroji aIoz) {
if (aIoz.getChildren().size() == 1 && aIoz.parent != null) {
final InformaceOZdroji jedinacek = aIoz.getChildren().get(0);
aIoz.parent.remplaceChild(aIoz, jedinacek);
jedinacek.parent = aIoz.parent;
}
// po sesypání nebo bez sesypání, děti sesypeme
for (final InformaceOZdroji ioz : aIoz.getChildren()) {
setřepáníNevětvenýchCest(ioz); // pro 0 se nedělá nic a pro více než 1 se nesetřepává
}
}
}
private static class Strom {
InformaceOZdroji root;
Map<KeFile, InformaceOZdroji> map = new LinkedHashMap<>();
}
private final Map<Root, Strom> stromy = new LinkedHashMap<>();
private InformaceOZdroji root;
public static Builder builder() {
return new InformaceOZdrojich().new Builder();
}
private InformaceOZdrojich() {}
public InformaceOZdroji get(final KeFile key) {
final InformaceOZdroji informaceOZdroji = stromy.get(key.root).map.get(key);
return informaceOZdroji;
}
public Set<File> getJmenaZdroju() {
final Set<File> files = new LinkedHashSet<>();
for (final KeFile kefile : getKeJmenaZdroju()) {
files.add(kefile.getFile());
}
return files;
}
public Set<KeFile> getKeJmenaZdroju() {
final Set<KeFile> files = new LinkedHashSet<>();
for (final Strom strom : stromy.values()) {
files.addAll(strom.map.keySet());
}
return files;
}
public InformaceOZdroji getRoot() {
return root;
}
public Set<InformaceOZdroji> getSetInformaciOZdrojich() {
final Set<InformaceOZdroji> infas = new LinkedHashSet<>();
for (final Strom strom : stromy.values()) {
infas.addAll(strom.map.values());
}
return infas;
}
public int getSourceCount(final boolean loaded) {
int loadedCount = 0;
int notLoadedCount = 0;
for (final InformaceOZdroji ioz : getSetInformaciOZdrojich()) {
if (ioz.getChildren().isEmpty()) {
if (ioz.nacteno) {
++loadedCount;
} else {
++notLoadedCount;
}
}
}
return loaded ? loadedCount : notLoadedCount;
}
public Collection<InformaceOZdroji> getSubtree(final KeFile subTreeRoot) {
final List<InformaceOZdroji> toReturn = new ArrayList<>();
return getSubtree(get(subTreeRoot), toReturn);
}
public long getYungest() {
long x = 0;
for (final InformaceOZdroji info : getSetInformaciOZdrojich()) {
if (info.nacteno) {
x = Math.max(x, info.getLastModified());
}
}
log.info("Spocitano nejmladsi datum: {}", x);
return x;
}
public void print() {
if (log.isDebugEnabled()) {
System.out.println("================= prin strom - START");
root.print(":: ", null);
System.out.println("================= prin strom - END");
}
}
private Collection<InformaceOZdroji> getSubtree(final InformaceOZdroji subTreeRoot, final Collection<InformaceOZdroji> buffer) {
final List<InformaceOZdroji> children = subTreeRoot.getChildren();
buffer.add(subTreeRoot);
for (final InformaceOZdroji child : children) {
getSubtree(child, buffer);
}
return buffer;
}
} | gpl-3.0 |
onedanshow/Screen-Courter | lib/src/org/apache/http/impl/conn/AbstractClientConnAdapter.java | 11703 | /*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.conn;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSession;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.ManagedClientConnection;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.protocol.HttpContext;
/**
* Abstract adapter from {@link OperatedClientConnection operated} to
* {@link ManagedClientConnection managed} client connections.
* Read and write methods are delegated to the wrapped connection.
* Operations affecting the connection state have to be implemented
* by derived classes. Operations for querying the connection state
* are delegated to the wrapped connection if there is one, or
* return a default value if there is none.
* <p>
* This adapter tracks the checkpoints for reusable communication states,
* as indicated by {@link #markReusable markReusable} and queried by
* {@link #isMarkedReusable isMarkedReusable}.
* All send and receive operations will automatically clear the mark.
* <p>
* Connection release calls are delegated to the connection manager,
* if there is one. {@link #abortConnection abortConnection} will
* clear the reusability mark first. The connection manager is
* expected to tolerate multiple calls to the release method.
*
* @since 4.0
*/
public abstract class AbstractClientConnAdapter
implements ManagedClientConnection, HttpContext {
/**
* The connection manager, if any.
* This attribute MUST NOT be final, so the adapter can be detached
* from the connection manager without keeping a hard reference there.
*/
private volatile ClientConnectionManager connManager;
/** The wrapped connection. */
private volatile OperatedClientConnection wrappedConnection;
/** The reusability marker. */
private volatile boolean markedReusable;
/** True if the connection has been shut down or released. */
private volatile boolean released;
/** The duration this is valid for while idle (in ms). */
private volatile long duration;
/**
* Creates a new connection adapter.
* The adapter is initially <i>not</i>
* {@link #isMarkedReusable marked} as reusable.
*
* @param mgr the connection manager, or <code>null</code>
* @param conn the connection to wrap, or <code>null</code>
*/
protected AbstractClientConnAdapter(ClientConnectionManager mgr,
OperatedClientConnection conn) {
super();
connManager = mgr;
wrappedConnection = conn;
markedReusable = false;
released = false;
duration = Long.MAX_VALUE;
}
/**
* Detaches this adapter from the wrapped connection.
* This adapter becomes useless.
*/
protected synchronized void detach() {
wrappedConnection = null;
connManager = null; // base class attribute
duration = Long.MAX_VALUE;
}
protected OperatedClientConnection getWrappedConnection() {
return wrappedConnection;
}
protected ClientConnectionManager getManager() {
return connManager;
}
/**
* @deprecated use {@link #assertValid(OperatedClientConnection)}
*/
@Deprecated
protected final void assertNotAborted() throws InterruptedIOException {
if (isReleased()) {
throw new InterruptedIOException("Connection has been shut down");
}
}
/**
* @since 4.1
* @return value of released flag
*/
protected boolean isReleased() {
return released;
}
/**
* Asserts that there is a valid wrapped connection to delegate to.
*
* @throws ConnectionShutdownException if there is no wrapped connection
* or connection has been aborted
*/
protected final void assertValid(
final OperatedClientConnection wrappedConn) throws ConnectionShutdownException {
if (isReleased() || wrappedConn == null) {
throw new ConnectionShutdownException();
}
}
public boolean isOpen() {
OperatedClientConnection conn = getWrappedConnection();
if (conn == null)
return false;
return conn.isOpen();
}
public boolean isStale() {
if (isReleased())
return true;
OperatedClientConnection conn = getWrappedConnection();
if (conn == null)
return true;
return conn.isStale();
}
public void setSocketTimeout(int timeout) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
conn.setSocketTimeout(timeout);
}
public int getSocketTimeout() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getSocketTimeout();
}
public HttpConnectionMetrics getMetrics() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getMetrics();
}
public void flush() throws IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
conn.flush();
}
public boolean isResponseAvailable(int timeout) throws IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.isResponseAvailable(timeout);
}
public void receiveResponseEntity(HttpResponse response)
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
conn.receiveResponseEntity(response);
}
public HttpResponse receiveResponseHeader()
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
return conn.receiveResponseHeader();
}
public void sendRequestEntity(HttpEntityEnclosingRequest request)
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
conn.sendRequestEntity(request);
}
public void sendRequestHeader(HttpRequest request)
throws HttpException, IOException {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
unmarkReusable();
conn.sendRequestHeader(request);
}
public InetAddress getLocalAddress() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getLocalAddress();
}
public int getLocalPort() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getLocalPort();
}
public InetAddress getRemoteAddress() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getRemoteAddress();
}
public int getRemotePort() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.getRemotePort();
}
public boolean isSecure() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
return conn.isSecure();
}
public SSLSession getSSLSession() {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (!isOpen())
return null;
SSLSession result = null;
Socket sock = conn.getSocket();
if (sock instanceof SSLSocket) {
result = ((SSLSocket)sock).getSession();
}
return result;
}
public void markReusable() {
markedReusable = true;
}
public void unmarkReusable() {
markedReusable = false;
}
public boolean isMarkedReusable() {
return markedReusable;
}
public void setIdleDuration(long duration, TimeUnit unit) {
if(duration > 0) {
this.duration = unit.toMillis(duration);
} else {
this.duration = -1;
}
}
public synchronized void releaseConnection() {
if (released) {
return;
}
released = true;
if (connManager != null) {
connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS);
}
}
public synchronized void abortConnection() {
if (released) {
return;
}
released = true;
unmarkReusable();
try {
shutdown();
} catch (IOException ignore) {
}
if (connManager != null) {
connManager.releaseConnection(this, duration, TimeUnit.MILLISECONDS);
}
}
public synchronized Object getAttribute(final String id) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (conn instanceof HttpContext) {
return ((HttpContext) conn).getAttribute(id);
} else {
return null;
}
}
public synchronized Object removeAttribute(final String id) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (conn instanceof HttpContext) {
return ((HttpContext) conn).removeAttribute(id);
} else {
return null;
}
}
public synchronized void setAttribute(final String id, final Object obj) {
OperatedClientConnection conn = getWrappedConnection();
assertValid(conn);
if (conn instanceof HttpContext) {
((HttpContext) conn).setAttribute(id, obj);
}
}
}
| gpl-3.0 |
geocollections/kivid.info | src/main/java/info/kivid/controller/RockController.java | 2372 | package info.kivid.controller;
import info.kivid.model.*;
import info.kivid.service.RockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@Controller
public class RockController {
@Autowired
private RockService rockService;
@RequestMapping(value = "/rock/{id}", method = RequestMethod.GET)
public String getRock(@PathVariable("id") String id, Model model) {
RockApiResult rockApiResult = rockService.getRock(id);
if (rockApiResult != null) {
model.addAttribute("rock", rockApiResult);
RockCarousellContainer imagesContainers = new RockCarousellContainer(rockService.getRockGallery(id),4);
model.addAttribute("images", imagesContainers.getContainers());
List<PropertyApiResult> props = rockService.getRockProperties(id);
model.addAttribute("properties", props);
List<TreeApiResult> tree = rockService.getRockTree(id);
model.addAttribute("rockTree", tree);
return "rock";
}
return "rock_error";
}
@RequestMapping(value = "/rock/{id}/gallery", method = RequestMethod.GET)
public String getRockGallery(@PathVariable("id") String id, Model model) {
List<ImageApiResult> images = rockService.getRockGallery(id);
if (images != null) {
model.addAttribute("images", images);
model.addAttribute("rockId", id);
return "rock_gallery";
}
return "rock_error";
}
@RequestMapping(value = "/rock/{id}/map", method = RequestMethod.GET)
public String getRockMap(@PathVariable("id") String id, Model model) {
model.addAttribute("rockId", id);
return "rock_map";
}
@RequestMapping(value = "/rock/{id}/tree", method = RequestMethod.GET)
public String getRockTree(@PathVariable("id") String id, Model model) {
List<TreeApiResult> tree = rockService.getRockTree(id);
model.addAttribute("rockTree", tree);
model.addAttribute("rockId", id);
return "rock_tree";
}
}
| gpl-3.0 |
AsamK/signal-cli | lib/src/main/java/org/asamk/signal/manager/helper/GroupV2Helper.java | 25184 | package org.asamk.signal.manager.helper;
import com.google.protobuf.InvalidProtocolBufferException;
import org.asamk.signal.manager.SignalDependencies;
import org.asamk.signal.manager.api.Pair;
import org.asamk.signal.manager.groups.GroupLinkPassword;
import org.asamk.signal.manager.groups.GroupLinkState;
import org.asamk.signal.manager.groups.GroupPermission;
import org.asamk.signal.manager.groups.GroupUtils;
import org.asamk.signal.manager.groups.NotAGroupMemberException;
import org.asamk.signal.manager.storage.groups.GroupInfoV2;
import org.asamk.signal.manager.storage.recipients.Profile;
import org.asamk.signal.manager.storage.recipients.RecipientId;
import org.asamk.signal.manager.util.IOUtils;
import org.asamk.signal.manager.util.Utils;
import org.signal.storageservice.protos.groups.AccessControl;
import org.signal.storageservice.protos.groups.GroupChange;
import org.signal.storageservice.protos.groups.Member;
import org.signal.storageservice.protos.groups.local.DecryptedGroup;
import org.signal.storageservice.protos.groups.local.DecryptedGroupChange;
import org.signal.storageservice.protos.groups.local.DecryptedGroupJoinInfo;
import org.signal.storageservice.protos.groups.local.DecryptedPendingMember;
import org.signal.zkgroup.InvalidInputException;
import org.signal.zkgroup.VerificationFailedException;
import org.signal.zkgroup.auth.AuthCredentialResponse;
import org.signal.zkgroup.groups.GroupMasterKey;
import org.signal.zkgroup.groups.GroupSecretParams;
import org.signal.zkgroup.groups.UuidCiphertext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.groupsv2.DecryptedGroupUtil;
import org.whispersystems.signalservice.api.groupsv2.GroupCandidate;
import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
import org.whispersystems.signalservice.api.groupsv2.GroupsV2AuthorizationString;
import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
import org.whispersystems.signalservice.api.groupsv2.InvalidGroupStateException;
import org.whispersystems.signalservice.api.groupsv2.NotAbleToApplyGroupV2ChangeException;
import org.whispersystems.signalservice.api.push.ACI;
import org.whispersystems.signalservice.api.push.ServiceId;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
class GroupV2Helper {
private final static Logger logger = LoggerFactory.getLogger(GroupV2Helper.class);
private final SignalDependencies dependencies;
private final Context context;
private HashMap<Integer, AuthCredentialResponse> groupApiCredentials;
GroupV2Helper(final Context context) {
this.dependencies = context.getDependencies();
this.context = context;
}
DecryptedGroup getDecryptedGroup(final GroupSecretParams groupSecretParams) throws NotAGroupMemberException {
try {
final var groupsV2AuthorizationString = getGroupAuthForToday(groupSecretParams);
return dependencies.getGroupsV2Api().getGroup(groupSecretParams, groupsV2AuthorizationString);
} catch (NonSuccessfulResponseCodeException e) {
if (e.getCode() == 403) {
throw new NotAGroupMemberException(GroupUtils.getGroupIdV2(groupSecretParams), null);
}
logger.warn("Failed to retrieve Group V2 info, ignoring: {}", e.getMessage());
return null;
} catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
logger.warn("Failed to retrieve Group V2 info, ignoring: {}", e.getMessage());
return null;
}
}
DecryptedGroupJoinInfo getDecryptedGroupJoinInfo(
GroupMasterKey groupMasterKey, GroupLinkPassword password
) throws IOException, GroupLinkNotActiveException {
var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
return dependencies.getGroupsV2Api()
.getGroupJoinInfo(groupSecretParams,
Optional.fromNullable(password).transform(GroupLinkPassword::serialize),
getGroupAuthForToday(groupSecretParams));
}
Pair<GroupInfoV2, DecryptedGroup> createGroup(
String name, Set<RecipientId> members, File avatarFile
) throws IOException {
final var avatarBytes = readAvatarBytes(avatarFile);
final var newGroup = buildNewGroup(name, members, avatarBytes);
if (newGroup == null) {
return null;
}
final var groupSecretParams = newGroup.getGroupSecretParams();
final GroupsV2AuthorizationString groupAuthForToday;
final DecryptedGroup decryptedGroup;
try {
groupAuthForToday = getGroupAuthForToday(groupSecretParams);
dependencies.getGroupsV2Api().putNewGroup(newGroup, groupAuthForToday);
decryptedGroup = dependencies.getGroupsV2Api().getGroup(groupSecretParams, groupAuthForToday);
} catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
logger.warn("Failed to create V2 group: {}", e.getMessage());
return null;
}
if (decryptedGroup == null) {
logger.warn("Failed to create V2 group, unknown error!");
return null;
}
final var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
final var masterKey = groupSecretParams.getMasterKey();
var g = new GroupInfoV2(groupId, masterKey);
return new Pair<>(g, decryptedGroup);
}
private byte[] readAvatarBytes(final File avatarFile) throws IOException {
final byte[] avatarBytes;
try (InputStream avatar = avatarFile == null ? null : new FileInputStream(avatarFile)) {
avatarBytes = avatar == null ? null : IOUtils.readFully(avatar);
}
return avatarBytes;
}
private GroupsV2Operations.NewGroup buildNewGroup(
String name, Set<RecipientId> members, byte[] avatar
) {
final var profileKeyCredential = context.getProfileHelper()
.getRecipientProfileKeyCredential(context.getAccount().getSelfRecipientId());
if (profileKeyCredential == null) {
logger.warn("Cannot create a V2 group as self does not have a versioned profile");
return null;
}
if (!areMembersValid(members)) return null;
final var self = new GroupCandidate(getSelfAci().uuid(), Optional.fromNullable(profileKeyCredential));
final var memberList = new ArrayList<>(members);
final var credentials = context.getProfileHelper().getRecipientProfileKeyCredential(memberList).stream();
final var uuids = memberList.stream()
.map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid());
var candidates = Utils.zip(uuids,
credentials,
(uuid, credential) -> new GroupCandidate(uuid, Optional.fromNullable(credential)))
.collect(Collectors.toSet());
final var groupSecretParams = GroupSecretParams.generate();
return dependencies.getGroupsV2Operations()
.createNewGroup(groupSecretParams,
name,
Optional.fromNullable(avatar),
self,
candidates,
Member.Role.DEFAULT,
0);
}
private boolean areMembersValid(final Set<RecipientId> members) {
final var noGv2Capability = context.getProfileHelper()
.getRecipientProfile(new ArrayList<>(members))
.stream()
.filter(profile -> profile != null && !profile.getCapabilities().contains(Profile.Capability.gv2))
.collect(Collectors.toSet());
if (noGv2Capability.size() > 0) {
logger.warn("Cannot create a V2 group as some members don't support Groups V2: {}",
noGv2Capability.stream().map(Profile::getDisplayName).collect(Collectors.joining(", ")));
return false;
}
return true;
}
Pair<DecryptedGroup, GroupChange> updateGroup(
GroupInfoV2 groupInfoV2, String name, String description, File avatarFile
) throws IOException {
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
var groupOperations = dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
var change = name != null ? groupOperations.createModifyGroupTitle(name) : GroupChange.Actions.newBuilder();
if (description != null) {
change.setModifyDescription(groupOperations.createModifyGroupDescriptionAction(description));
}
if (avatarFile != null) {
final var avatarBytes = readAvatarBytes(avatarFile);
var avatarCdnKey = dependencies.getGroupsV2Api()
.uploadAvatar(avatarBytes, groupSecretParams, getGroupAuthForToday(groupSecretParams));
change.setModifyAvatar(GroupChange.Actions.ModifyAvatarAction.newBuilder().setAvatar(avatarCdnKey));
}
change.setSourceUuid(getSelfAci().toByteString());
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> addMembers(
GroupInfoV2 groupInfoV2, Set<RecipientId> newMembers
) throws IOException {
GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
if (!areMembersValid(newMembers)) {
throw new IOException("Failed to update group");
}
final var memberList = new ArrayList<>(newMembers);
final var credentials = context.getProfileHelper().getRecipientProfileKeyCredential(memberList).stream();
final var uuids = memberList.stream()
.map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid());
var candidates = Utils.zip(uuids,
credentials,
(uuid, credential) -> new GroupCandidate(uuid, Optional.fromNullable(credential)))
.collect(Collectors.toSet());
final var aci = getSelfAci();
final var change = groupOperations.createModifyGroupMembershipChange(candidates, aci.uuid());
change.setSourceUuid(getSelfAci().toByteString());
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> leaveGroup(
GroupInfoV2 groupInfoV2, Set<RecipientId> membersToMakeAdmin
) throws IOException {
var pendingMembersList = groupInfoV2.getGroup().getPendingMembersList();
final var selfAci = getSelfAci();
var selfPendingMember = DecryptedGroupUtil.findPendingByUuid(pendingMembersList, selfAci.uuid());
if (selfPendingMember.isPresent()) {
return revokeInvites(groupInfoV2, Set.of(selfPendingMember.get()));
}
final var adminUuids = membersToMakeAdmin.stream()
.map(context.getRecipientHelper()::resolveSignalServiceAddress)
.map(SignalServiceAddress::getServiceId)
.map(ServiceId::uuid)
.toList();
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
return commitChange(groupInfoV2,
groupOperations.createLeaveAndPromoteMembersToAdmin(selfAci.uuid(), adminUuids));
}
Pair<DecryptedGroup, GroupChange> removeMembers(
GroupInfoV2 groupInfoV2, Set<RecipientId> members
) throws IOException {
final var memberUuids = members.stream()
.map(context.getRecipientHelper()::resolveSignalServiceAddress)
.map(SignalServiceAddress::getServiceId)
.map(ServiceId::uuid)
.collect(Collectors.toSet());
return ejectMembers(groupInfoV2, memberUuids);
}
Pair<DecryptedGroup, GroupChange> revokeInvitedMembers(
GroupInfoV2 groupInfoV2, Set<RecipientId> members
) throws IOException {
var pendingMembersList = groupInfoV2.getGroup().getPendingMembersList();
final var memberUuids = members.stream()
.map(context.getRecipientHelper()::resolveSignalServiceAddress)
.map(SignalServiceAddress::getServiceId)
.map(ServiceId::uuid)
.map(uuid -> DecryptedGroupUtil.findPendingByUuid(pendingMembersList, uuid))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
return revokeInvites(groupInfoV2, memberUuids);
}
Pair<DecryptedGroup, GroupChange> resetGroupLinkPassword(GroupInfoV2 groupInfoV2) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var newGroupLinkPassword = GroupLinkPassword.createNew().serialize();
final var change = groupOperations.createModifyGroupLinkPasswordChange(newGroupLinkPassword);
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> setGroupLinkState(
GroupInfoV2 groupInfoV2, GroupLinkState state
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var accessRequired = toAccessControl(state);
final var requiresNewPassword = state != GroupLinkState.DISABLED && groupInfoV2.getGroup()
.getInviteLinkPassword()
.isEmpty();
final var change = requiresNewPassword ? groupOperations.createModifyGroupLinkPasswordAndRightsChange(
GroupLinkPassword.createNew().serialize(),
accessRequired) : groupOperations.createChangeJoinByLinkRights(accessRequired);
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> setEditDetailsPermission(
GroupInfoV2 groupInfoV2, GroupPermission permission
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var accessRequired = toAccessControl(permission);
final var change = groupOperations.createChangeAttributesRights(accessRequired);
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> setAddMemberPermission(
GroupInfoV2 groupInfoV2, GroupPermission permission
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var accessRequired = toAccessControl(permission);
final var change = groupOperations.createChangeMembershipRights(accessRequired);
return commitChange(groupInfoV2, change);
}
GroupChange joinGroup(
GroupMasterKey groupMasterKey,
GroupLinkPassword groupLinkPassword,
DecryptedGroupJoinInfo decryptedGroupJoinInfo
) throws IOException {
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
final var groupOperations = dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
final var selfRecipientId = context.getAccount().getSelfRecipientId();
final var profileKeyCredential = context.getProfileHelper().getRecipientProfileKeyCredential(selfRecipientId);
if (profileKeyCredential == null) {
throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
}
var requestToJoin = decryptedGroupJoinInfo.getAddFromInviteLink() == AccessControl.AccessRequired.ADMINISTRATOR;
var change = requestToJoin
? groupOperations.createGroupJoinRequest(profileKeyCredential)
: groupOperations.createGroupJoinDirect(profileKeyCredential);
change.setSourceUuid(context.getRecipientHelper()
.resolveSignalServiceAddress(selfRecipientId)
.getServiceId()
.toByteString());
return commitChange(groupSecretParams, decryptedGroupJoinInfo.getRevision(), change, groupLinkPassword);
}
Pair<DecryptedGroup, GroupChange> acceptInvite(GroupInfoV2 groupInfoV2) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var selfRecipientId = context.getAccount().getSelfRecipientId();
final var profileKeyCredential = context.getProfileHelper().getRecipientProfileKeyCredential(selfRecipientId);
if (profileKeyCredential == null) {
throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
}
final var change = groupOperations.createAcceptInviteChange(profileKeyCredential);
final var aci = context.getRecipientHelper().resolveSignalServiceAddress(selfRecipientId).getServiceId();
change.setSourceUuid(aci.toByteString());
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> setMemberAdmin(
GroupInfoV2 groupInfoV2, RecipientId recipientId, boolean admin
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var address = context.getRecipientHelper().resolveSignalServiceAddress(recipientId);
final var newRole = admin ? Member.Role.ADMINISTRATOR : Member.Role.DEFAULT;
final var change = groupOperations.createChangeMemberRole(address.getServiceId().uuid(), newRole);
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> setMessageExpirationTimer(
GroupInfoV2 groupInfoV2, int messageExpirationTimer
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var change = groupOperations.createModifyGroupTimerChange(messageExpirationTimer);
return commitChange(groupInfoV2, change);
}
Pair<DecryptedGroup, GroupChange> setIsAnnouncementGroup(
GroupInfoV2 groupInfoV2, boolean isAnnouncementGroup
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var change = groupOperations.createAnnouncementGroupChange(isAnnouncementGroup);
return commitChange(groupInfoV2, change);
}
private AccessControl.AccessRequired toAccessControl(final GroupLinkState state) {
return switch (state) {
case DISABLED -> AccessControl.AccessRequired.UNSATISFIABLE;
case ENABLED -> AccessControl.AccessRequired.ANY;
case ENABLED_WITH_APPROVAL -> AccessControl.AccessRequired.ADMINISTRATOR;
};
}
private AccessControl.AccessRequired toAccessControl(final GroupPermission permission) {
return switch (permission) {
case EVERY_MEMBER -> AccessControl.AccessRequired.MEMBER;
case ONLY_ADMINS -> AccessControl.AccessRequired.ADMINISTRATOR;
};
}
private GroupsV2Operations.GroupOperations getGroupOperations(final GroupInfoV2 groupInfoV2) {
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
return dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
}
private Pair<DecryptedGroup, GroupChange> revokeInvites(
GroupInfoV2 groupInfoV2, Set<DecryptedPendingMember> pendingMembers
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
final var uuidCipherTexts = pendingMembers.stream().map(member -> {
try {
return new UuidCiphertext(member.getUuidCipherText().toByteArray());
} catch (InvalidInputException e) {
throw new AssertionError(e);
}
}).collect(Collectors.toSet());
return commitChange(groupInfoV2, groupOperations.createRemoveInvitationChange(uuidCipherTexts));
}
private Pair<DecryptedGroup, GroupChange> ejectMembers(
GroupInfoV2 groupInfoV2, Set<UUID> uuids
) throws IOException {
final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
return commitChange(groupInfoV2, groupOperations.createRemoveMembersChange(uuids));
}
private Pair<DecryptedGroup, GroupChange> commitChange(
GroupInfoV2 groupInfoV2, GroupChange.Actions.Builder change
) throws IOException {
final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
final var groupOperations = dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
final var previousGroupState = groupInfoV2.getGroup();
final var nextRevision = previousGroupState.getRevision() + 1;
final var changeActions = change.setRevision(nextRevision).build();
final DecryptedGroupChange decryptedChange;
final DecryptedGroup decryptedGroupState;
try {
decryptedChange = groupOperations.decryptChange(changeActions, getSelfAci().uuid());
decryptedGroupState = DecryptedGroupUtil.apply(previousGroupState, decryptedChange);
} catch (VerificationFailedException | InvalidGroupStateException | NotAbleToApplyGroupV2ChangeException e) {
throw new IOException(e);
}
var signedGroupChange = dependencies.getGroupsV2Api()
.patchGroup(changeActions, getGroupAuthForToday(groupSecretParams), Optional.absent());
return new Pair<>(decryptedGroupState, signedGroupChange);
}
private GroupChange commitChange(
GroupSecretParams groupSecretParams,
int currentRevision,
GroupChange.Actions.Builder change,
GroupLinkPassword password
) throws IOException {
final var nextRevision = currentRevision + 1;
final var changeActions = change.setRevision(nextRevision).build();
return dependencies.getGroupsV2Api()
.patchGroup(changeActions,
getGroupAuthForToday(groupSecretParams),
Optional.fromNullable(password).transform(GroupLinkPassword::serialize));
}
DecryptedGroup getUpdatedDecryptedGroup(
DecryptedGroup group, byte[] signedGroupChange, GroupMasterKey groupMasterKey
) {
try {
final var decryptedGroupChange = getDecryptedGroupChange(signedGroupChange, groupMasterKey);
if (decryptedGroupChange == null) {
return null;
}
return DecryptedGroupUtil.apply(group, decryptedGroupChange);
} catch (NotAbleToApplyGroupV2ChangeException e) {
return null;
}
}
private DecryptedGroupChange getDecryptedGroupChange(byte[] signedGroupChange, GroupMasterKey groupMasterKey) {
if (signedGroupChange != null) {
var groupOperations = dependencies.getGroupsV2Operations()
.forGroup(GroupSecretParams.deriveFromMasterKey(groupMasterKey));
try {
return groupOperations.decryptChange(GroupChange.parseFrom(signedGroupChange), true).orNull();
} catch (VerificationFailedException | InvalidGroupStateException | InvalidProtocolBufferException e) {
return null;
}
}
return null;
}
private static int currentTimeDays() {
return (int) TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
}
private GroupsV2AuthorizationString getGroupAuthForToday(
final GroupSecretParams groupSecretParams
) throws IOException {
final var today = currentTimeDays();
if (groupApiCredentials == null || !groupApiCredentials.containsKey(today)) {
// Returns credentials for the next 7 days
groupApiCredentials = dependencies.getGroupsV2Api().getCredentials(today);
// TODO cache credentials on disk until they expire
}
var authCredentialResponse = groupApiCredentials.get(today);
final var aci = getSelfAci();
try {
return dependencies.getGroupsV2Api()
.getGroupsV2AuthorizationString(aci, today, groupSecretParams, authCredentialResponse);
} catch (VerificationFailedException e) {
throw new IOException(e);
}
}
private ACI getSelfAci() {
return context.getAccount().getAci();
}
}
| gpl-3.0 |
simhall/BubblBox | src/configurationHandlerUI/configurationHandlerTests.java | 452 | package configurationHandlerUI;
import static org.junit.Assert.*;
import java.util.Collection;
import org.junit.Test;
import shared.ConfigurationArtifacts.ConfigurationArtifact;
public class configurationHandlerTests {
@Test
public void sampleDataFilesExist() {
//
Collection<ConfigurationArtifact> sampleArtifacts = SampleDataLoader.getSampleData();
if(sampleArtifacts.size() <= 0)
{
fail("No sample artifacts loaded.");
}
}
}
| gpl-3.0 |
MineMaarten/Signals | src/com/minemaarten/signals/rail/network/mc/NetworkStorage.java | 2600 | package com.minemaarten.signals.rail.network.mc;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.storage.WorldSavedData;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import com.minemaarten.signals.lib.Constants;
import com.minemaarten.signals.rail.network.RailNetwork;
@EventBusSubscriber(modid = Constants.MOD_ID)
public class NetworkStorage extends WorldSavedData{
public static final String DATA_KEY = "SignalsRailNetwork";
public static World overworld;
private RailNetwork<MCPos> network;
private MCNetworkState state;
private final boolean clientSide;
public NetworkStorage(String name){
this(false, name);
}
public NetworkStorage(boolean clientSide, String name){
super(name);
this.clientSide = clientSide;
network = RailNetworkManager.getInstance(clientSide).getNetwork();
state = RailNetworkManager.getInstance(clientSide).getState();
}
@SubscribeEvent
public static void onWorldLoad(WorldEvent.Load event){
if(!event.getWorld().isRemote && event.getWorld().provider.getDimension() == 0) {
overworld = event.getWorld();
overworld.loadData(NetworkStorage.class, DATA_KEY);
}
}
public static NetworkStorage getInstance(boolean clientSide){
if(clientSide) return new NetworkStorage(clientSide, DATA_KEY);
if(overworld != null) {
NetworkStorage manager = (NetworkStorage)overworld.loadData(NetworkStorage.class, DATA_KEY);
if(manager == null) {
manager = new NetworkStorage(clientSide, DATA_KEY);
overworld.setData(DATA_KEY, manager);
}
return manager;
} else {
throw new IllegalStateException("Overworld not initialized");
}
}
public void setNetwork(RailNetwork<MCPos> network){
this.network = network;
markDirty();
}
@Override
public void readFromNBT(NBTTagCompound tag){
network = new NetworkSerializer().loadNetworkFromTag(tag);
state = MCNetworkState.fromNBT(RailNetworkManager.getInstance(clientSide), tag);
RailNetworkManager.getInstance(clientSide).loadNetwork(network, state);
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag){
new NetworkSerializer().writeToTag(network, tag);
state.writeToNBT(tag);
return tag;
}
}
| gpl-3.0 |
potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/db4ounit/common/reflect/ReflectClassTestCase.java | 1431 | /* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. */
package com.db4o.db4ounit.common.reflect;
import com.db4o.internal.*;
import com.db4o.reflect.*;
import com.db4o.reflect.generic.*;
import db4ounit.*;
public class ReflectClassTestCase implements TestCase {
public static void main(String[] args) {
new ConsoleTestRunner(ReflectClassTestCase.class).run();
}
public void testNameIsFullyQualified() {
assertFullyQualifiedName(getClass());
assertFullyQualifiedName(GenericArrayClass.class);
assertFullyQualifiedName(int[].class);
}
private void assertFullyQualifiedName(Class clazz) {
final ReflectClass reflectClass = Platform4.reflectorForType(clazz).forClass(clazz);
Assert.areEqual(ReflectPlatform.fullyQualifiedName(clazz), reflectClass.getName());
}
}
| gpl-3.0 |
jbundle/jbundle | base/db/mongodb/src/main/java/org/jbundle/base/db/mongodb/DBProperties_mongodb.java | 3012 | /*
* AccessProperties.java
*
* Created on March 29, 2001, 2:16 AM
* Copyright © 2012 jbundle.org. All rights reserved.
*/
package org.jbundle.base.db.mongodb;
import java.util.ListResourceBundle;
import org.bson.BsonType;
import org.jbundle.base.db.SQLParams;
import org.jbundle.base.model.DBConstants;
import org.jbundle.base.model.DBSQLTypes;
/**
* AccessProperties - SQL specficics for the MS Access database.
* @author don
* @version
*/
public class DBProperties_mongodb extends ListResourceBundle
{
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
// LOCALIZE THIS
{SQLParams.ALTERNATE_COUNTER_NAME, "_id"},
{SQLParams.TABLE_NOT_FOUND_ERROR_TEXT, " does not exist"}, // Table not found 42X05"42Y07},
{SQLParams.AUTO_SEQUENCE_ENABLED, DBConstants.FALSE},
{SQLParams.COUNTER_OBJECT_CLASS, java.lang.String.class.getName()}, //, java.lang.Integer.class.getName()}, // Default
{DBSQLTypes.COUNTER, "string"}, // Object
{SQLParams.NO_NULL_UNIQUE_KEYS, DBConstants.TRUE}, // A null is considered a indexable value and will produce a dup error
{SQLParams.NO_DUPLICATE_KEY_NAMES, DBConstants.TRUE},
{SQLParams.MAX_KEY_NAME_LENGTH, "128"},
// {SQLParams.BIT_TYPE_SUPPORTED, DBConstants.TRUE},
{DBSQLTypes.DATETIME, "date"},
{DBSQLTypes.DATE, "date"},
{DBSQLTypes.TIME, "date"}, // timestamp?
{DBSQLTypes.BOOLEAN, "bool"},
{DBSQLTypes.FLOAT, "double"},
{DBSQLTypes.CURRENCY, "double"}, // decimal?
{DBSQLTypes.MEMO, "string"},
{DBSQLTypes.SHORT, "int"},
{DBSQLTypes.INTEGER, "int"},
{DBSQLTypes.OBJECT, "binData"},
{DBSQLTypes.BYTE, "int"},
{DBSQLTypes.DOUBLE, "double"},
{DBSQLTypes.SMALLINT, "int"},
{DBSQLTypes.STRING, "string"},
{"INNER_JOIN", ","},
{"INNER_JOIN_ON", "WHERE"},
// {SQLParams.SQL_DATE_FORMAT, "yyyy-MM-dd"},
// {SQLParams.SQL_TIME_FORMAT, "HH:mm:ss"},
// {SQLParams.SQL_DATETIME_FORMAT, "yyyy-MM-dd HH:mm:ss"},
// {SQLParams.SQL_DATE_QUOTE, "\'"},
// {SQLParams.CREATE_PRIMARY_INDEX, "alter table {table} add CONSTRAINT {table}_{keyname} PRIMARY KEY({fields})"},
// {SQLParams.CREATE_INDEX, ""}, // Blank = Not supported
// {SQLParams.ALT_SECONDARY_INDEX, "INDEX_BLIST"}, // Alt method supported (This will speed things up a little).
{SQLParams.CREATE_DATABASE_SUPPORTED, DBConstants.TRUE}, // Can create databases.
//? {SQLParams.RENAME_TABLE_SUPPORT, DBConstants.TRUE}, // Can rename tables.
{SQLParams.AUTO_COMMIT_PARAM, DBConstants.TRUE},
{DBConstants.LOAD_INITIAL_DATA, DBConstants.TRUE}, // Load the initial data
{SQLParams.INTERNAL_DB_NAME, "mongodb"},
{SQLParams.DEFAULT_JDBC_URL_PARAM, "mongodb://${username}:${password}@${dbserver}"},
{SQLParams.DEFAULT_USERNAME_PARAM, "tourgeek"},
{SQLParams.DEFAULT_PASSWORD_PARAM, "sa1sa"}
};
// END OF MATERIAL TO LOCALIZE
}
| gpl-3.0 |
Black-millenium/rdb-executequery | java/src/org/executequery/gui/sqlstates/SQLStateCode.java | 1577 | /*
* SQLStateCode.java
*
* Copyright (C) 2002-2013 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.gui.sqlstates;
/**
* SQL State Code definition.
*
* @author Takis Diakoumis
* @version $Revision: 160 $
* @date $Date: 2013-02-08 17:15:04 +0400 (Пт, 08 фев 2013) $
*/
public class SQLStateCode {
private String sqlStateClass;
private String sqlStateSubClass;
private String description;
/**
* Creates a new instance of SQLStateCode
*/
public SQLStateCode(String sqlStateClass,
String sqlStateSubClass,
String description) {
this.sqlStateClass = sqlStateClass;
this.sqlStateSubClass = sqlStateSubClass;
this.description = description;
}
public String getSqlStateClass() {
return sqlStateClass;
}
public String getSqlStateSubClass() {
return sqlStateSubClass;
}
public String getDescription() {
return description;
}
}
| gpl-3.0 |
wylfrand/smart-album | smartalbum-service/src/main/java/com/mycompany/services/exception/ServiceException.java | 1198 | package com.mycompany.services.exception;
/**
* Exception spécique couche service.
*
* @author amv
*/
public class ServiceException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Code de l'erreur
*/
private String codeErreur;
/**
* Libellé de l'erreur
*/
private String libelleErreur;
public ServiceException(String message) {
super(message);
}
public ServiceException(Throwable cause) {
super(cause);
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
public ServiceException(String codeErreur, String libelleErreur, Throwable cause) {
super(cause);
this.codeErreur = codeErreur;
this.libelleErreur = libelleErreur;
}
public String getCodeErreur() {
return codeErreur;
}
public void setCodeErreur(String codeErreur) {
this.codeErreur = codeErreur;
}
public String getLibelleErreur() {
return libelleErreur;
}
public void setLibelleErreur(String libelleErreur) {
this.libelleErreur = libelleErreur;
}
} | gpl-3.0 |
takisd123/executequery | src/org/executequery/gui/browser/nodes/DatabaseSchemaNode.java | 2680 | /*
* DatabaseSchemaNode.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.gui.browser.nodes;
import java.util.ArrayList;
import java.util.List;
import org.executequery.databaseobjects.DatabaseMetaTag;
import org.executequery.databaseobjects.DatabaseSchema;
import org.underworldlabs.jdbc.DataSourceException;
/**
*
* @author Takis Diakoumis
*/
public class DatabaseSchemaNode extends DatabaseObjectNode {
/** the direct descendants of this object */
private List<DatabaseObjectNode> children;
/** Creates a new instance of DatabaseSchemaNode */
public DatabaseSchemaNode(DatabaseSchema schema) {
super(schema);
}
/**
* Returns the children associated with this node.
*
* @return a list of children for this node
*/
@SuppressWarnings("rawtypes")
public List<DatabaseObjectNode> getChildObjects() throws DataSourceException {
if (children != null) {
return children;
}
DatabaseSchema schema = (DatabaseSchema)getDatabaseObject();
// check for meta tags
List _children = schema.getMetaObjects();
if (_children != null && !_children.isEmpty()) {
int count = _children.size();
children = new ArrayList<DatabaseObjectNode>(count);
for (int i = 0; i < count; i++) {
DatabaseMetaTag metaTag = (DatabaseMetaTag)_children.get(i);
children.add(new DatabaseMetaTagNode(metaTag));
}
return children;
}
return null;
}
/**
* Override to return true.
*/
public boolean allowsChildren() {
return true;
}
/**
* Indicates whether this node is a leaf node.
*
* @return true | false
*/
public boolean isLeaf() {
return false;
}
/**
* Clears out the children of this node.
*/
public void reset() {
super.reset();
children = null;
}
}
| gpl-3.0 |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/ADQLValidator.java | 15309 | package cds.adql.validation;
import adql.parser.ADQLParser;
import adql.parser.grammar.ParseException;
import cds.adql.validation.parser.ValidationSetParser;
import cds.adql.validation.parser.xml.XMLValidationSetParser;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import cds.adql.validation.report.ValidatorListener;
import java.io.InputStream;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static adql.parser.ADQLParser.ADQLVersion;
/**
* Validator tool for queries set and individual queries, whatever is their
* format (XML or Java Object).
*
* <p>
* This validator can deal with all supported ADQL versions.
* <em>See {@link #getParser(ADQLVersion)}.</em>
* </p>
*
* <p>
* Any validation process reports its progress and result to all registered
* {@link ValidatorListener}. Some are already provided (
* {@link cds.adql.validation.report.StatCollector},
* {@link cds.adql.validation.report.MarkdownReport} and
* {@link cds.adql.validation.report.TextReport}) but custom ones are
* encouraged in case of special needs.
* </p>
*
* @author Grégory Mantelet (CDS)
* @version 1.0 (12/2021)
*/
public class ADQLValidator {
final static Logger LOGGER = Logger.getLogger(ADQLValidator.class.getName());
private final List<ValidatorListener> listeners;
private final Map<ADQLVersion, ADQLParser> parsers;
/* ********************************************************************** */
public ADQLValidator(){
listeners = new ArrayList<>();
parsers = new HashMap<>(ADQLVersion.values().length);
}
/* *************************************************************************
* LISTENERS MANAGEMENT
*/
/**
* Add a listener to this validator.
*
* <p>
* This function rejects NULL listeners ; it returns <code>false</code>
* immediately.
* </p>
*
* <p>
* This function does nothing more than returning <code>true</code>
* immediately if the given listener is already registered with this
* validator.
* </p>
*
* <p><i><b>Note:</b>
* If the listener can not be added, this function returns
* <code>false</code> and logs the reason as a WARNING message.
* </i></p>
*
* @param listener The new listener.
*
* @return <code>true</code> if the listener has been added,
* <code>false</code> otherwise (e.g. if already listening).
*/
public final boolean addListener(final ValidatorListener listener){
// Forbid NULL listeners:
if (listener == null)
return false;
// Do nothing more if already registered:
else if (listeners.contains(listener))
return true;
// Otherwise, use the standard ArrayList `add(Object) function:
try{
return listeners.add(listener);
}
// ...but in case of error, log a WARNING and return `false`:
catch(Exception ex){
LOGGER.log(Level.WARNING, "Impossible to add the given listener! Cause: "+ex.getMessage(), ex);
return false;
}
}
/**
* Insert the given listener at the given position in the listeners list.
*
* <p>
* This function rejects NULL listeners ; it returns <code>false</code>
* immediately.
* </p>
*
* <p>
* This function does nothing more than returning <code>true</code>
* immediately if the given listener is already registered with this
* validator.
* </p>
*
* <p><i><b>Note:</b>
* If the listener can not be added, this function returns
* <code>false</code> and logs the reason as a WARNING message.
* </i></p>
*
* @param index Position where to insert the listener.
* @param listener The new listener.
*
* @return <code>true</code> if the listener has been added,
* <code>false</code> otherwise (e.g. if already listening).
*/
public final boolean addListener(final int index, final ValidatorListener listener){
// Forbid NULL listeners:
if (listener == null)
return false;
// Do nothing more if already registered:
else if (listeners.contains(listener))
return true;
// Otherwise, use the standard ArrayList `add(int, Object)` function:
try {
listeners.add(index, listener);
return true;
}
// ...but in case of error, log a WARNING and return `false`:
catch(Exception ex){
LOGGER.log(Level.WARNING, "Impossible to add the given listener! Cause: "+ex.getMessage(), ex);
return false;
}
}
/**
* Remove the given listener from the list of objects listening to this
* validator.
*
* <p><i><b>Note:</b>
* If the listener can not be removed, this function returns
* <code>false</code> and logs the reason as a FINE message.
* </i></p>
*
* @param listener The listener to remove.
*
* @return <code>true</code> if the listener has been removed,
* <code>false</code> otherwise (e.g. if already not listening).
*/
public final boolean removeListener(final ValidatorListener listener){
// Use the standard ArrayList `remove(Object)` function:
try {
if (listeners.remove(listener))
return true;
else {
LOGGER.log(Level.FINE, "Impossible to remove the given listener! Cause: it does not listen to this validator.");
return false;
}
}
// ...but in case of error, log a FINE message and return `false`:
catch(Exception ex){
LOGGER.log(Level.FINE, "Impossible to remove the given listener! Cause: "+ex.getMessage(), ex);
return false;
}
}
/**
* Remove the specified listener from the list of objects listening to this
* validator.
*
* <p><i><b>Note:</b>
* If no listener matches the given index, NULL is returned and the reason
* is logged as a FINE message.
* </i></p>
*
* @param index Index of the listener to remove.
*
* @return The removed listener,
* or NULL in case of error.
*/
public final ValidatorListener removeListener(final int index){
try {
return listeners.remove(index);
}
// ...but in case of error, log a WARNING and return NULL:
catch(Exception ex){
LOGGER.log(Level.FINE, "Impossible to remove the listener at the index "+index+"! Cause: "+ex.getMessage(), ex);
return null;
}
}
/**
* Get an iterator over the complete list of objects listening to this
* validator.
*
* @return An iterator over all listeners.
*/
public final Iterator<ValidatorListener> getListeners(){
return listeners.iterator();
}
/* *************************************************************************
* PARSERS MANAGEMENT
*/
/**
* Get a parser for the given version of ADQL.
*
* <p>
* If no parser exists for the given ADQL version, one will be created
* and returned. Then, it will be reused whenever a parser for the same
* ADQL version is asked.
* </p>
*
* <p>
* The returned parser always accepts all coordinate systems.
* </p>
*
* @param version The target ADQL version.
* NULL is equivalent to {@link ValidationSetParser#DEFAULT_ADQL_VERSION}.
*
* @return The corresponding ADQL parser.
*/
protected ADQLParser getParser(ADQLVersion version) {
// Set a default version if none is provided:
if (version == null)
version = ValidationSetParser.DEFAULT_ADQL_VERSION;
// Try to get the parser, if already created:
ADQLParser parser = parsers.get(version);
// If not existing, create it:
if (parser == null) {
parsers.put(version, (parser = new ADQLParser(version)));
// Allow any coordinate system:
try {
parser.setAllowedCoordSys(null);
} catch (ParseException e) {
LOGGER.log(Level.WARNING, "Impossible to remove the restriction on the coordinate system argument!", e);
}
// Allow any UDF:
parser.allowAnyUdf(true);
}
// Return the found/created parser:
return parser;
}
/* *************************************************************************
* XML VALIDATION
*/
/**
*
* Check that the document provided by the given stream is a valid XML
* document, as expected by this {@link ADQLValidator}.
*
* @param stream Stream toward the document to parse.
*
* @throws cds.adql.validation.parser.ParseException In case of parsing error.
*
* @see XMLValidationSetParser#checkXML(InputStream)
*/
public void checkXML(final InputStream stream)
throws cds.adql.validation.parser.ParseException
{
(new XMLValidationSetParser()).checkXML(stream);
}
/**
* Validate a valid XML document representing a complete validation set.
*
* <p>
* The parsed validation set will be validated thanks to
* {@link #validate(ValidationSet, String)}.
* </p>
*
* <p>
* Validation status, progress, success and failure are all reported to
* all registered listeners.
* </p>
*
* @param stream Stream toward the XML validation set.
* @param source Human information about where the document comes from
* (example: <code>File /foo/bar.xml</code>). It is purely
* informal. It aims to improve the documentation of the
* validation process.
*
* @return <code>true</code> if all tests passed inside the validation set,
* <code>false</code> in case of error or if at least one test
* failed.
*
* @see XMLValidationSetParser#parse(InputStream)
* @see #validate(ValidationSet, String)
*/
public boolean validateXML(final InputStream stream, final String source){
// Parse the file:
ValidationSet tests;
try{
// Parse the XML document and transform it into a tests set:
tests = (new XMLValidationSetParser()).parse(stream);
// Validate the tests set:
if (tests != null)
return validate(tests, source);
// Or report an error:
else {
publishError(new ValidationException("No validation set provided!"));
return false;
}
}
catch (cds.adql.validation.parser.ParseException e) {
publishError(new ValidationException("XML document parsing failed! Cause: "+e.getMessage(), e));
return false;
}
}
/* *************************************************************************
* GENERIC VALIDATION
*/
/**
* Validate all queries of the given validation set.
*
* <p>
* This function does NOT stop the validation at the first failed query.
* All queries are tested so that the final report can be as complete as
* possible.
* </p>
*
* @param set Set of queries to validate.
* @param source Human information about where the document comes from
* (example: <code>File /foo/bar.xml</code>). It is purely
* informal. It aims to improve the documentation of the
* validation process.
*
* @return <code>true</code> if all queries of the validation set passed,
* <code>false</code> in case of error, NULL or if one query failed.
*/
public boolean validate(final ValidationSet set, final String source){
// Nothing to validate if NULL:
if (set == null)
return false;
// Publish the start of the Validation session:
publishStartValidation(set, source);
// Validate all queries:
boolean allValid = true;
for(ValidationQuery query : set.queries) {
/* always try to validate all queries even if allValid is false ;
* that way, all errors of all queries are reported. */
allValid = validate(query) && allValid;
}
// Publish the end of the Validation session:
publishEndValidation(set);
return allValid;
}
/**
* Validate a single ADQL query.
*
* <p><i><b>Note:</b>
* NULL or an empty query string will make this function immediately
* return <code>false</code>.
* </i></p>
*
* @param query The query to validate.
*
* @return <code>true</code> if this query passed the validation test,
* <code>false</code> otherwise.
*/
public boolean validate(final ValidationQuery query){
// Nothing to validate if NULL:
if (query == null
|| query.query == null
|| query.query.trim().isEmpty())
{
return false;
}
boolean valid;
String err = null;
// Get the appropriate ADQL parser:
final ADQLParser parser = getParser(query.adqlVersion);
// Publish start of validation:
publishStartValidation(query);
// Parse the ADQL query:
try {
parser.parseQuery(query.query);
valid = true;
}catch(ParseException pe){
valid = false;
err = pe.getMessage();
}
// Report the validation result:
final boolean success = (valid == query.isValid);
publishTestResult(query, success, err);
return success;
}
protected void publishStartValidation(final ValidationSet set,
final String source)
{
for(ValidatorListener listener : listeners){
listener.start(set, source);
}
}
protected void publishEndValidation(final ValidationSet set){
for(ValidatorListener listener : listeners){
listener.end(set);
}
}
protected void publishStartValidation(final ValidationQuery query){
for(ValidatorListener listener : listeners){
listener.validating(query);
}
}
protected void publishError(final ValidationException error){
for(ValidatorListener listener : listeners){
listener.error(error);
}
}
protected void publishTestResult(final ValidationQuery query,
final boolean success,
final String errorMessage)
{
for(ValidatorListener listener : listeners){
if (success)
listener.pass(query);
else
listener.fail(query, errorMessage);
}
}
}
| gpl-3.0 |
CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/LocElementDAO.java | 3195 | /*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
* MARLO is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
package org.cgiar.ccafs.marlo.data.dao;
import org.cgiar.ccafs.marlo.data.model.LocElement;
import java.util.List;
public interface LocElementDAO {
/**
* This method removes a specific locElement value from the database.
*
* @param locElementId is the locElement identifier.
* @return true if the locElement was successfully deleted, false otherwise.
*/
public void deleteLocElement(long locElementId);
/**
* This method validate if the locElement identify with the given id exists
* in the system.
*
* @param locElementID is a locElement identifier.
* @return true if the locElement exists, false otherwise.
*/
public boolean existLocElement(long locElementID);
/**
* This method gets a locElement object by a given locElement identifier.
*
* @param locElementID is the locElement identifier.
* @return a LocElement object.
*/
public LocElement find(long id);
/**
* This method gets a list of locElement that are active
*
* @return a list from LocElement null if no exist records
*/
public List<LocElement> findAll();
public List<LocElement> findAllLocationMap(Long phase);
/**
* This method gets a locElement object by a given locElement IsoCode.
*
* @param ISOCode of the LocElement.
* @return a LocElement object.
*/
public LocElement findISOCode(String ISOcode);
/**
* This method gets a locElement object by a parent locElement.
*
* @param parentId is the locElement parent id.
* @return a LocElement object.
*/
public List<LocElement> findLocElementByParent(Long parentId);
/**
* This method gets a locElement object by a given locElement numeric
* IsoCode.
*
* @param numeric ISOCode of the LocElement.
* @return a LocElement object.
*/
LocElement findNumericISOCode(Long ISOcode);
/**
* This method saves the information of the given locElement
*
* @param locElement - is the locElement object with the new information to
* be added/updated.
* @return a number greater than 0 representing the new ID assigned by the
* database, 0 if the locElement was updated or -1 is some error occurred.
*/
public LocElement save(LocElement locElement);
}
| gpl-3.0 |
Minecolonies/minecolonies | src/api/java/com/minecolonies/api/sounds/TavernSounds.java | 280 | package com.minecolonies.api.sounds;
import net.minecraft.util.SoundEvent;
/**
* Sounds for the tavern
*/
public class TavernSounds
{
/**
* Tavern theme
*/
public static final SoundEvent tavernTheme = ModSoundEvents.getSoundID("tile.tavern.tavern_theme");
}
| gpl-3.0 |
kostovhg/SoftUni | Java Fundamentals-Sep17/Java Advanced/t05_ObjectClassesAndCollections_E/src/p03_BasicQueueOperations.java | 1157 | import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Scanner;
public class p03_BasicQueueOperations {
private static Deque<Integer> queue = new ArrayDeque<>();
private static Deque<Integer> minStack = new ArrayDeque<>();
static private int[] readIntArr(String line){
return Arrays.stream(line.split("\\s+"))
.mapToInt(Integer::parseInt).toArray();
}
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
int[] comm = readIntArr(scann.nextLine());
int[] nums = readIntArr(scann.nextLine());
minStack.push(Integer.MAX_VALUE);
for (int i = 0; i < comm[0]; i++) {
queue.add(nums[i]);
if(nums[i] < minStack.peek()) minStack.push(nums[i]);
}
for (int i = 0; i < comm[1]; i++) {
if(queue.poll().equals(minStack.peek())) minStack.pop();
}
if(queue.contains(comm[2])) System.out.println("true");
else if(queue.isEmpty()) System.out.println("0");
else
{
System.out.println(minStack.peek());
}
}
} | gpl-3.0 |
RezzedUp/OpGuard | src/main/java/com/rezzedup/opguard/api/message/Loggable.java | 124 | package com.rezzedup.opguard.api.message;
public interface Loggable extends ChainableMessage
{
boolean isLoggable();
}
| gpl-3.0 |
nebulent/netflexity-qflex-commons | netflexity-commons-ssh/src/test/java/org/netflexity/api/ssh/jsch/JschSshManagerTest.java | 3806 | /*
* 2007 Netflexity, Ltd. All Rights Reserved.
*
* CONFIDENTIAL BUSINESS INFORMATION
*
* THIS PROGRAM IS PROPRIETARY INFORMATION OF NETFLEXITY, LTD. AND
* IS NOT TO BE COPIED, REPRODUCED, LENT, OR DISPOSED OF, NOR USED FOR ANY
* OTHER PURPOSE, UNLESS THE WRITTEN PERMISSION FROM THE STATED ABOVE CORPORATION
* IS GIVEN.
*/
package org.netflexity.api.ssh.jsch;
import java.util.Iterator;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.netflexity.api.ssh.SshException;
import org.netflexity.api.ssh.jsch.JschSshManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author MAX
*
*/
public class JschSshManagerTest extends TestCase{
protected ApplicationContext appContext;
protected Logger logger;
protected JschSshManager sshManager;
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
appContext = new ClassPathXmlApplicationContext(JschSshManagerTest.class.getPackage().getName()
.replace('.', '/') + "/applicationContext.xml");
// Configure log4j.
BasicConfigurator.configure();
logger = Logger.getLogger(this.getClass().getName());
// Retrieve ssh session factory bean.
sshManager = (JschSshManager) appContext.getBean("jschSshSession");
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
}
public void testAll() {
getFileListing();
changeWorkingDirectory();
getTextFileContent();
}
public void executeShellCommand() {
try {
String result = sshManager.executeShellCommand("qflex_ssh.sh a b");
logger.info(result);
}
catch (SshException e) {
logger.error(e.getMessage(), e);
Assert.assertTrue(e.getMessage(), false);
}
}
/**
* Test method for {@link org.netflexity.api.ssh.jsch.JschSshManager#getFileListing()}.
*/
public void getFileListing() {
try {
List listings = sshManager.getFileListing();
for (Iterator iter = listings.iterator(); iter.hasNext();) {
String fileName = (String) iter.next();
logger.info(fileName);
}
}
catch (SshException e) {
logger.error(e.getMessage(), e);
Assert.assertTrue(e.getMessage(), false);
}
}
/**
* Test method for {@link org.netflexity.api.ssh.jsch.JschSshManager#changeWorkingDirectory(java.lang.String)}.
*/
public void changeWorkingDirectory() {
try {
sshManager.changeWorkingDirectory("/var/mqm/errors");
String result = sshManager.getWorkingDirectory();
Assert.assertEquals("/var/mqm/errors", result);
}
catch (SshException e) {
logger.error(e.getMessage(), e);
Assert.assertTrue(e.getMessage(), false);
}
}
/**
* Test method for {@link org.netflexity.api.ssh.jsch.JschSshManager#getTextFileContent(java.lang.String)}.
*/
public void getTextFileContent() {
try {
String result = sshManager.getTextFileContent("AMQ16665.0.FDC");
logger.info(result);
}
catch (SshException e) {
logger.error(e.getMessage(), e);
Assert.assertTrue(e.getMessage(), false);
}
}
}
| gpl-3.0 |
javieriserte/bioUtils | src/utils/ConservationImage/RendererValue.java | 1237 | package utils.ConservationImage;
import java.io.File;
import utils.ConservationImage.renderer.ColoredLinesRenderer;
import utils.ConservationImage.renderer.Renderer;
import utils.ConservationImage.renderer.RendererReader;
import utils.ConservationImage.renderer.XYPlotRenderer;
import cmdGA2.returnvalues.InfileValue;
import cmdGA2.returnvalues.ReturnValueParser;
public class RendererValue extends ReturnValueParser<Renderer> {
///////////////////////////////////////
// Class constants
public static final String XY_PLOT_RENDERER = "XY";
public static final String VERTICAL_LINES_RENDERER = "LINES";
///////////////////////////////////////
@Override
public Renderer parse(String token) {
Renderer renderer = null;
if (token.equals(RendererValue.XY_PLOT_RENDERER)) {
renderer = new XYPlotRenderer();
renderer.setLayout(renderer.getDefaultLayout());
} else
if (token.equals(RendererValue.VERTICAL_LINES_RENDERER)){
renderer = new ColoredLinesRenderer();
renderer.setLayout(renderer.getDefaultLayout());
} else {
File infile = (new InfileValue()).parse(token);
if ( infile.exists() ) {
renderer = (new RendererReader()).parse_file(infile);
}
}
return renderer;
}
}
| gpl-3.0 |
jakey766/web_base | src/main/java/com/pk/framework/vo/PageSearchVO.java | 540 | package com.pk.framework.vo;
/**
* 分页查询Bean
* Created by jiangkunpeng on 16/9/23.
*/
public class PageSearchVO {
private int page = 1;
private int size = 0;
public int getStart() {
if(page < 0)
page = 1;
return (page - 1) * size;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
| gpl-3.0 |
proarc/proarc | proarc-common/src/main/java/cz/cas/lib/proarc/common/object/emods/BornDigitalDisseminationHandler.java | 5400 | /*
* Copyright (C) 2015 Jan Pokorsky
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cas.lib.proarc.common.object.emods;
import cz.cas.lib.proarc.common.config.AppConfiguration;
import cz.cas.lib.proarc.common.config.AppConfigurationException;
import cz.cas.lib.proarc.common.config.AppConfigurationFactory;
import cz.cas.lib.proarc.common.fedora.BinaryEditor;
import cz.cas.lib.proarc.common.fedora.DigitalObjectException;
import cz.cas.lib.proarc.common.imports.InputUtils;
import cz.cas.lib.proarc.common.object.DefaultDisseminationHandler;
import cz.cas.lib.proarc.common.object.DigitalObjectHandler;
import cz.cas.lib.proarc.common.object.DisseminationHandler;
import cz.cas.lib.proarc.common.object.DisseminationInput;
import cz.cas.lib.proarc.common.process.GenericExternalProcess;
import java.io.File;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import org.apache.commons.configuration.Configuration;
/**
* Processes uploaded contents (PDF), validates, creates thumbnail, preview and others.
*
* @author Jan Pokorsky
*/
public class BornDigitalDisseminationHandler implements DisseminationHandler {
private final String dsId;
private final DigitalObjectHandler objHandler;
private final DefaultDisseminationHandler ddh;
public BornDigitalDisseminationHandler(DefaultDisseminationHandler ddh) {
this.dsId = ddh.getDsId();
this.objHandler = ddh.getHandler();
this.ddh = ddh;
}
@Override
public Response getDissemination(Request httpRequest) throws DigitalObjectException {
return ddh.getDissemination(httpRequest);
}
@Override
public void setDissemination(DisseminationInput input, String message) throws DigitalObjectException {
// MediaType mime = input.getMime();
// if (!"application".equalsIgnoreCase(mime.getType()) || !"pdf".equalsIgnoreCase(mime.getSubtype())) {
// throw new DigitalObjectException(handler.getFedoraObject().getPid(), null, dsId,
// "Unsupported MIME " + mime, null);
// }
File inputFile = input.getFile();
if (!isPdf(inputFile)) {
throw new DigitalObjectException(objHandler.getFedoraObject().getPid(), null, dsId,
"Not PDF content " + inputFile + ", exists: " + inputFile.exists() + ", size: " + inputFile.length(), null);
}
MediaType mime = new MediaType("application", "pdf");
if (BinaryEditor.RAW_ID.equals(dsId)) {
// XXX use importer
ddh.setRawDissemination(inputFile, input.getFilename(), mime, message);
ddh.setIconAsDissemination(BinaryEditor.PREVIEW_ID, mime, BinaryEditor.PREVIEW_LABEL, message);
createThumbnail(inputFile, message);
} else {
throw new DigitalObjectException(objHandler.getFedoraObject().getPid(), null, dsId,
"Unsupported datastream ID!", null);
}
}
@Override
public void deleteDissemination(String message) throws DigitalObjectException {
objHandler.getFedoraObject().purgeDatastream(BinaryEditor.RAW_ID, message);
objHandler.getFedoraObject().purgeDatastream(BinaryEditor.PREVIEW_ID, message);
objHandler.getFedoraObject().purgeDatastream(BinaryEditor.THUMB_ID, message);
}
private void createThumbnail(File inputFile, String message) throws DigitalObjectException {
Configuration thumbConf = getConfig().getImportConfiguration().getThumbnailProcessor();
if (thumbConf != null && !thumbConf.isEmpty()) {
GenericExternalProcess thumbProc = new GenericExternalProcess(thumbConf)
.addInputFile(inputFile)
.addOutputFile(new File(inputFile.getAbsolutePath() + ".jpg"));
thumbProc.run();
if (thumbProc.isOk()) {
ddh.setDsDissemination(BinaryEditor.THUMB_ID, thumbProc.getOutputFile(),
BinaryEditor.THUMB_LABEL, BinaryEditor.IMAGE_JPEG, message);
}
}
}
private AppConfiguration getConfig() throws DigitalObjectException {
try {
return AppConfigurationFactory.getInstance().defaultInstance();
} catch (AppConfigurationException ex) {
throw new DigitalObjectException(objHandler.getFedoraObject().getPid(), null, dsId,
"Broken configuration! ", ex);
}
}
private boolean isPdf(File f) throws DigitalObjectException {
try {
return InputUtils.isPdf(f);
} catch (IOException ex) {
throw new DigitalObjectException(objHandler.getFedoraObject().getPid(),
null, dsId, f.toString(), ex);
}
}
}
| gpl-3.0 |
dvoraka/av-service | client/src/main/java/dvoraka/avservice/client/configuration/file/AmqpFileClientConfig.java | 2002 | package dvoraka.avservice.client.configuration.file;
import dvoraka.avservice.client.transport.AvNetworkComponent;
import dvoraka.avservice.client.transport.amqp.AmqpAdapter;
import dvoraka.avservice.db.service.MessageInfoService;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* AMQP file client configuration for the import.
*/
@Configuration
@Profile("amqp")
public class AmqpFileClientConfig {
@Value("${avservice.amqp.resultQueue}")
private String resultQueue;
@Value("${avservice.amqp.fileExchange}")
private String fileExchange;
@Value("${avservice.serviceId}")
private String serviceId;
@Bean
public AvNetworkComponent avNetworkComponent(
RabbitTemplate rabbitTemplate,
MessageInfoService messageInfoService
) {
return new AmqpAdapter(fileExchange, serviceId, rabbitTemplate, messageInfoService);
}
@Bean
public MessageListener messageListener(AvNetworkComponent avNetworkComponent) {
return avNetworkComponent;
}
@Bean
public MessageListenerContainer messageListenerContainer(
ConnectionFactory connectionFactory,
MessageListener messageListener
) {
DirectMessageListenerContainer container = new DirectMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setQueueNames(resultQueue);
container.setMessageListener(messageListener);
return container;
}
}
| gpl-3.0 |
tohhy/olivia-swing | src/main/java/org/ocsoft/olivia/views/components/window/OliviaWindow.java | 6162 | package org.ocsoft.olivia.views.components.window;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.apache.commons.lang3.SystemUtils;
import org.frows.exwing.v0_0_7.topcontainers.ExFrame;
import org.frows.observatories.v0_1_0.ObserverStopper;
import org.frows.observatories.v0_1_0.ObserverStopper.StoppableObserver;
import org.frows.pjf.v0_0_4.PJF;
import org.ocsoft.olivia.core.Olivia;
import org.ocsoft.olivia.logger.OliviaLogger;
import org.ocsoft.olivia.models.components.window.WindowModel;
import org.ocsoft.olivia.models.components.window.WindowModelObserver;
import org.ocsoft.olivia.views.components.layout.MainContainer;
import org.ocsoft.olivia.views.components.menu.OliviaMenuBar;
import org.ocsoft.olivia.views.components.menu.OliviaPopupMenu;
/**
* Oliviaのメインウィンドウ.
* @author tohhy
*/
@SuppressWarnings("serial")
public class OliviaWindow extends ExFrame implements WindowModelObserver, StoppableObserver {
private Rectangle memorizedBounds;
private final OliviaMenuBar mainMenu;
private final OliviaPopupMenu popupMenu;
private final MainContainer mainPanel;
private final WindowModel model;
private final WindowAdapter wa = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
Olivia.exit();
}
};
private final ComponentListener cl = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
try(ObserverStopper s = new ObserverStopper(OliviaWindow.this)) {
model.setSize(e.getComponent().getWidth(), e.getComponent().getHeight());
}
}
public void componentMoved(ComponentEvent e) {
try(ObserverStopper s = new ObserverStopper(OliviaWindow.this)) {
model.setLocation(e.getComponent().getX(), e.getComponent().getY());
}
}
};
public OliviaWindow() {
//設定
this.setTitle(Olivia.getView().getTitleBarText());
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//コンポーネントの追加
this.mainMenu = new OliviaMenuBar();
this.popupMenu = new OliviaPopupMenu();
this.mainPanel = new MainContainer(this);
this.setJMenuBar(getMainMenu());
this.add(mainPanel);
//モデルの状態読み込み
this.model = Olivia.getView().getComponents().getWindow();
//デフォルトは非フルスクリーンにしておく
model.setFullScreen(false);
sizeChanged(model.getWidth(), model.getHeight());
locationChanged(model.getX(), model.getY());
startObserving();
SwingUtilities.invokeLater(()->{
//可視化
this.pack();
this.setVisible(true);
OliviaLogger.initialized(this);
});
}
/**
*
* @return
*/
public OliviaMenuBar getMainMenu() {
return mainMenu;
}
/**
*
* @return
*/
public MainContainer getMainContainer() {
return mainPanel;
}
/**
*
* @return
*/
public OliviaPopupMenu getPopupMenus() {
return popupMenu;
}
/**
* フルスクリーンのON/OFFを切り替える.
*/
public void fullScreenStateChanged(boolean isFullScreen) {
try(ObserverStopper s = new ObserverStopper(this)) {
SwingUtilities.invokeLater(()->{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = ge.getDefaultScreenDevice();
if(!device.isFullScreenSupported()) return;
//フルスクリーン状態切替中は一時的に非表示にする
this.setVisible(false);
//disposeしておかないと"The frame is displayable"のエラーが出る
this.dispose();
//切替
if(isFullScreen) {
memorizedBounds = getBounds();
this.setUndecorated(true);
if(SystemUtils.IS_OS_MAC) {
int barheight = 23;
this.setBounds(0, barheight,
PJF.getScreen().getWidth(),
PJF.getScreen().getHeight() - barheight);
} else {
device.setFullScreenWindow(this);
}
} else {
device.setFullScreenWindow(null);
this.setUndecorated(false);
this.setBounds(memorizedBounds);
}
//再表示
this.setVisible(true);
});
}
}
@Override
public void sizeChanged(int width, int height) {
try(ObserverStopper s = new ObserverStopper(this)) {
SwingUtilities.invokeLater(()->{
this.setPreferredSize(new Dimension(width, height));
this.setSize(width, height);
this.revalidate();
});
}
}
@Override
public void locationChanged(int x, int y) {
try(ObserverStopper s = new ObserverStopper(this)) {
SwingUtilities.invokeLater(()->{
this.setLocation(x, y);
});
}
}
@Override
public void startObserving() {
this.addWindowListener(wa);
this.addComponentListener(cl);
Olivia.getView().getComponents().getWindow().addObserver(this);
}
@Override
public void stopObserving() {
this.removeWindowListener(wa);
this.removeComponentListener(cl);
Olivia.getView().getComponents().getWindow().removeObserver(this);
}
}
| gpl-3.0 |
dedmen/McMod1 | common/com/dedmen/MyMod1/lib/Reference.java | 208 | package com.dedmen.MyMod1.lib;
public class Reference {
public static final String MOD_ID = "DM1";
public static final String MOD_NAME = "Dedmens MC Mod";
public static final String VERSION = "0.0.1";
}
| gpl-3.0 |
meyerjp3/jmetrik-cadence | src/main/java/com/itemanalysis/jmetrik/stats/cmh/DifEffectSizeType.java | 928 | /**
* Copyright 2015 J. Patrick Meyer
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.itemanalysis.jmetrik.stats.cmh;
public enum DifEffectSizeType {
ETS_DELTA{
@Override
public String toString(){
return "delta";
}
},
COMMON_ODDS_RATIO{
@Override
public String toString(){
return "odds";
}
}
}
| gpl-3.0 |
Tynogc/Cryptograph | src/gui/start/AccountSetup_Name.java | 2477 | package gui.start;
import gui.Ping;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.regex.Pattern;
import main.Fonts;
import main.Language;
import main.PicLoader;
import main.SeyprisMain;
import main.UserManager;
import menu.Button;
import menu.MoveMenu;
import menu.TextEnterButton;
public class AccountSetup_Name extends MoveMenu{
private TextEnterButton teb;
private Button ok;
private NewAccount controle;
private String[] text;
public AccountSetup_Name(int x, int y, NewAccount n) {
super(x, y, PicLoader.pic.getImage("res/ima/mbe/m700x500.png"), Language.lang.text(20200));
teb = new TextEnterButton(40, 400, 200, 20, Color.black, SeyprisMain.getKL()) {
@Override
protected void textEntered(String text) {
check();
}
};
teb.setTextColor(Color.white);
add(teb);
teb.setText(n.name);
ok = new Button(530,450,"res/ima/cli/B") {
@Override
protected void uppdate() {}
@Override
protected void isFocused() {}
@Override
protected void isClicked() {
make();
}
};
ok.setText(Language.lang.text(4));
ok.setTextColor(Button.gray);
add(ok);
controle = n;
text = new String[]{
Language.lang.text(20201),
Language.lang.text(20202),
Language.lang.text(20203),
Language.lang.text(20204),
""
};
}
@Override
protected void paintSecond(Graphics g) {
g.setColor(Color.white);
g.setFont(Fonts.fontBold18);
g.drawString(text[0], 50, 130);
g.drawString(text[1], 50, 150);
g.setFont(Fonts.fontBold14);
g.drawString(text[2], 40, 370);
g.drawString(text[3], 60, 390);
g.setColor(Color.red);
g.drawString(text[4], 45, 440);
}
@Override
protected boolean close() {
return true; //TODO ask
}
@Override
protected void uppdateIntern() {
}
private boolean check(){
String dir = teb.getText();
if(dir.length()<3){
text[4] = Language.lang.text(20205);
return false;
}
if(!Pattern.matches("[a-zA-Z0-9-_]+", dir)){
text[4] = Language.lang.text(20206);
return false;
}
File f = new File(UserManager.getPreDirectory()+dir);
if(f.exists()){//User Already exists!
text[4] = Language.lang.text(20207);
return false;
}
text[4] = "";
return true;
}
private void make(){
if(!check()){
Ping.ping(xPos+30, yPos+410, Ping.ALARM);
return;
}
String dir = teb.getText();
controle.name = dir;
controle.nextMenu();
closeYou();
}
}
| gpl-3.0 |
EvilSeph/Bukkit | src/main/java/org/bukkit/plugin/PluginDescriptionFile.java | 41937 | package org.bukkit.plugin;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.permissions.Permissible;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
/**
* This type is the runtime-container for the information in the plugin.yml.
* All plugins must have a respective plugin.yml. For plugins written in java
* using the standard plugin loader, this file must be in the root of the jar
* file.
* <p>
* When Bukkit loads a plugin, it needs to know some basic information about
* it. It reads this information from a YAML file, 'plugin.yml'. This file
* consists of a set of attributes, each defined on a new line and with no
* indentation.
* <p>
* Every (almost* every) method corresponds with a specific entry in the
* plugin.yml. These are the <b>required</b> entries for every plugin.yml:
* <ul>
* <li>{@link #getName()} - <code>name</code>
* <li>{@link #getVersion()} - <code>version</code>
* <li>{@link #getMain()} - <code>main</code>
* </ul>
* <p>
* Failing to include any of these items will throw an exception and cause the
* server to ignore your plugin.
* <p>
* This is a list of the possible yaml keys, with specific details included in
* the respective method documentations:
* <table border=1>
* <tr>
* <th>Node</th>
* <th>Method</th>
* <th>Summary</th>
* </tr><tr>
* <td><code>name</code></td>
* <td>{@link #getName()}</td>
* <td>The unique name of plugin</td>
* </tr><tr>
* <td><code>version</code></td>
* <td>{@link #getVersion()}</td>
* <td>A plugin revision identifier</td>
* </tr><tr>
* <td><code>main</code></td>
* <td>{@link #getMain()}</td>
* <td>The plugin's initial class file</td>
* </tr><tr>
* <td><code>author</code><br><code>authors</code></td>
* <td>{@link #getAuthors()}</td>
* <td>The plugin contributors</td>
* </tr><tr>
* <td><code>description</code></td>
* <td>{@link #getDescription()}</td>
* <td>Human readable plugin summary</td>
* </tr><tr>
* <td><code>website</code></td>
* <td>{@link #getWebsite()}</td>
* <td>The URL to the plugin's site</td>
* </tr><tr>
* <td><code>prefix</code></td>
* <td>{@link #getPrefix()}</td>
* <td>The token to prefix plugin log entries</td>
* </tr><tr>
* <td><code>database</code></td>
* <td>{@link #isDatabaseEnabled()}</td>
* <td>Indicator to enable database support</td>
* </tr><tr>
* <td><code>load</code></td>
* <td>{@link #getLoad()}</td>
* <td>The phase of server-startup this plugin will load during</td>
* </tr><tr>
* <td><code>depend</code></td>
* <td>{@link #getDepend()}</td>
* <td>Other required plugins</td>
* </tr><tr>
* <td><code>softdepend</code></td>
* <td>{@link #getSoftDepend()}</td>
* <td>Other plugins that add functionality</td>
* </tr><tr>
* <td><code>loadbefore</code></td>
* <td>{@link #getLoadBefore()}</td>
* <td>The inverse softdepend</td>
* </tr><tr>
* <td><code>commands</code></td>
* <td>{@link #getCommands()}</td>
* <td>The commands the plugin will register</td>
* </tr><tr>
* <td><code>permissions</code></td>
* <td>{@link #getPermissions()}</td>
* <td>The permissions the plugin will register</td>
* </tr><tr>
* <td><code>default-permission</code></td>
* <td>{@link #getPermissionDefault()}</td>
* <td>The default {@link Permission#getDefault() default} permission
* state for defined {@link #getPermissions() permissions} the plugin
* will register</td>
* </tr>
* </table>
* <p>
* A plugin.yml example:<blockquote><pre>
*name: Inferno
*version: 1.4.1
*description: This plugin is so 31337. You can set yourself on fire.
*# We could place every author in the authors list, but chose not to for illustrative purposes
*# Also, having an author distinguishes that person as the project lead, and ensures their
*# name is displayed first
*author: CaptainInflamo
*authors: [Cogito, verrier, EvilSeph]
*website: http://www.curse.com/server-mods/minecraft/myplugin
*
*main: com.captaininflamo.bukkit.inferno.Inferno
*database: false
*depend: [NewFire, FlameWire]
*
*commands:
* flagrate:
* description: Set yourself on fire.
* aliases: [combust_me, combustMe]
* permission: inferno.flagrate
* usage: Syntax error! Simply type /<command> to ignite yourself.
* burningdeaths:
* description: List how many times you have died by fire.
* aliases: [burning_deaths, burningDeaths]
* permission: inferno.burningdeaths
* usage: |
* /<command> [player]
* Example: /<command> - see how many times you have burned to death
* Example: /<command> CaptainIce - see how many times CaptainIce has burned to death
*
*permissions:
* inferno.*:
* description: Gives access to all Inferno commands
* children:
* inferno.flagrate: true
* inferno.burningdeaths: true
* inferno.burningdeaths.others: true
* inferno.flagrate:
* description: Allows you to ignite yourself
* default: true
* inferno.burningdeaths:
* description: Allows you to see how many times you have burned to death
* default: true
* inferno.burningdeaths.others:
* description: Allows you to see how many times others have burned to death
* default: op
* children:
* inferno.burningdeaths: true
*</pre></blockquote>
*/
public final class PluginDescriptionFile {
private static final Yaml yaml = new Yaml(new SafeConstructor());
private String name = null;
private String main = null;
private String classLoaderOf = null;
private List<String> depend = null;
private List<String> softDepend = null;
private List<String> loadBefore = null;
private String version = null;
private Map<String, Map<String, Object>> commands = null;
private String description = null;
private List<String> authors = null;
private String website = null;
private String prefix = null;
private boolean database = false;
private PluginLoadOrder order = PluginLoadOrder.POSTWORLD;
private List<Permission> permissions = null;
private Map<?, ?> lazyPermissions = null;
private PermissionDefault defaultPerm = PermissionDefault.OP;
public PluginDescriptionFile(final InputStream stream) throws InvalidDescriptionException {
loadMap(asMap(yaml.load(stream)));
}
/**
* Loads a PluginDescriptionFile from the specified reader
*
* @param reader The reader
* @throws InvalidDescriptionException If the PluginDescriptionFile is
* invalid
*/
public PluginDescriptionFile(final Reader reader) throws InvalidDescriptionException {
loadMap(asMap(yaml.load(reader)));
}
/**
* Creates a new PluginDescriptionFile with the given detailed
*
* @param pluginName Name of this plugin
* @param pluginVersion Version of this plugin
* @param mainClass Full location of the main class of this plugin
*/
public PluginDescriptionFile(final String pluginName, final String pluginVersion, final String mainClass) {
name = pluginName.replace(' ', '_');
version = pluginVersion;
main = mainClass;
}
/**
* Gives the name of the plugin. This name is a unique identifier for
* plugins.
* <ul>
* <li>Must consist of all alphanumeric characters, underscores, hyphon,
* and period (a-z,A-Z,0-9, _.-). Any other character will cause the
* plugin.yml to fail loading.
* <li>Used to determine the name of the plugin's data folder. Data
* folders are placed in the ./plugins/ directory by default, but this
* behavior should not be relied on. {@link Plugin#getDataFolder()}
* should be used to reference the data folder.
* <li>It is good practice to name your jar the same as this, for example
* 'MyPlugin.jar'.
* <li>Case sensitive.
* <li>The is the token referenced in {@link #getDepend()}, {@link
* #getSoftDepend()}, and {@link #getLoadBefore()}.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>name</code>.
* <p>
* Example:<blockquote><pre>name: MyPlugin</pre></blockquote>
*
* @return the name of the plugin
*/
public String getName() {
return name;
}
/**
* Gives the version of the plugin.
* <ul>
* <li>Version is an arbitrary string, however the most common format is
* MajorRelease.MinorRelease.Build (eg: 1.4.1).
* <li>Typically you will increment this every time you release a new
* feature or bug fix.
* <li>Displayed when a user types <code>/version PluginName</code>
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>version</code>.
* <p>
* Example:<blockquote><pre>version: 1.4.1</pre></blockquote>
*
* @return the version of the plugin
*/
public String getVersion() {
return version;
}
/**
* Gives the fully qualified name of the main class for a plugin. The
* format should follow the {@link ClassLoader#loadClass(String)} syntax
* to successfully be resolved at runtime. For most plugins, this is the
* class that extends {@link JavaPlugin}.
* <ul>
* <li>This must contain the full namespace including the class file
* itself.
* <li>If your namespace is <code>org.bukkit.plugin</code>, and your class
* file is called <code>MyPlugin</code> then this must be
* <code>org.bukkit.plugin.MyPlugin</code>
* <li>No plugin can use <code>org.bukkit.</code> as a base package for
* <b>any class</b>, including the main class.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>main</code>.
* <p>
* Example:
* <blockquote><pre>main: org.bukkit.plugin.MyPlugin</pre></blockquote>
*
* @return the fully qualified main class for the plugin
*/
public String getMain() {
return main;
}
/**
* Gives a human-friendly description of the functionality the plugin
* provides.
* <ul>
* <li>The description can have multiple lines.
* <li>Displayed when a user types <code>/version PluginName</code>
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>description</code>.
* <p>
* Example:
* <blockquote><pre>description: This plugin is so 31337. You can set yourself on fire.</pre></blockquote>
*
* @return description of this plugin, or null if not specified
*/
public String getDescription() {
return description;
}
/**
* Gives the phase of server startup that the plugin should be loaded.
* <ul>
* <li>Possible values are in {@link PluginLoadOrder}.
* <li>Defaults to {@link PluginLoadOrder#POSTWORLD}.
* <li>Certain caveats apply to each phase.
* <li>When different, {@link #getDepend()}, {@link #getSoftDepend()}, and
* {@link #getLoadBefore()} become relative in order loaded per-phase.
* If a plugin loads at <code>STARTUP</code>, but a dependency loads
* at <code>POSTWORLD</code>, the dependency will not be loaded before
* the plugin is loaded.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>load</code>.
* <p>
* Example:<blockquote><pre>load: STARTUP</pre></blockquote>
*
* @return the phase when the plugin should be loaded
*/
public PluginLoadOrder getLoad() {
return order;
}
/**
* Gives the list of authors for the plugin.
* <ul>
* <li>Gives credit to the developer.
* <li>Used in some server error messages to provide helpful feedback on
* who to contact when an error occurs.
* <li>A bukkit.org forum handle or email address is recommended.
* <li>Is displayed when a user types <code>/version PluginName</code>
* <li><code>authors</code> must be in <a
* href="http://en.wikipedia.org/wiki/YAML#Lists">YAML list
* format</a>.
* </ul>
* <p>
* In the plugin.yml, this has two entries, <code>author</code> and
* <code>authors</code>.
* <p>
* Single author example:
* <blockquote><pre>author: CaptainInflamo</pre></blockquote>
* Multiple author example:
* <blockquote><pre>authors: [Cogito, verrier, EvilSeph]</pre></blockquote>
* When both are specified, author will be the first entry in the list, so
* this example:
* <blockquote><pre>author: Grum
*authors:
*- feildmaster
*- amaranth</pre></blockquote>
* Is equivilant to this example:
* <blockquote><pre>authors: [Grum, feildmaster, aramanth]<pre></blockquote>
*
* @return an immutable list of the plugin's authors
*/
public List<String> getAuthors() {
return authors;
}
/**
* Gives the plugin's or plugin's author's website.
* <ul>
* <li>A link to the Curse page that includes documentation and downloads
* is highly recommended.
* <li>Displayed when a user types <code>/version PluginName</code>
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>website</code>.
* <p>
* Example:
* <blockquote><pre>website: http://www.curse.com/server-mods/minecraft/myplugin</pre></blockquote>
*
* @return description of this plugin, or null if not specified
*/
public String getWebsite() {
return website;
}
/**
* Gives if the plugin uses a database.
* <ul>
* <li>Using a database is non-trivial.
* <li>Valid values include <code>true</code> and <code>false</code>
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>database</code>.
* <p>
* Example:
* <blockquote><pre>database: false</pre></blockquote>
*
* @return if this plugin requires a database
* @see Plugin#getDatabase()
*/
public boolean isDatabaseEnabled() {
return database;
}
/**
* Gives a list of other plugins that the plugin requires.
* <ul>
* <li>Use the value in the {@link #getName()} of the target plugin to
* specify the dependency.
* <li>If any plugin listed here is not found, your plugin will fail to
* load at startup.
* <li>If multiple plugins list each other in <code>depend</code>,
* creating a network with no individual plugin does not list another
* plugin in the <a
* href=https://en.wikipedia.org/wiki/Circular_dependency>network</a>,
* all plugins in that network will fail.
* <li><code>depend</code> must be in must be in <a
* href="http://en.wikipedia.org/wiki/YAML#Lists">YAML list
* format</a>.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>depend</code>.
* <p>
* Example:
* <blockquote><pre>depend:
*- OnePlugin
*- AnotherPlugin</pre></blockquote>
*
* @return immutable list of the plugin's dependencies
*/
public List<String> getDepend() {
return depend;
}
/**
* Gives a list of other plugins that the plugin requires for full
* functionality. The {@link PluginManager} will make best effort to treat
* all entries here as if they were a {@link #getDepend() dependency}, but
* will never fail because of one of these entries.
* <ul>
* <li>Use the value in the {@link #getName()} of the target plugin to
* specify the dependency.
* <li>When an unresolvable plugin is listed, it will be ignored and does
* not affect load order.
* <li>When a circular dependency occurs (a network of plugins depending
* or soft-dependending each other), it will arbitrarily choose a
* plugin that can be resolved when ignoring soft-dependencies.
* <li><code>softdepend</code> must be in <a
* href="http://en.wikipedia.org/wiki/YAML#Lists">YAML list
* format</a>.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>softdepend</code>.
* <p>
* Example:
* <blockquote><pre>softdepend: [OnePlugin, AnotherPlugin]</pre></blockquote>
*
* @return immutable list of the plugin's preferred dependencies
*/
public List<String> getSoftDepend() {
return softDepend;
}
/**
* Gets the list of plugins that should consider this plugin a
* soft-dependency.
* <ul>
* <li>Use the value in the {@link #getName()} of the target plugin to
* specify the dependency.
* <li>The plugin should load before any other plugins listed here.
* <li>Specifying another plugin here is strictly equivalent to having the
* specified plugin's {@link #getSoftDepend()} include {@link
* #getName() this plugin}.
* <li><code>loadbefore</code> must be in <a
* href="http://en.wikipedia.org/wiki/YAML#Lists">YAML list
* format</a>.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>loadbefore</code>.
* <p>
* Example:
* <blockquote><pre>loadbefore:
*- OnePlugin
*- AnotherPlugin</pre></blockquote>
*
* @return immutable list of plugins that should consider this plugin a
* soft-dependency
*/
public List<String> getLoadBefore() {
return loadBefore;
}
/**
* Gives the token to prefix plugin-specific logging messages with.
* <ul>
* <li>This includes all messages using {@link Plugin#getLogger()}.
* <li>If not specified, the server uses the plugin's {@link #getName()
* name}.
* <li>This should clearly indicate what plugin is being logged.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>prefix</code>.
* <p>
* Example:<blockquote><pre>prefix: ex-why-zee</pre></blockquote>
*
* @return the prefixed logging token, or null if not specified
*/
public String getPrefix() {
return prefix;
}
/**
* Gives the map of command-name to command-properties. Each entry in this
* map corresponds to a single command and the respective values are the
* properties of the command. Each property, <i>with the exception of
* aliases</i>, can be defined at runtime using methods in {@link
* PluginCommand} and are defined here only as a convenience.
* <table border=1>
* <tr>
* <th>Node</th>
* <th>Method</th>
* <th>Type</th>
* <th>Description</th>
* <th>Example</th>
* </tr><tr>
* <td><code>description</code></td>
* <td>{@link PluginCommand#setDescription(String)}</td>
* <td>String</td>
* <td>A user-friendly description for a command. It is useful for
* documentation purposes as well as in-game help.</td>
* <td><blockquote><pre>description: Set yourself on fire</pre></blockquote></td>
* </tr><tr>
* <td><code>aliases</code></td>
* <td>{@link PluginCommand#setAliases(List)}</td>
* <td>String or <a
* href="http://en.wikipedia.org/wiki/YAML#Lists">List</a> of
* strings</td>
* <td>Alternative command names, with special usefulness for commands
* that are already registered. <i>Aliases are not effective when
* defined at runtime,</i> so the plugin description file is the
* only way to have them properly defined.
* <p>
* Note: Command aliases may not have a colon in them.</td>
* <td>Single alias format:
* <blockquote><pre>aliases: combust_me</pre></blockquote> or
* multiple alias format:
* <blockquote><pre>aliases: [combust_me, combustMe]</pre></blockquote></td>
* </tr><tr>
* <td><code>permission</code></td>
* <td>{@link PluginCommand#setPermission(String)}</td>
* <td>String</td>
* <td>The name of the {@link Permission} required to use the command.
* A user without the permission will receive the specified
* message (see {@linkplain
* PluginCommand#setPermissionMessage(String) below}), or a
* standard one if no specific message is defined. Without the
* permission node, no {@link
* PluginCommand#setExecutor(CommandExecutor) CommandExecutor} or
* {@link PluginCommand#setTabCompleter(TabCompleter)
* TabCompleter} will be called.</td>
* <td><blockquote><pre>permission: inferno.flagrate</pre></blockquote></td>
* </tr><tr>
* <td><code>permission-message</code></td>
* <td>{@link PluginCommand#setPermissionMessage(String)}</td>
* <td>String</td>
* <td><ul>
* <li>Displayed to a player that attempts to use a command, but
* does not have the required permission. See {@link
* PluginCommand#getPermission() above}.
* <li><permission> is a macro that is replaced with the
* permission node required to use the command.
* <li>Using empty quotes is a valid way to indicate nothing
* should be displayed to a player.
* </ul></td>
* <td><blockquote><pre>permission-message: You do not have /<permission></pre></blockquote></td>
* </tr><tr>
* <td><code>usage</code></td>
* <td>{@link PluginCommand#setUsage(String)}</td>
* <td>String</td>
* <td>This message is displayed to a player when the {@link
* PluginCommand#setExecutor(CommandExecutor)} {@linkplain
* CommandExecutor#onCommand(CommandSender,Command,String,String[])
* returns false}. <command> is a macro that is replaced
* the command issued.</td>
* <td><blockquote><pre>usage: Syntax error! Perhaps you meant /<command> PlayerName?</pre></blockquote>
* It is worth noting that to use a colon in a yaml, like
* <code>`usage: Usage: /god [player]'</code>, you need to
* <a href="http://yaml.org/spec/current.html#id2503232">surround
* the message with double-quote</a>:
* <blockquote><pre>usage: "Usage: /god [player]"</pre></blockquote></td>
* </tr>
* </table>
* The commands are structured as a hiearchy of <a
* href="http://yaml.org/spec/current.html#id2502325">nested mappings</a>.
* The primary (top-level, no intendentation) node is
* `<code>commands</code>', while each individual command name is
* indented, indicating it maps to some value (in our case, the
* properties of the table above).
* <p>
* Here is an example bringing together the piecemeal examples above, as
* well as few more definitions:<blockquote><pre>
*commands:
* flagrate:
* description: Set yourself on fire.
* aliases: [combust_me, combustMe]
* permission: inferno.flagrate
* permission-message: You do not have /<permission>
* usage: Syntax error! Perhaps you meant /<command> PlayerName?
* burningdeaths:
* description: List how many times you have died by fire.
* aliases:
* - burning_deaths
* - burningDeaths
* permission: inferno.burningdeaths
* usage: |
* /<command> [player]
* Example: /<command> - see how many times you have burned to death
* Example: /<command> CaptainIce - see how many times CaptainIce has burned to death
* # The next command has no description, aliases, etc. defined, but is still valid
* # Having an empty declaration is useful for defining the description, permission, and messages from a configuration dynamically
* apocalypse:
*</pre></blockquote>
* Note: Command names may not have a colon in their name.
*
* @return the commands this plugin will register
*/
public Map<String, Map<String, Object>> getCommands() {
return commands;
}
/**
* Gives the list of permissions the plugin will register at runtime,
* immediately proceding enabling. The format for defining permissions is
* a map from permission name to properties. To represent a map without
* any specific property, empty <a
* href="http://yaml.org/spec/current.html#id2502702">curly-braces</a> (
* <code>{}</code> ) may be used (as a null value is not
* accepted, unlike the {@link #getCommands() commands} above).
* <p>
* A list of optional properties for permissions:
* <table border=1>
* <tr>
* <th>Node</th>
* <th>Description</th>
* <th>Example</th>
* </tr><tr>
* <td><code>description</code></td>
* <td>Plaintext (user-friendly) description of what the permission
* is for.</td>
* <td><blockquote><pre>description: Allows you to set yourself on fire</pre></blockquote></td>
* </tr><tr>
* <td><code>default</code></td>
* <td>The default state for the permission, as defined by {@link
* Permission#getDefault()}. If not defined, it will be set to
* the value of {@link PluginDescriptionFile#getPermissionDefault()}.
* <p>
* For reference:<ul>
* <li><code>true</code> - Represents a positive assignment to
* {@link Permissible permissibles}.
* <li><code>false</code> - Represents no assignment to {@link
* Permissible permissibles}.
* <li><code>op</code> - Represents a positive assignment to
* {@link Permissible#isOp() operator permissibles}.
* <li><code>notop</code> - Represents a positive assignment to
* {@link Permissible#isOp() non-operator permissibiles}.
* </ul></td>
* <td><blockquote><pre>default: true</pre></blockquote></td>
* </tr><tr>
* <td><code>children</code></td>
* <td>Allows other permissions to be set as a {@linkplain
* Permission#getChildren() relation} to the parent permission.
* When a parent permissions is assigned, child permissions are
* respectively assigned as well.
* <ul>
* <li>When a parent permission is assigned negatively, child
* permissions are assigned based on an inversion of their
* association.
* <li>When a parent permission is assigned positively, child
* permissions are assigned based on their association.
* </ul>
* <p>
* Child permissions may be defined in a number of ways:<ul>
* <li>Children may be defined as a <a
* href="http://en.wikipedia.org/wiki/YAML#Lists">list</a> of
* names. Using a list will treat all children associated
* positively to their parent.
* <li>Children may be defined as a map. Each permission name maps
* to either a boolean (representing the association), or a
* nested permission definition (just as another permission).
* Using a nested definition treats the child as a positive
* association.
* <li>A nested permission definition must be a map of these same
* properties. To define a valid nested permission without
* defining any specific property, empty curly-braces (
* <code>{}</code> ) must be used.
* <li>A nested permission may carry it's own nested permissions
* as children, as they may also have nested permissions, and
* so forth. There is no direct limit to how deep the
* permission tree is defined.
* </ul></td>
* <td>As a list:
* <blockquote><pre>children: [inferno.flagrate, inferno.burningdeaths]</pre></blockquote>
* Or as a mapping:
* <blockquote><pre>children:
* inferno.flagrate: true
* inferno.burningdeaths: true</pre></blockquote>
* An additional example showing basic nested values can be seen
* <a href="doc-files/permissions-example_plugin.yml">here</a>.
* </td>
* </tr>
* </table>
* The permissions are structured as a hiearchy of <a
* href="http://yaml.org/spec/current.html#id2502325">nested mappings</a>.
* The primary (top-level, no intendentation) node is
* `<code>permissions</code>', while each individual permission name is
* indented, indicating it maps to some value (in our case, the
* properties of the table above).
* <p>
* Here is an example using some of the properties:<blockquote><pre>
*permissions:
* inferno.*:
* description: Gives access to all Inferno commands
* children:
* inferno.flagrate: true
* inferno.burningdeaths: true
* inferno.flagate:
* description: Allows you to ignite yourself
* default: true
* inferno.burningdeaths:
* description: Allows you to see how many times you have burned to death
* default: true
*</pre></blockquote>
* Another example, with nested definitions, can be found <a
* href="doc-files/permissions-example_plugin.yml">here</a>.
*/
public List<Permission> getPermissions() {
if (permissions == null) {
if (lazyPermissions == null) {
permissions = ImmutableList.<Permission>of();
} else {
permissions = ImmutableList.copyOf(Permission.loadPermissions(lazyPermissions, "Permission node '%s' in plugin description file for " + getFullName() + " is invalid", defaultPerm));
lazyPermissions = null;
}
}
return permissions;
}
/**
* Gives the default {@link Permission#getDefault() default} state of
* {@link #getPermissions() permissions} registered for the plugin.
* <ul>
* <li>If not specified, it will be {@link PermissionDefault#OP}.
* <li>It is matched using {@link PermissionDefault#getByName(String)}
* <li>It only affects permissions that do not define the
* <code>default</code> node.
* <li>It may be any value in {@link PermissionDefault}.
* </ul>
* <p>
* In the plugin.yml, this entry is named <code>default-permission</code>.
* <p>
* Example:<blockquote><pre>default-permission: NOT_OP</pre></blockquote>
*
* @return the default value for the plugin's permissions
*/
public PermissionDefault getPermissionDefault() {
return defaultPerm;
}
/**
* Returns the name of a plugin, including the version. This method is
* provided for convenience; it uses the {@link #getName()} and {@link
* #getVersion()} entries.
*
* @return a descriptive name of the plugin and respective version
*/
public String getFullName() {
return name + " v" + version;
}
/**
* @deprecated unused
*/
@Deprecated
public String getClassLoaderOf() {
return classLoaderOf;
}
public void setDatabaseEnabled(boolean database) {
this.database = database;
}
/**
* Saves this PluginDescriptionFile to the given writer
*
* @param writer Writer to output this file to
*/
public void save(Writer writer) {
yaml.dump(saveMap(), writer);
}
private void loadMap(Map<?, ?> map) throws InvalidDescriptionException {
try {
name = map.get("name").toString();
if (!name.matches("^[A-Za-z0-9 _.-]+$")) {
throw new InvalidDescriptionException("name '" + name + "' contains invalid characters.");
}
name = name.replace(' ', '_');
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "name is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "name is of wrong type");
}
try {
version = map.get("version").toString();
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "version is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "version is of wrong type");
}
try {
main = map.get("main").toString();
if (main.startsWith("org.bukkit.")) {
throw new InvalidDescriptionException("main may not be within the org.bukkit namespace");
}
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "main is not defined");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "main is of wrong type");
}
if (map.get("commands") != null) {
ImmutableMap.Builder<String, Map<String, Object>> commandsBuilder = ImmutableMap.<String, Map<String, Object>>builder();
try {
for (Map.Entry<?, ?> command : ((Map<?, ?>) map.get("commands")).entrySet()) {
ImmutableMap.Builder<String, Object> commandBuilder = ImmutableMap.<String, Object>builder();
if (command.getValue() != null) {
for (Map.Entry<?, ?> commandEntry : ((Map<?, ?>) command.getValue()).entrySet()) {
if (commandEntry.getValue() instanceof Iterable) {
// This prevents internal alias list changes
ImmutableList.Builder<Object> commandSubList = ImmutableList.<Object>builder();
for (Object commandSubListItem : (Iterable<?>) commandEntry.getValue()) {
if (commandSubListItem != null) {
commandSubList.add(commandSubListItem);
}
}
commandBuilder.put(commandEntry.getKey().toString(), commandSubList.build());
} else if (commandEntry.getValue() != null) {
commandBuilder.put(commandEntry.getKey().toString(), commandEntry.getValue());
}
}
}
commandsBuilder.put(command.getKey().toString(), commandBuilder.build());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "commands are of wrong type");
}
commands = commandsBuilder.build();
}
if (map.get("class-loader-of") != null) {
classLoaderOf = map.get("class-loader-of").toString();
}
if (map.get("depend") != null) {
ImmutableList.Builder<String> dependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("depend")) {
dependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "depend is of wrong type");
} catch (NullPointerException e) {
throw new InvalidDescriptionException(e, "invalid dependency format");
}
depend = dependBuilder.build();
}
if (map.get("softdepend") != null) {
ImmutableList.Builder<String> softDependBuilder = ImmutableList.<String>builder();
try {
for (Object dependency : (Iterable<?>) map.get("softdepend")) {
softDependBuilder.add(dependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "softdepend is of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "invalid soft-dependency format");
}
softDepend = softDependBuilder.build();
}
if (map.get("loadbefore") != null) {
ImmutableList.Builder<String> loadBeforeBuilder = ImmutableList.<String>builder();
try {
for (Object predependency : (Iterable<?>) map.get("loadbefore")) {
loadBeforeBuilder.add(predependency.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "loadbefore is of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "invalid load-before format");
}
loadBefore = loadBeforeBuilder.build();
}
if (map.get("database") != null) {
try {
database = (Boolean) map.get("database");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "database is of wrong type");
}
}
if (map.get("website") != null) {
website = map.get("website").toString();
}
if (map.get("description") != null) {
description = map.get("description").toString();
}
if (map.get("load") != null) {
try {
order = PluginLoadOrder.valueOf(((String) map.get("load")).toUpperCase().replaceAll("\\W", ""));
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "load is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "load is not a valid choice");
}
}
if (map.get("authors") != null) {
ImmutableList.Builder<String> authorsBuilder = ImmutableList.<String>builder();
if (map.get("author") != null) {
authorsBuilder.add(map.get("author").toString());
}
try {
for (Object o : (Iterable<?>) map.get("authors")) {
authorsBuilder.add(o.toString());
}
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "authors are of wrong type");
} catch (NullPointerException ex) {
throw new InvalidDescriptionException(ex, "authors are improperly defined");
}
authors = authorsBuilder.build();
} else if (map.get("author") != null) {
authors = ImmutableList.of(map.get("author").toString());
} else {
authors = ImmutableList.<String>of();
}
if (map.get("default-permission") != null) {
try {
defaultPerm = PermissionDefault.getByName(map.get("default-permission").toString());
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "default-permission is of wrong type");
} catch (IllegalArgumentException ex) {
throw new InvalidDescriptionException(ex, "default-permission is not a valid choice");
}
}
try {
lazyPermissions = (Map<?, ?>) map.get("permissions");
} catch (ClassCastException ex) {
throw new InvalidDescriptionException(ex, "permissions are of the wrong type");
}
if (map.get("prefix") != null) {
prefix = map.get("prefix").toString();
}
}
private Map<String, Object> saveMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", name);
map.put("main", main);
map.put("version", version);
map.put("database", database);
map.put("order", order.toString());
map.put("default-permission", defaultPerm.toString());
if (commands != null) {
map.put("command", commands);
}
if (depend != null) {
map.put("depend", depend);
}
if (softDepend != null) {
map.put("softdepend", softDepend);
}
if (website != null) {
map.put("website", website);
}
if (description != null) {
map.put("description", description);
}
if (authors.size() == 1) {
map.put("author", authors.get(0));
} else if (authors.size() > 1) {
map.put("authors", authors);
}
if (classLoaderOf != null) {
map.put("class-loader-of", classLoaderOf);
}
if (prefix != null) {
map.put("prefix", prefix);
}
return map;
}
private Map<?,?> asMap(Object object) throws InvalidDescriptionException {
if (object instanceof Map) {
return (Map<?,?>) object;
}
throw new InvalidDescriptionException(object + " is not properly structured.");
}
}
| gpl-3.0 |
jbgi/replics | swans/jist/swans/app/AppInterface.java | 1977 | //////////////////////////////////////////////////
// JIST (Java In Simulation Time) Project
// Timestamp: <AppInterface.java Wed 2005/03/09 15:45:35 barr rimbase.rimonbarr.com>
//
// Copyright (C) 2004 by Cornell University
// All rights reserved.
// Refer to LICENSE for terms and conditions of use.
package jist.swans.app;
import jist.swans.trans.TransInterface;
import jist.swans.app.lang.SimtimeThread;
import jist.runtime.JistAPI;
/**
* Interface for Application entities.
*
* @author Rimon Barr <barr+jist@cs.cornell.edu>
* @version $Id: AppInterface.java,v 1.1 2007/04/09 18:49:48 drchoffnes Exp $
* @since SWANS1.0
*/
public interface AppInterface extends JistAPI.Proxiable
{
/**
* Run application.
*/
void run();
/**
* Run application.
*
* @param args command-line parameters
*/
void run(String[] args);
/**
* Application that supports TCP sockets.
*/
public static interface TcpApp
{
/**
* Return application TCP entity.
*
* @return application TCP entity
* @throws JistAPI.Continuation not thrown; marker for rewriter
*/
TransInterface.TransTcpInterface getTcpEntity() throws JistAPI.Continuation;
}
/**
* Application that supports UDP sockets.
*/
public static interface UdpApp
{
/**
* Return application UDP entity.
*
* @return application UDP entity
* @throws JistAPI.Continuation not thrown; marker for rewriter
*/
TransInterface.TransUdpInterface getUdpEntity() throws JistAPI.Continuation;
}
/**
* Application that supports threading.
*/
public interface ThreadedApp
{
/**
* Get current thread from thread context.
*
* @return thread entity
*/
public SimtimeThread getCurrentThread();
/**
* Set current thread in thread context.
*
* @param thread thread entity
*/
public void setCurrentThread(SimtimeThread t);
}
} // interface: AppInterface
| gpl-3.0 |
LukeCollins-net/GitHub-API-Tool | src/main/net/lukecollins/dev/github/Trees.java | 469 | /*******************************************************************************
* Copyright (c) 2017 Luke Collins and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the license
* which accompanies this distribution
* Contributors:
* Luke Collins
*******************************************************************************/
package net.lukecollins.dev.github;
public class Trees {
}
| gpl-3.0 |
triguero/Keel3.0 | src/keel/Algorithms/RST_Learning/KNNClassifier.java | 11952 | /***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
A. Fernández (alberto.fernandez@ujaen.es)
S. García (sglopez@ujaen.es)
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Luengo (julianlm@decsai.ugr.es)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
/**
*
* File: KNNClassifier.java
*
* A KNN classifier with the capabilities of selecting instances and features.
* For efficiency, employs unsquared euclidean distance.
*
* @author Written by Joaquín Derrac (University of Granada) 20/04/2010
* @version 1.0
* @since JDK1.5
*
*/
package keel.Algorithms.RST_Learning;
import java.util.Arrays;
public class KNNClassifier{
private static int K;
private static double data[][];
private static int output[];
private static int instances;
private static int features;
private static int nClasses;
private static int IS[];
private static int FS[];
private static int nearestN [];
private static double minDist [];
/**
* Sets the number of classes in the data
*
* @param value Number of classes
*/
public static void setClasses(int value){
nClasses=value;
}//end-method
/**
* Sets the K value
*
* @param value K value
*/
public static void setK(int value){
K=value;
nearestN = new int[K];
minDist = new double[K];
}//end-method
/**
* Loads the training data into the classifier
*
* @param newData Data represented with continuous values
*/
public static void setData(double newData[][]){
instances = newData.length;
features = newData[0].length;
data = new double [instances][features];
for(int i=0;i<instances;i++){
for(int j=0;j<features;j++){
data[i][j]=newData[i][j];
}
}
IS = new int [instances];
FS = new int [features];
Arrays.fill(IS, 1);
Arrays.fill(FS, 1);
}//end-method
/**
* Loads the training output into the classifier
*
* @param newOutput Output attribute of the training data
*/
public static void setOutput(int newOutput[]){
output=new int [data.length];
System.arraycopy(newOutput,0,output, 0, data.length);
}//end-method
/**
* Sets the vector of instances selected
*
* @param selected Vector of instances selected
*/
public static void setInstances(int selected []){
for(int i=0; i< instances;i++){
IS[i]=selected[i];
}
}//end-method
/**
* Sets the vector of features selected
*
* @param selected Vector of features selected
*/
public static void setFeatures(int selected []){
for(int i=0; i< features ;i++){
FS[i]=selected[i];
}
}//end-method
public static void setAllInstances(){
Arrays.fill(IS,1);
}//end-method
public static void setAllFeatures(){
Arrays.fill(FS,1);
}//end-method
/**
* Estimates the LVO (Leave-one-out) accuracy of the classifier
* over the training data.
*
* @return Accuracy estimated
*/
public static double accuracy(){
int hits;
int test;
double acc;
hits=0;
for (int i=0; i<data.length; i++) {
test=classifyTrainingInstance(i);
if(test==output[i]){
hits++;
}
}
acc=(double)((double)hits/(double)data.length);
return acc;
}//end-method
/**
* Classifies a new example
*
* @param example Example to classify
* @return Class of the example
*/
public static int classifyNewInstance(double example[]){
int value;
if(K==1){
value=classifyInstance(example);
}
else{
value=classifyInstanceK(example);
}
return value;
}//end-method
/**
* Classifies an instance by means of a 1-NN classifier
*
* @param example Example to classify
* @return Class of the example
*/
private static int classifyInstance(double example[]){
double dist;
int near=-1;
double minD=Double.MAX_VALUE;
//1-NN Method starts here
for (int i=0; i<data.length; i++) {
if(IS[i]==1){
dist = newEuclideanDistance(example,i);
//see if it's nearer than our previous selected neigbours
if (dist < minD) {
minD = dist;
near = i;
}
}
}
if(near==-1){
return -1;
}
return output[near];
}//end-method
/**
* Classifies an instance by means of a K-NN classifier
*
* @param example Example to classify
* @return Class of the example
*/
private static int classifyInstanceK(double example[]){
int selectedClasses[];
double dist;
int prediction;
int predictionValue;
boolean stop;
Arrays.fill(nearestN, -1);
Arrays.fill(minDist, Double.MAX_VALUE);
//KNN Method starts here
for (int i=0; i<instances; i++) {
if(IS[i]==1){
dist = newEuclideanDistance(example,i);
//see if it's nearer than our previous selected neighbors
stop=false;
for(int j=0;j<K && !stop;j++){
if (dist < minDist[j]) {
for (int l = K - 1; l >= j+1; l--) {
minDist[l] = minDist[l - 1];
nearestN[l] = nearestN[l - 1];
}
minDist[j] = dist;
nearestN[j] = i;
stop=true;
}
}
}
}
//we have check all the instances... see what is the most present class
selectedClasses= new int[nClasses];
for (int i=0; i<nClasses; i++) {
selectedClasses[i] = 0;
}
for (int i=0; i<K; i++) {
selectedClasses[output[nearestN[i]]]+=1;
}
prediction=0;
predictionValue=selectedClasses[0];
for (int i=1; i<nClasses; i++) {
if (predictionValue < selectedClasses[i]) {
predictionValue = selectedClasses[i];
prediction = i;
}
}
return prediction;
}//end-method
/**
* Classifies a training example
*
* @param index Training example to classify
* @return Class of the example
*/
public static int classifyTrainingInstance(int index){
int value;
int aux;
//leave-one-out
aux=IS[index];
IS[index]=0;
if(K==1){
value=classifyTrainInstance(index);
}
else{
value=classifyTrainInstanceK(index);
}
IS[index]=aux;
return value;
}//end-method
/**
* Classifies a training instance by means of a 1-NN classifier
*
* @param index Example to classify
* @return Class of the example
*/
private static int classifyTrainInstance(int index){
double dist;
int near=-1;
double minD=Double.MAX_VALUE;
//1-NN Method starts here
for (int i=0; i<data.length; i++) {
if(IS[i]==1){
dist = euclideanDistance(index,i);
//see if it's nearer than our previous selected neigbours
if (dist < minD) {
minD = dist;
near = i;
}
}
}
if(near==-1){
return -1;
}
return output[near];
}//end-method
/**
* Classifies an instance by means of a K-NN classifier
*
* @param instance Example to classify
* @return Class of the example
*/
private static int classifyTrainInstanceK(int index){
int selectedClasses[];
double dist;
int prediction;
int predictionValue;
boolean stop;
Arrays.fill(nearestN, -1);
Arrays.fill(minDist, Double.MAX_VALUE);
//KNN Method starts here
for (int i=0; i<instances; i++) {
if(IS[i]==1){
dist = euclideanDistance(index,i);
//see if it's nearer than our previous selected neighbors
stop=false;
for(int j=0;j<K && !stop;j++){
if (dist < minDist[j]) {
for (int l = K - 1; l >= j+1; l--) {
minDist[l] = minDist[l - 1];
nearestN[l] = nearestN[l - 1];
}
minDist[j] = dist;
nearestN[j] = i;
stop=true;
}
}
}
}
//we have check all the instances... see what is the most present class
selectedClasses= new int[nClasses];
for (int i=0; i<nClasses; i++) {
selectedClasses[i] = 0;
}
for (int i=0; i<K; i++) {
selectedClasses[output[nearestN[i]]]+=1;
}
prediction=0;
predictionValue=selectedClasses[0];
for (int i=1; i<nClasses; i++) {
if (predictionValue < selectedClasses[i]) {
predictionValue = selectedClasses[i];
prediction = i;
}
}
return prediction;
}//end-method
/**
* Euclidean instance between two training instances
*
* @param a First instance
* @param b Second instance
*
* @return Unsquared euclidean distance
*/
private static double euclideanDistance(int a,int b){
double length=0.0;
double value;
for (int i=0; i<data[b].length; i++) {
if(FS[i]==1){
value = data[a][i]-data[b][i];
length += value*value;
}
}
return length;
}//end-method
/**
* Euclidean instance between a training instance and a new example
*
* @param example New example
* @param b Training instance
*
* @return Unsquared euclidean distance
*/
private static double newEuclideanDistance(double example [],int b){
double length=0.0;
double value;
for (int i=0; i<data[b].length; i++) {
if(FS[i]==1){
value = example[i]-data[b][i];
length += value*value;
}
}
return length;
}//end-method
/**
* Computes reduction rates over instances
*
* @return Reduction rate
*/
public static double computeISReduction(){
double count=0;
double result;
for(int i=0;i<instances;i++){
if(IS[i]==1){
count+=1.0;
}
}
result=(double)(count/(double)instances);
result=1.0-result;
return result;
}//end-method
/**
* Computes reduction rates over features
*
* @return Reduction rate
*/
public static double computeFSReduction(){
double count=0;
double result;
for(int i=0;i<features;i++){
if(FS[i]==1){
count+=1.0;
}
}
result=(double)(count/(double)features);
result=1.0-result;
return result;
}//end-method
/**
* Get a vector with the instances currently selected
*
* @return A vector with the instances currently selected
*/
public static int [] getIS(){
return IS;
}//end-method
/**
* Get a vector with the features currently selected
*
* @return A vector with the features currently selected
*/
public static int [] getFS(){
int newFS [];
newFS= new int [FS.length];
for(int i=0;i<FS.length;i++){
newFS[i]=FS[i];
}
return newFS;
}//end-method
public static String printFS(){
String aux="";
for(int i=0;i<FS.length;i++){
aux+=FS[i];
}
return aux;
}//end-method
}//end-class
| gpl-3.0 |
Francescopaolo44/starship | Build/Android/src/com/YourCompany/StarShip/DownloaderActivity.java | 32329 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.YourCompany.StarShip;
import com.android.vending.expansion.zipfile.ZipResourceFile;
import com.android.vending.expansion.zipfile.ZipResourceFile.ZipEntryRO;
import com.google.android.vending.expansion.downloader.Constants;
import com.google.android.vending.expansion.downloader.DownloadProgressInfo;
import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller;
import com.google.android.vending.expansion.downloader.DownloaderServiceMarshaller;
import com.google.android.vending.expansion.downloader.Helpers;
import com.google.android.vending.expansion.downloader.IDownloaderClient;
import com.google.android.vending.expansion.downloader.IDownloaderService;
import com.google.android.vending.expansion.downloader.IStub;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Messenger;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.util.zip.CRC32;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import com.epicgames.ue4.GameActivity;
/**
* This is sample code for a project built against the downloader library. It
* implements the IDownloaderClient that the client marshaler will talk to as
* messages are delivered from the DownloaderService.
*/
public class DownloaderActivity extends Activity implements IDownloaderClient {
private static final String LOG_TAG = "LVLDownloader";
private ProgressBar mPB;
private TextView mStatusText;
private TextView mProgressFraction;
private TextView mProgressPercent;
private TextView mAverageSpeed;
private TextView mTimeRemaining;
private View mDashboard;
private View mCellMessage;
private Button mPauseButton;
private Button mWiFiSettingsButton;
private boolean mStatePaused;
private int mState;
private IDownloaderService mRemoteService;
private IStub mDownloaderClientStub;
private final CharSequence[] OBBSelectItems = { "Use Store Data", "Use Development Data" };
private void setState(int newState) {
if (mState != newState) {
mState = newState;
mStatusText.setText(Helpers.getDownloaderStringResourceIDFromState(newState));
}
}
private void setButtonPausedState(boolean paused) {
mStatePaused = paused;
int stringResourceID = paused ? R.string.text_button_resume :
R.string.text_button_pause;
mPauseButton.setText(stringResourceID);
}
static DownloaderActivity _download;
private Intent OutputData;
/**
* Go through each of the APK Expansion files defined in the structure above
* and determine if the files are present and match the required size. Free
* applications should definitely consider doing this, as this allows the
* application to be launched for the first time without having a network
* connection present. Paid applications that use LVL should probably do at
* least one LVL check that requires the network to be present, so this is
* not as necessary.
*
* @return true if they are present.
*/
boolean expansionFilesDelivered() {
for (OBBData.XAPKFile xf : OBBData.xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion);
GameActivity.Log.debug("Checking for file : " + fileName);
String fileForNewFile = Helpers.generateSaveFileName(this, fileName);
String fileForDevFile = Helpers.generateSaveFileNameDevelopment(this, fileName);
GameActivity.Log.debug("which is really being resolved to : " + fileForNewFile + "\n Or : " + fileForDevFile);
if (!Helpers.doesFileExist(this, fileName, xf.mFileSize, false) &&
!Helpers.doesFileExistDev(this, fileName, xf.mFileSize, false))
return false;
}
return true;
}
boolean onlySingleExpansionFileFound() {
for (OBBData.XAPKFile xf : OBBData.xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion);
GameActivity.Log.debug("Checking for file : " + fileName);
String fileForNewFile = Helpers.generateSaveFileName(this, fileName);
String fileForDevFile = Helpers.generateSaveFileNameDevelopment(this, fileName);
if (Helpers.doesFileExist(this, fileName, xf.mFileSize, false) &&
Helpers.doesFileExistDev(this, fileName, xf.mFileSize, false))
return false;
}
return true;
}
File getFileDetailsCacheFile() {
return new File(this.getExternalFilesDir(null), "cacheFile.txt");
}
boolean expansionFilesUptoData() {
File cacheFile = getFileDetailsCacheFile();
// Read data into an array or something...
Map<String, Long> fileDetailsMap = new HashMap<String, Long>();
if(cacheFile.exists()) {
try {
FileReader fileCache = new FileReader(cacheFile);
BufferedReader bufferedFileCache = new BufferedReader(fileCache);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedFileCache.readLine()) != null) {
lines.add(line);
}
bufferedFileCache.close();
for(String dataLine : lines)
{
GameActivity.Log.debug("Splitting dataLine => " + dataLine);
String[] parts = dataLine.split(",");
fileDetailsMap.put(parts[0], Long.parseLong(parts[1]));
}
}
catch(Exception e)
{
GameActivity.Log.debug("Exception thrown during file details reading.");
e.printStackTrace();
fileDetailsMap.clear();
}
}
for (OBBData.XAPKFile xf : OBBData.xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(this, xf.mIsMain, xf.mFileVersion);
String fileForNewFile = Helpers.generateSaveFileName(this, fileName);
String fileForDevFile = Helpers.generateSaveFileNameDevelopment(this, fileName);
// check to see if time/data on files match cached version
// if not return false
File srcFile = new File(fileForNewFile);
File srcDevFile = new File(fileForDevFile);
long lastModified = srcFile.lastModified();
long lastModifiedDev = srcDevFile.lastModified();
if(!(srcFile.exists() && fileDetailsMap.containsKey(fileName) && lastModified == fileDetailsMap.get(fileName))
&&
!(srcDevFile.exists() && fileDetailsMap.containsKey(fileName) && lastModifiedDev == fileDetailsMap.get(fileName)))
return false;
}
return true;
}
static private void RemoveOBBFile(int OBBToDelete) {
for (OBBData.XAPKFile xf : OBBData.xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(DownloaderActivity._download, xf.mIsMain, xf.mFileVersion);
switch(OBBToDelete)
{
case 0:
String fileForNewFile = Helpers.generateSaveFileName(DownloaderActivity._download, fileName);
File srcFile = new File(fileForNewFile);
srcFile.delete();
break;
case 1:
String fileForDevFile = Helpers.generateSaveFileNameDevelopment(DownloaderActivity._download, fileName);
File srcDevFile = new File(fileForDevFile);
srcDevFile.delete();
break;
}
}
}
private void ProcessOBBFiles()
{
if(GameActivity.Get().VerifyOBBOnStartUp && !expansionFilesUptoData()) {
validateXAPKZipFiles();
} else {
OutputData.putExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_FILES_PRESENT);
setResult(RESULT_OK, OutputData);
finish();
overridePendingTransition(R.anim.noaction, R.anim.noaction);
}
}
/**
* Calculating a moving average for the validation speed so we don't get
* jumpy calculations for time etc.
*/
static private final float SMOOTHING_FACTOR = 0.005f;
/**
* Used by the async task
*/
private boolean mCancelValidation;
/**
* Go through each of the Expansion APK files and open each as a zip file.
* Calculate the CRC for each file and return false if any fail to match.
*
* @return true if XAPKZipFile is successful
*/
void validateXAPKZipFiles() {
AsyncTask<Object, DownloadProgressInfo, Boolean> validationTask = new AsyncTask<Object, DownloadProgressInfo, Boolean>() {
@Override
protected void onPreExecute() {
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_verifying_download);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCancelValidation = true;
}
});
mPauseButton.setVisibility(View.GONE);
// mPauseButton.setText(R.string.text_button_cancel_verify);
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Object... params) {
for (OBBData.XAPKFile xf : OBBData.xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(
DownloaderActivity.this,
xf.mIsMain, xf.mFileVersion);
boolean normalFile = Helpers.doesFileExist(DownloaderActivity.this, fileName, xf.mFileSize, false);
boolean devFile = Helpers.doesFileExistDev(DownloaderActivity.this, fileName, xf.mFileSize, false);
if (!normalFile && !devFile )
return false;
if(normalFile)
{
fileName = Helpers.generateSaveFileName(DownloaderActivity.this, fileName);
}
else
{
fileName = Helpers.generateSaveFileNameDevelopment(DownloaderActivity.this, fileName);
}
ZipResourceFile zrf;
byte[] buf = new byte[1024 * 256];
try {
zrf = new ZipResourceFile(fileName);
ZipEntryRO[] entries = zrf.getAllEntries();
/**
* First calculate the total compressed length
*/
long totalCompressedLength = 0;
for (ZipEntryRO entry : entries) {
totalCompressedLength += entry.mCompressedLength;
}
float averageVerifySpeed = 0;
long totalBytesRemaining = totalCompressedLength;
long timeRemaining;
/**
* Then calculate a CRC for every file in the Zip file,
* comparing it to what is stored in the Zip directory.
* Note that for compressed Zip files we must extract
* the contents to do this comparison.
*/
for (ZipEntryRO entry : entries) {
if (-1 != entry.mCRC32) {
long length = entry.mUncompressedLength;
CRC32 crc = new CRC32();
DataInputStream dis = null;
try {
dis = new DataInputStream(
zrf.getInputStream(entry.mFileName));
long startTime = SystemClock.uptimeMillis();
while (length > 0) {
int seek = (int) (length > buf.length ? buf.length
: length);
dis.readFully(buf, 0, seek);
crc.update(buf, 0, seek);
length -= seek;
long currentTime = SystemClock.uptimeMillis();
long timePassed = currentTime - startTime;
if (timePassed > 0) {
float currentSpeedSample = (float) seek
/ (float) timePassed;
if (0 != averageVerifySpeed) {
averageVerifySpeed = SMOOTHING_FACTOR
* currentSpeedSample
+ (1 - SMOOTHING_FACTOR)
* averageVerifySpeed;
} else {
averageVerifySpeed = currentSpeedSample;
}
totalBytesRemaining -= seek;
timeRemaining = (long) (totalBytesRemaining / averageVerifySpeed);
this.publishProgress(
new DownloadProgressInfo(
totalCompressedLength,
totalCompressedLength
- totalBytesRemaining,
timeRemaining,
averageVerifySpeed)
);
}
startTime = currentTime;
if (mCancelValidation)
return true;
}
if (crc.getValue() != entry.mCRC32) {
Log.e(Constants.TAG,
"CRC does not match for entry: "
+ entry.mFileName);
Log.e(Constants.TAG,
"In file: " + entry.getZipFileName());
return false;
}
} finally {
if (null != dis) {
dis.close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
@Override
protected void onProgressUpdate(DownloadProgressInfo... values) {
onDownloadProgress(values[0]);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
// save details to cache file...
try {
File cacheFile = getFileDetailsCacheFile();
FileWriter fileCache = new FileWriter(cacheFile);
BufferedWriter bufferedFileCache = new BufferedWriter(fileCache);
for (OBBData.XAPKFile xf : OBBData.xAPKS) {
String fileName = Helpers.getExpansionAPKFileName(DownloaderActivity.this, xf.mIsMain, xf.mFileVersion);
String fileForNewFile = Helpers.generateSaveFileName(DownloaderActivity.this, fileName);
String fileForDevFile = Helpers.generateSaveFileNameDevelopment(DownloaderActivity.this, fileName);
GameActivity.Log.debug("Writing details for file : " + fileName);
File srcFile = new File(fileForNewFile);
File srcDevFile = new File(fileForDevFile);
if(srcFile.exists()) {
long lastModified = srcFile.lastModified();
bufferedFileCache.write(fileName);
bufferedFileCache.write(",");
bufferedFileCache.write(new Long(lastModified).toString());
bufferedFileCache.newLine();
GameActivity.Log.debug("Details for file : " + fileName + " with modified time of " + new Long(lastModified).toString() );
}
else {
long lastModified = srcDevFile.lastModified();
bufferedFileCache.write(fileName);
bufferedFileCache.write(",");
bufferedFileCache.write(new Long(lastModified).toString());
bufferedFileCache.newLine();
GameActivity.Log.debug("Details for file : " + fileName + " with modified time of " + new Long(lastModified).toString() );
}
}
bufferedFileCache.close();
}
catch(Exception e)
{
GameActivity.Log.debug("Exception thrown during file details writing.");
e.printStackTrace();
}
/*
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_validation_complete);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OutputData.putExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_FILES_PRESENT);
setResult(RESULT_OK, OutputData);
finish();
}
});
mPauseButton.setText(android.R.string.ok);
*/
OutputData.putExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_FILES_PRESENT);
setResult(RESULT_OK, OutputData);
finish();
} else {
// clear cache file if it exists...
File cacheFile = getFileDetailsCacheFile();
if(cacheFile.exists()) {
cacheFile.delete();
}
mDashboard.setVisibility(View.VISIBLE);
mCellMessage.setVisibility(View.GONE);
mStatusText.setText(R.string.text_validation_failed);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OutputData.putExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_INVALID);
setResult(RESULT_OK, OutputData);
finish();
}
});
mPauseButton.setText(android.R.string.cancel);
}
super.onPostExecute(result);
}
};
validationTask.execute(new Object());
}
/**
* If the download isn't present, we initialize the download UI. This ties
* all of the controls into the remote service calls.
*/
private void initializeDownloadUI() {
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub
(this, OBBDownloaderService.class);
setContentView(R.layout.downloader_progress);
mPB = (ProgressBar) findViewById(R.id.progressBar);
mStatusText = (TextView) findViewById(R.id.statusText);
mProgressFraction = (TextView) findViewById(R.id.progressAsFraction);
mProgressPercent = (TextView) findViewById(R.id.progressAsPercentage);
mAverageSpeed = (TextView) findViewById(R.id.progressAverageSpeed);
mTimeRemaining = (TextView) findViewById(R.id.progressTimeRemaining);
mDashboard = findViewById(R.id.downloaderDashboard);
mCellMessage = findViewById(R.id.approveCellular);
mPauseButton = (Button) findViewById(R.id.pauseButton);
mWiFiSettingsButton = (Button) findViewById(R.id.wifiSettingsButton);
mPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mStatePaused) {
mRemoteService.requestContinueDownload();
} else {
mRemoteService.requestPauseDownload();
}
setButtonPausedState(!mStatePaused);
}
});
mWiFiSettingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
Button resumeOnCell = (Button) findViewById(R.id.resumeOverCellular);
resumeOnCell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mRemoteService.setDownloadFlags(IDownloaderService.FLAGS_DOWNLOAD_OVER_CELLULAR);
mRemoteService.requestContinueDownload();
mCellMessage.setVisibility(View.GONE);
}
});
}
/**
* Called when the activity is first create; we wouldn't create a layout in
* the case where we have the file and are moving to another activity
* without downloading.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GameActivity.Log.debug("Starting DownloaderActivity...");
_download = this;
// Create somewhere to place the output - we'll check this on 'finish' to make sure we are returning 'something'
OutputData = new Intent();
/**
* Both downloading and validation make use of the "download" UI
*/
initializeDownloadUI();
GameActivity.Log.debug("... UI setup. Checking for files.");
/**
* Before we do anything, are the files we expect already here and
* delivered (presumably by Market) For free titles, this is probably
* worth doing. (so no Market request is necessary)
*/
if (!expansionFilesDelivered()) {
GameActivity.Log.debug("... Whoops... missing; go go go download system!");
try {
// Make sure we have a key before we try to start the service
if(OBBDownloaderService.getPublicKeyLength() == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false)
.setTitle("No Google Play Store Key")
.setMessage("No OBB found and no store key to try to download. Please set one up in Android Project Settings")
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
OutputData.putExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_NO_PLAY_KEY);
setResult(RESULT_OK, OutputData);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else
{
Intent launchIntent = DownloaderActivity.this
.getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent(
DownloaderActivity
.this, DownloaderActivity.this.getClass());
intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());
if (launchIntent.getCategories() != null) {
for (String category : launchIntent.getCategories()) {
intentToLaunchThisActivityFromNotification.addCategory(category);
}
}
// Build PendingIntent used to open this activity from
// Notification
PendingIntent pendingIntent = PendingIntent.getActivity(
DownloaderActivity.this,
0, intentToLaunchThisActivityFromNotification,
PendingIntent.FLAG_UPDATE_CURRENT);
// Request to start the download
int startResult = DownloaderClientMarshaller.startDownloadServiceIfRequired(this,
pendingIntent, OBBDownloaderService.class);
if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) {
// The DownloaderService has started downloading the files,
// show progress
initializeDownloadUI();
return;
} // otherwise, download not needed so we fall through to saying all is OK
else
{
OutputData.putExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_FILES_PRESENT);
setResult(RESULT_OK, OutputData);
finish();
}
}
} catch (NameNotFoundException e) {
Log.e(LOG_TAG, "Cannot find own package! MAYDAY!");
e.printStackTrace();
}
} else {
GameActivity.Log.debug("... Can has! Check 'em Dano!");
if(!onlySingleExpansionFileFound()) {
// Do some UI here to figure out which we want to keep
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false)
.setTitle("Select OBB to use")
.setItems(OBBSelectItems, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
DownloaderActivity.RemoveOBBFile(item);
ProcessOBBFiles();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else {
ProcessOBBFiles();
}
}
}
/**
* Connect the stub to our service on start.
*/
@Override
protected void onStart() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(this);
}
super.onStart();
}
@Override
protected void onPause() {
super.onPause();
GameActivity.Log.debug("In onPause");
if(OutputData.getIntExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_NO_RETURN_CODE) == GameActivity.DOWNLOAD_NO_RETURN_CODE)
{
GameActivity.Log.debug("onPause returning that user quit the download.");
OutputData.putExtra(GameActivity.DOWNLOAD_RETURN_NAME, GameActivity.DOWNLOAD_USER_QUIT);
setResult(RESULT_OK, OutputData);
}
}
/**
* Disconnect the stub from our service on stop
*/
@Override
protected void onStop() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.disconnect(this);
}
super.onStop();
setResult(RESULT_OK, OutputData);
}
/**
* Critical implementation detail. In onServiceConnected we create the
* remote service and marshaler. This is how we pass the client information
* back to the service so the client can be properly notified of changes. We
* must do this every time we reconnect to the service.
*/
@Override
public void onServiceConnected(Messenger m) {
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
/**
* The download state should trigger changes in the UI --- it may be useful
* to show the state as being indeterminate at times. This sample can be
* considered a guideline.
*/
@Override
public void onDownloadStateChanged(int newState) {
setState(newState);
boolean showDashboard = true;
boolean showCellMessage = false;
boolean paused;
boolean indeterminate;
switch (newState) {
case IDownloaderClient.STATE_IDLE:
// STATE_IDLE means the service is listening, so it's
// safe to start making calls via mRemoteService.
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_CONNECTING:
case IDownloaderClient.STATE_FETCHING_URL:
showDashboard = true;
paused = false;
indeterminate = true;
break;
case IDownloaderClient.STATE_DOWNLOADING:
paused = false;
showDashboard = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
paused = true;
showDashboard = false;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_NEED_CELLULAR_PERMISSION:
case IDownloaderClient.STATE_PAUSED_WIFI_DISABLED_NEED_CELLULAR_PERMISSION:
showDashboard = false;
paused = true;
indeterminate = false;
showCellMessage = true;
break;
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_PAUSED_ROAMING:
case IDownloaderClient.STATE_PAUSED_SDCARD_UNAVAILABLE:
paused = true;
indeterminate = false;
break;
case IDownloaderClient.STATE_COMPLETED:
showDashboard = false;
paused = false;
indeterminate = false;
validateXAPKZipFiles();
return;
default:
paused = true;
indeterminate = true;
showDashboard = true;
}
int newDashboardVisibility = showDashboard ? View.VISIBLE : View.GONE;
if (mDashboard.getVisibility() != newDashboardVisibility) {
mDashboard.setVisibility(newDashboardVisibility);
}
int cellMessageVisibility = showCellMessage ? View.VISIBLE : View.GONE;
if (mCellMessage.getVisibility() != cellMessageVisibility) {
mCellMessage.setVisibility(cellMessageVisibility);
}
mPB.setIndeterminate(indeterminate);
setButtonPausedState(paused);
}
/**
* Sets the state of the various controls based on the progressinfo object
* sent from the downloader service.
*/
@Override
public void onDownloadProgress(DownloadProgressInfo progress) {
mAverageSpeed.setText(getString(R.string.kilobytes_per_second,
Helpers.getSpeedString(progress.mCurrentSpeed)));
mTimeRemaining.setText(getString(R.string.time_remaining,
Helpers.getTimeRemaining(progress.mTimeRemaining)));
progress.mOverallTotal = progress.mOverallTotal;
mPB.setMax((int) (progress.mOverallTotal >> 8));
mPB.setProgress((int) (progress.mOverallProgress >> 8));
mProgressPercent.setText(Long.toString(progress.mOverallProgress
* 100 /
progress.mOverallTotal) + "%");
mProgressFraction.setText(Helpers.getDownloadProgressString
(progress.mOverallProgress,
progress.mOverallTotal));
}
@Override
protected void onDestroy() {
this.mCancelValidation = true;
super.onDestroy();
}
}
| gpl-3.0 |
fuzzylite/jfuzzylite | jfuzzylite/src/main/java/com/fuzzylite/term/Sigmoid.java | 5250 | /*
jfuzzylite (TM), a fuzzy logic control library in Java.
Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved.
Author: Juan Rada-Vilela, Ph.D. <jcrada@fuzzylite.com>
This file is part of jfuzzylite.
jfuzzylite is free software: you can redistribute it and/or modify it under
the terms of the FuzzyLite License included with the software.
You should have received a copy of the FuzzyLite License along with
jfuzzylite. If not, see <http://www.fuzzylite.com/license/>.
jfuzzylite is a trademark of FuzzyLite Limited.
fuzzylite (R) is a registered trademark of FuzzyLite Limited.
*/
package com.fuzzylite.term;
import com.fuzzylite.Op;
import java.util.Iterator;
import java.util.List;
/**
The Sigmoid class is an edge Term that represents the sigmoid membership
function.
@image html sigmoid.svg
@author Juan Rada-Vilela, Ph.D.
@see Term
@see Variable
@since 4.0
*/
public class Sigmoid extends Term {
/**
Direction is an enumerator that indicates the direction of the sigmoid.
*/
public enum Direction {
/**
`(_/)` increases to the right
*/
Positive,
/**
`(--)` slope is zero
*/
Zero,
/**
`(\\_)` increases to the left
*/
Negative
}
private double inflection, slope;
public Sigmoid() {
this("");
}
public Sigmoid(String name) {
this(name, Double.NaN, Double.NaN);
}
public Sigmoid(String name, double inflection, double slope) {
this(name, inflection, slope, 1.0);
}
public Sigmoid(String name, double inflection, double slope, double height) {
super(name, height);
this.inflection = inflection;
this.slope = slope;
}
/**
Returns the parameters of the term
@return `"inflection slope [height]"`
*/
@Override
public String parameters() {
return Op.join(" ", inflection, slope)
+ (!Op.isEq(height, 1.0) ? " " + Op.str(height) : "");
}
/**
Configures the term with the parameters
@param parameters as `"inflection slope [height]"`
*/
@Override
public void configure(String parameters) {
if (parameters.isEmpty()) {
return;
}
List<String> values = Op.split(parameters, " ");
int required = 2;
if (values.size() < required) {
throw new RuntimeException(String.format(
"[configuration error] term <%s> requires <%d> parameters",
this.getClass().getSimpleName(), required));
}
Iterator<String> it = values.iterator();
setInflection(Op.toDouble(it.next()));
setSlope(Op.toDouble(it.next()));
if (values.size() > required) {
setHeight(Op.toDouble(it.next()));
}
}
/**
Computes the membership function evaluated at `x`
@param x
@return ` h / (1 + \exp(-s(x-i)))`
where `h` is the height of the Term,
`s` is the slope of the Sigmoid,
`i` is the inflection of the Sigmoid
*/
@Override
public double membership(double x) {
if (Double.isNaN(x)) {
return Double.NaN;
}
return height * 1.0 / (1.0 + Math.exp(-slope * (x - inflection)));
}
@Override
public double tsukamoto(double activationDegree, double minimum, double maximum) {
double w = activationDegree;
double z;
if (Op.isEq(w, 1.0)) {
if (Op.isGE(slope, 0.0)) {
z = maximum;
} else {
z = minimum;
}
} else if (Op.isEq(w, 0.0)) {
if (Op.isGE(slope, 0.0)) {
z = minimum;
} else {
z = maximum;
}
} else {
double a = slope;
double b = inflection;
z = b + (Math.log(1.0 / w - 1.0) / -a);
}
return z;
}
@Override
public boolean isMonotonic() {
return true;
}
/**
Gets the inflection of the sigmoid
@return the inflection of the sigmoid
*/
public double getInflection() {
return inflection;
}
/**
Sets the inflection of the sigmoid
@param inflection is the inflection of the sigmoid
*/
public void setInflection(double inflection) {
this.inflection = inflection;
}
/**
Gets the slope of the sigmoid
@return the slope of the sigmoid
*/
public double getSlope() {
return slope;
}
/**
Sets the slope of the sigmoid
@param slope is the slope of the sigmoid
*/
public void setSlope(double slope) {
this.slope = slope;
}
/**
Returns the direction of the sigmoid
@return the direction of the sigmoid
*/
public Direction direction() {
if (!Op.isFinite(slope) || Op.isEq(slope, 0.0)) {
return Direction.Zero;
}
if (Op.isGt(slope, 0.0)) {
return Direction.Positive;
}
return Direction.Negative;
}
@Override
public Sigmoid clone() throws CloneNotSupportedException {
return (Sigmoid) super.clone();
}
}
| gpl-3.0 |
desht/pnc-repressurized | src/api/java/me/desht/pneumaticcraft/api/event/SemiblockEvent.java | 836 | package me.desht.pneumaticcraft.api.event;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.eventhandler.Event;
public class SemiblockEvent extends Event {
private final World world;
private final BlockPos pos;
SemiblockEvent(World world, BlockPos pos) {
this.world = world;
this.pos = pos;
}
public World getWorld() {
return world;
}
public BlockPos getPos() {
return pos;
}
public static class PlaceEvent extends SemiblockEvent {
public PlaceEvent(World world, BlockPos pos) {
super(world, pos);
}
}
public static class BreakEvent extends SemiblockEvent {
public BreakEvent(World world, BlockPos pos) {
super(world, pos);
}
}
}
| gpl-3.0 |
neo-cs/sakila-web | src/main/java/mx/neocs/sakila/pu/FilmCategoryPrimaryKey.java | 2663 | /*
* Copyright (C) 2016 Freddy Barrera [freddy.barrera.moo(at)gmail.com.mx]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package mx.neocs.sakila.pu;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
/**
*
* @author Freddy Barrera [freddy.barrera.moo(at)gmail.com.mx]
*/
@Embeddable
public class FilmCategoryPrimaryKey implements Serializable {
private static final long serialVersionUID = 7530042784924646128L;
@Basic(optional = false)
@NotNull
@Column(name = "film_id")
private short filmId;
@Basic(optional = false)
@NotNull
@Column(name = "category_id")
private short categoryId;
public FilmCategoryPrimaryKey() {
}
public FilmCategoryPrimaryKey(short filmId, short categoryId) {
this.filmId = filmId;
this.categoryId = categoryId;
}
public short getFilmId() {
return filmId;
}
public void setFilmId(short filmId) {
this.filmId = filmId;
}
public short getCategoryId() {
return categoryId;
}
public void setCategoryId(short categoryId) {
this.categoryId = categoryId;
}
@Override
public int hashCode() {
int hash = 89;
hash += (int) filmId;
hash += (int) categoryId;
return hash;
}
@Override
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (!(object instanceof FilmCategoryPrimaryKey)) {
return false;
}
FilmCategoryPrimaryKey other = (FilmCategoryPrimaryKey) object;
if (this.filmId != other.filmId) {
return false;
}
return this.categoryId == other.categoryId;
}
@Override
public String toString() {
return "mx.org.neocs.pu.FilmCategoryEntityPK[ filmId=" + filmId + ", categoryId="
+ categoryId + " ]";
}
}
| gpl-3.0 |
CeON/saos | saos-enrichment/src/main/java/pl/edu/icm/saos/enrichment/apply/refcases/ReferencedCourtCasesTagValueItem.java | 933 | package pl.edu.icm.saos.enrichment.apply.refcases;
import java.util.List;
import com.google.common.collect.Lists;
/**
* @author Łukasz Dumiszewski
*/
public class ReferencedCourtCasesTagValueItem {
private String caseNumber;
private List<Long> judgmentIds = Lists.newArrayList();
//------------------------ GETTERS --------------------------
public String getCaseNumber() {
return caseNumber;
}
public List<Long> getJudgmentIds() {
if (judgmentIds == null) {
judgmentIds = Lists.newArrayList();
}
return judgmentIds;
}
//------------------------ SETTERS --------------------------
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public void setJudgmentIds(List<Long> judgmentIds) {
this.judgmentIds = judgmentIds;
}
} | gpl-3.0 |
fufuself/grit | src/main/java/com/fufu/java/chapter21/SingleThreadPool.java | 466 | package com.fufu.java.chapter21;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 线程池
*
* @author fufu
* @version 0.1.0
* @date 2018-09-25
*/
public class SingleThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
| gpl-3.0 |
oTkPoBeHuE/BirdsStore | app/src/exceptions/AuthorisationException.java | 171 | package exceptions;
public class AuthorisationException extends BirdsStoreException {
public AuthorisationException(String message) {
super(message);
}
}
| gpl-3.0 |
julianoezequiel/simple-serve | ex/src/main/java/com/topdata/toppontoweb/dto/ConversorEntidade.java | 227 | package com.topdata.toppontoweb.dto;
/**
* @version 1.0.0 data 20/07/2017
* @param <T>
* @since 1.0.0 data 20/07/2017
*
* @author juliano.ezequiel
*/
public interface ConversorEntidade<T> {
public T toEntidade();
}
| gpl-3.0 |
forkch/adhoc-railway | ch.fork.adhocrailway.railway.brain/src/main/java/ch/fork/adhocrailway/railway/brain/brain/BrainListener.java | 272 | package ch.fork.adhocrailway.railway.brain.brain;
public interface BrainListener {
void sentMessage(String sentMessage);
void receivedMessage(String receivedMessage);
void brainReset(String receivedMessage);
void brainMessage(String receivedMessage);
}
| gpl-3.0 |
jdrossl/liferay-ecommerce-theme | e-commerce/portlets/e-commerce-portlet/docroot/WEB-INF/service/com/rivetlogic/ecommerce/model/ShoppingOrderClp.java | 24370 | /**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.rivetlogic.ecommerce.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 com.liferay.portal.util.PortalUtil;
import com.rivetlogic.ecommerce.service.ClpSerializer;
import com.rivetlogic.ecommerce.service.ShoppingOrderLocalServiceUtil;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author isaiulate
*/
public class ShoppingOrderClp extends BaseModelImpl<ShoppingOrder>
implements ShoppingOrder {
public ShoppingOrderClp() {
}
@Override
public Class<?> getModelClass() {
return ShoppingOrder.class;
}
@Override
public String getModelClassName() {
return ShoppingOrder.class.getName();
}
@Override
public long getPrimaryKey() {
return _orderId;
}
@Override
public void setPrimaryKey(long primaryKey) {
setOrderId(primaryKey);
}
@Override
public Serializable getPrimaryKeyObj() {
return _orderId;
}
@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("orderId", getOrderId());
attributes.put("groupId", getGroupId());
attributes.put("companyId", getCompanyId());
attributes.put("userId", getUserId());
attributes.put("userName", getUserName());
attributes.put("createDate", getCreateDate());
attributes.put("modifiedDate", getModifiedDate());
attributes.put("orderStatus", getOrderStatus());
attributes.put("customerEmail", getCustomerEmail());
attributes.put("customerName", getCustomerName());
attributes.put("customerPhone", getCustomerPhone());
attributes.put("shippingAddress1", getShippingAddress1());
attributes.put("shippingAddress2", getShippingAddress2());
attributes.put("shippingCity", getShippingCity());
attributes.put("shippingPostalCode", getShippingPostalCode());
attributes.put("shippingStateProvince", getShippingStateProvince());
attributes.put("shippingCountry", getShippingCountry());
attributes.put("total", getTotal());
attributes.put("notes", getNotes());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Long orderId = (Long)attributes.get("orderId");
if (orderId != null) {
setOrderId(orderId);
}
Long groupId = (Long)attributes.get("groupId");
if (groupId != null) {
setGroupId(groupId);
}
Long companyId = (Long)attributes.get("companyId");
if (companyId != null) {
setCompanyId(companyId);
}
Long userId = (Long)attributes.get("userId");
if (userId != null) {
setUserId(userId);
}
String userName = (String)attributes.get("userName");
if (userName != null) {
setUserName(userName);
}
Date createDate = (Date)attributes.get("createDate");
if (createDate != null) {
setCreateDate(createDate);
}
Date modifiedDate = (Date)attributes.get("modifiedDate");
if (modifiedDate != null) {
setModifiedDate(modifiedDate);
}
String orderStatus = (String)attributes.get("orderStatus");
if (orderStatus != null) {
setOrderStatus(orderStatus);
}
String customerEmail = (String)attributes.get("customerEmail");
if (customerEmail != null) {
setCustomerEmail(customerEmail);
}
String customerName = (String)attributes.get("customerName");
if (customerName != null) {
setCustomerName(customerName);
}
String customerPhone = (String)attributes.get("customerPhone");
if (customerPhone != null) {
setCustomerPhone(customerPhone);
}
String shippingAddress1 = (String)attributes.get("shippingAddress1");
if (shippingAddress1 != null) {
setShippingAddress1(shippingAddress1);
}
String shippingAddress2 = (String)attributes.get("shippingAddress2");
if (shippingAddress2 != null) {
setShippingAddress2(shippingAddress2);
}
String shippingCity = (String)attributes.get("shippingCity");
if (shippingCity != null) {
setShippingCity(shippingCity);
}
String shippingPostalCode = (String)attributes.get("shippingPostalCode");
if (shippingPostalCode != null) {
setShippingPostalCode(shippingPostalCode);
}
String shippingStateProvince = (String)attributes.get(
"shippingStateProvince");
if (shippingStateProvince != null) {
setShippingStateProvince(shippingStateProvince);
}
String shippingCountry = (String)attributes.get("shippingCountry");
if (shippingCountry != null) {
setShippingCountry(shippingCountry);
}
Double total = (Double)attributes.get("total");
if (total != null) {
setTotal(total);
}
String notes = (String)attributes.get("notes");
if (notes != null) {
setNotes(notes);
}
}
@Override
public long getOrderId() {
return _orderId;
}
@Override
public void setOrderId(long orderId) {
_orderId = orderId;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setOrderId", long.class);
method.invoke(_shoppingOrderRemoteModel, orderId);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getGroupId() {
return _groupId;
}
@Override
public void setGroupId(long groupId) {
_groupId = groupId;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setGroupId", long.class);
method.invoke(_shoppingOrderRemoteModel, groupId);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getCompanyId() {
return _companyId;
}
@Override
public void setCompanyId(long companyId) {
_companyId = companyId;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setCompanyId", long.class);
method.invoke(_shoppingOrderRemoteModel, companyId);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public long getUserId() {
return _userId;
}
@Override
public void setUserId(long userId) {
_userId = userId;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setUserId", long.class);
method.invoke(_shoppingOrderRemoteModel, userId);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getUserUuid() throws SystemException {
return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid);
}
@Override
public void setUserUuid(String userUuid) {
_userUuid = userUuid;
}
@Override
public String getUserName() {
return _userName;
}
@Override
public void setUserName(String userName) {
_userName = userName;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setUserName", String.class);
method.invoke(_shoppingOrderRemoteModel, userName);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public Date getCreateDate() {
return _createDate;
}
@Override
public void setCreateDate(Date createDate) {
_createDate = createDate;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setCreateDate", Date.class);
method.invoke(_shoppingOrderRemoteModel, createDate);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public Date getModifiedDate() {
return _modifiedDate;
}
@Override
public void setModifiedDate(Date modifiedDate) {
_modifiedDate = modifiedDate;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setModifiedDate", Date.class);
method.invoke(_shoppingOrderRemoteModel, modifiedDate);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getOrderStatus() {
return _orderStatus;
}
@Override
public void setOrderStatus(String orderStatus) {
_orderStatus = orderStatus;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setOrderStatus", String.class);
method.invoke(_shoppingOrderRemoteModel, orderStatus);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getCustomerEmail() {
return _customerEmail;
}
@Override
public void setCustomerEmail(String customerEmail) {
_customerEmail = customerEmail;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setCustomerEmail", String.class);
method.invoke(_shoppingOrderRemoteModel, customerEmail);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getCustomerName() {
return _customerName;
}
@Override
public void setCustomerName(String customerName) {
_customerName = customerName;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setCustomerName", String.class);
method.invoke(_shoppingOrderRemoteModel, customerName);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getCustomerPhone() {
return _customerPhone;
}
@Override
public void setCustomerPhone(String customerPhone) {
_customerPhone = customerPhone;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setCustomerPhone", String.class);
method.invoke(_shoppingOrderRemoteModel, customerPhone);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getShippingAddress1() {
return _shippingAddress1;
}
@Override
public void setShippingAddress1(String shippingAddress1) {
_shippingAddress1 = shippingAddress1;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setShippingAddress1",
String.class);
method.invoke(_shoppingOrderRemoteModel, shippingAddress1);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getShippingAddress2() {
return _shippingAddress2;
}
@Override
public void setShippingAddress2(String shippingAddress2) {
_shippingAddress2 = shippingAddress2;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setShippingAddress2",
String.class);
method.invoke(_shoppingOrderRemoteModel, shippingAddress2);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getShippingCity() {
return _shippingCity;
}
@Override
public void setShippingCity(String shippingCity) {
_shippingCity = shippingCity;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setShippingCity", String.class);
method.invoke(_shoppingOrderRemoteModel, shippingCity);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getShippingPostalCode() {
return _shippingPostalCode;
}
@Override
public void setShippingPostalCode(String shippingPostalCode) {
_shippingPostalCode = shippingPostalCode;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setShippingPostalCode",
String.class);
method.invoke(_shoppingOrderRemoteModel, shippingPostalCode);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getShippingStateProvince() {
return _shippingStateProvince;
}
@Override
public void setShippingStateProvince(String shippingStateProvince) {
_shippingStateProvince = shippingStateProvince;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setShippingStateProvince",
String.class);
method.invoke(_shoppingOrderRemoteModel, shippingStateProvince);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getShippingCountry() {
return _shippingCountry;
}
@Override
public void setShippingCountry(String shippingCountry) {
_shippingCountry = shippingCountry;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setShippingCountry",
String.class);
method.invoke(_shoppingOrderRemoteModel, shippingCountry);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public double getTotal() {
return _total;
}
@Override
public void setTotal(double total) {
_total = total;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setTotal", double.class);
method.invoke(_shoppingOrderRemoteModel, total);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
@Override
public String getNotes() {
return _notes;
}
@Override
public void setNotes(String notes) {
_notes = notes;
if (_shoppingOrderRemoteModel != null) {
try {
Class<?> clazz = _shoppingOrderRemoteModel.getClass();
Method method = clazz.getMethod("setNotes", String.class);
method.invoke(_shoppingOrderRemoteModel, notes);
}
catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
}
public BaseModel<?> getShoppingOrderRemoteModel() {
return _shoppingOrderRemoteModel;
}
public void setShoppingOrderRemoteModel(
BaseModel<?> shoppingOrderRemoteModel) {
_shoppingOrderRemoteModel = shoppingOrderRemoteModel;
}
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 = _shoppingOrderRemoteModel.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(_shoppingOrderRemoteModel,
remoteParameterValues);
if (returnValue != null) {
returnValue = ClpSerializer.translateOutput(returnValue);
}
return returnValue;
}
@Override
public void persist() throws SystemException {
if (this.isNew()) {
ShoppingOrderLocalServiceUtil.addShoppingOrder(this);
}
else {
ShoppingOrderLocalServiceUtil.updateShoppingOrder(this);
}
}
@Override
public ShoppingOrder toEscapedModel() {
return (ShoppingOrder)ProxyUtil.newProxyInstance(ShoppingOrder.class.getClassLoader(),
new Class[] { ShoppingOrder.class }, new AutoEscapeBeanHandler(this));
}
@Override
public Object clone() {
ShoppingOrderClp clone = new ShoppingOrderClp();
clone.setOrderId(getOrderId());
clone.setGroupId(getGroupId());
clone.setCompanyId(getCompanyId());
clone.setUserId(getUserId());
clone.setUserName(getUserName());
clone.setCreateDate(getCreateDate());
clone.setModifiedDate(getModifiedDate());
clone.setOrderStatus(getOrderStatus());
clone.setCustomerEmail(getCustomerEmail());
clone.setCustomerName(getCustomerName());
clone.setCustomerPhone(getCustomerPhone());
clone.setShippingAddress1(getShippingAddress1());
clone.setShippingAddress2(getShippingAddress2());
clone.setShippingCity(getShippingCity());
clone.setShippingPostalCode(getShippingPostalCode());
clone.setShippingStateProvince(getShippingStateProvince());
clone.setShippingCountry(getShippingCountry());
clone.setTotal(getTotal());
clone.setNotes(getNotes());
return clone;
}
@Override
public int compareTo(ShoppingOrder shoppingOrder) {
long primaryKey = shoppingOrder.getPrimaryKey();
if (getPrimaryKey() < primaryKey) {
return -1;
}
else if (getPrimaryKey() > primaryKey) {
return 1;
}
else {
return 0;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ShoppingOrderClp)) {
return false;
}
ShoppingOrderClp shoppingOrder = (ShoppingOrderClp)obj;
long primaryKey = shoppingOrder.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
}
else {
return false;
}
}
public Class<?> getClpSerializerClass() {
return _clpSerializerClass;
}
@Override
public int hashCode() {
return (int)getPrimaryKey();
}
@Override
public String toString() {
StringBundler sb = new StringBundler(39);
sb.append("{orderId=");
sb.append(getOrderId());
sb.append(", groupId=");
sb.append(getGroupId());
sb.append(", companyId=");
sb.append(getCompanyId());
sb.append(", userId=");
sb.append(getUserId());
sb.append(", userName=");
sb.append(getUserName());
sb.append(", createDate=");
sb.append(getCreateDate());
sb.append(", modifiedDate=");
sb.append(getModifiedDate());
sb.append(", orderStatus=");
sb.append(getOrderStatus());
sb.append(", customerEmail=");
sb.append(getCustomerEmail());
sb.append(", customerName=");
sb.append(getCustomerName());
sb.append(", customerPhone=");
sb.append(getCustomerPhone());
sb.append(", shippingAddress1=");
sb.append(getShippingAddress1());
sb.append(", shippingAddress2=");
sb.append(getShippingAddress2());
sb.append(", shippingCity=");
sb.append(getShippingCity());
sb.append(", shippingPostalCode=");
sb.append(getShippingPostalCode());
sb.append(", shippingStateProvince=");
sb.append(getShippingStateProvince());
sb.append(", shippingCountry=");
sb.append(getShippingCountry());
sb.append(", total=");
sb.append(getTotal());
sb.append(", notes=");
sb.append(getNotes());
sb.append("}");
return sb.toString();
}
@Override
public String toXmlString() {
StringBundler sb = new StringBundler(61);
sb.append("<model><model-name>");
sb.append("com.rivetlogic.ecommerce.model.ShoppingOrder");
sb.append("</model-name>");
sb.append(
"<column><column-name>orderId</column-name><column-value><![CDATA[");
sb.append(getOrderId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupId</column-name><column-value><![CDATA[");
sb.append(getGroupId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>companyId</column-name><column-value><![CDATA[");
sb.append(getCompanyId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>userId</column-name><column-value><![CDATA[");
sb.append(getUserId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>userName</column-name><column-value><![CDATA[");
sb.append(getUserName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>createDate</column-name><column-value><![CDATA[");
sb.append(getCreateDate());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>modifiedDate</column-name><column-value><![CDATA[");
sb.append(getModifiedDate());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>orderStatus</column-name><column-value><![CDATA[");
sb.append(getOrderStatus());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>customerEmail</column-name><column-value><![CDATA[");
sb.append(getCustomerEmail());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>customerName</column-name><column-value><![CDATA[");
sb.append(getCustomerName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>customerPhone</column-name><column-value><![CDATA[");
sb.append(getCustomerPhone());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>shippingAddress1</column-name><column-value><![CDATA[");
sb.append(getShippingAddress1());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>shippingAddress2</column-name><column-value><![CDATA[");
sb.append(getShippingAddress2());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>shippingCity</column-name><column-value><![CDATA[");
sb.append(getShippingCity());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>shippingPostalCode</column-name><column-value><![CDATA[");
sb.append(getShippingPostalCode());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>shippingStateProvince</column-name><column-value><![CDATA[");
sb.append(getShippingStateProvince());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>shippingCountry</column-name><column-value><![CDATA[");
sb.append(getShippingCountry());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>total</column-name><column-value><![CDATA[");
sb.append(getTotal());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>notes</column-name><column-value><![CDATA[");
sb.append(getNotes());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
private long _orderId;
private long _groupId;
private long _companyId;
private long _userId;
private String _userUuid;
private String _userName;
private Date _createDate;
private Date _modifiedDate;
private String _orderStatus;
private String _customerEmail;
private String _customerName;
private String _customerPhone;
private String _shippingAddress1;
private String _shippingAddress2;
private String _shippingCity;
private String _shippingPostalCode;
private String _shippingStateProvince;
private String _shippingCountry;
private double _total;
private String _notes;
private BaseModel<?> _shoppingOrderRemoteModel;
private Class<?> _clpSerializerClass = com.rivetlogic.ecommerce.service.ClpSerializer.class;
} | gpl-3.0 |
hartwigmedical/hmftools | hmf-common/src/main/java/com/hartwig/hmftools/common/serve/classification/EventClassifierConfig.java | 2736 | package com.hartwig.hmftools.common.serve.classification;
import java.util.Map;
import java.util.Set;
import org.immutables.value.Value;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@Value.Immutable
@Value.Style(passAnnotations = { NotNull.class, Nullable.class })
public abstract class EventClassifierConfig {
@NotNull
public abstract EventPreprocessor proteinAnnotationExtractor();
@NotNull
public abstract Set<String> exonIdentifiers();
@NotNull
public abstract Set<String> exonKeywords();
@NotNull
public abstract Set<String> exonBlacklistKeyPhrases();
@NotNull
public abstract Set<String> specificExonEvents();
@NotNull
public abstract Map<String, Set<String>> fusionPairAndExonsPerGene();
@NotNull
public abstract Set<String> geneLevelBlacklistKeyPhrases();
@NotNull
public abstract Set<String> geneWildTypesKeyPhrases();
@NotNull
public abstract Set<String> genericGeneLevelKeyPhrases();
@NotNull
public abstract Set<String> activatingGeneLevelKeyPhrases();
@NotNull
public abstract Set<String> inactivatingGeneLevelKeyPhrases();
@NotNull
public abstract Set<String> amplificationKeywords();
@NotNull
public abstract Set<String> amplificationKeyPhrases();
@NotNull
public abstract Set<String> deletionBlacklistKeyPhrases();
@NotNull
public abstract Set<String> deletionKeywords();
@NotNull
public abstract Set<String> deletionKeyPhrases();
@NotNull
public abstract Set<String> exonicDelDupFusionKeyPhrases();
@NotNull
public abstract Set<String> exonicDelDupFusionEvents();
@NotNull
public abstract Set<String> fusionPairEventsToSkip();
@NotNull
public abstract Set<String> promiscuousFusionKeyPhrases();
@NotNull
public abstract Set<String> microsatelliteStableEvents();
@NotNull
public abstract Set<String> microsatelliteUnstableEvents();
@NotNull
public abstract Set<String> highTumorMutationalLoadEvents();
@NotNull
public abstract Set<String> lowTumorMutationalLoadEvents();
@NotNull
public abstract Set<String> highTumorMutationalBurdenEvents();
@NotNull
public abstract Set<String> lowTumorMutationalBurdenEvents();
@NotNull
public abstract Set<String> hrDeficiencyEvents();
@NotNull
public abstract Set<String> hlaEvents();
@NotNull
public abstract Set<String> hpvPositiveEvents();
@NotNull
public abstract Set<String> ebvPositiveEvents();
@NotNull
public abstract Map<String, Set<String>> combinedEventsPerGene();
@NotNull
public abstract Map<String, Set<String>> complexEventsPerGene();
} | gpl-3.0 |
bionimbuz/BionimbuzClient | src/main/java/br/unb/cic/bionimbuz/rest/action/Login.java | 1157 | package br.unb.cic.bionimbuz.rest.action;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import br.unb.cic.bionimbuz.model.User;
import br.unb.cic.bionimbuz.rest.request.RequestInfo;
import br.unb.cic.bionimbuz.rest.response.LoginResponse;
public class Login extends Action {
private static final String REST_LOGIN_URL = "/rest/login";
@Override
public void setup(Client client, RequestInfo reqInfo) {
this.target = client.target(super.bionimbuzAddress);
this.request = reqInfo;
}
@Override
public void prepareTarget() {
target = target.path(REST_LOGIN_URL);
}
@Override
public LoginResponse execute() {
logAction(REST_LOGIN_URL, Login.class);
Response response = target
.request(MediaType.APPLICATION_JSON)
.post(Entity.entity(request, MediaType.APPLICATION_JSON), Response.class);
return new LoginResponse(response.readEntity(new GenericType<User>(){
// Nothing to do.
}));
}
}
| gpl-3.0 |
CaptainBern/MinecraftNetLib | src/main/java/com/captainbern/minecraft/net/codec/play/server/CodecChangeGameState.java | 707 | package com.captainbern.minecraft.net.codec.play.server;
import com.captainbern.minecraft.net.codec.Codec;
import com.captainbern.minecraft.net.packet.play.server.PacketChangeGameState;
import io.netty.buffer.ByteBuf;
public class CodecChangeGameState implements Codec<PacketChangeGameState> {
public ByteBuf encode(ByteBuf byteBuf, PacketChangeGameState packet) {
byteBuf.writeByte(packet.getReason());
byteBuf.writeFloat(packet.getValue());
return byteBuf;
}
public PacketChangeGameState decode(ByteBuf byteBuf) {
int reason = byteBuf.readByte();
float value = byteBuf.readFloat();
return new PacketChangeGameState(reason, value);
}
}
| gpl-3.0 |
eighthave/NewPipe | app/src/main/java/org/schabi/newpipe/ActionBarHandler.java | 16351 | package org.schabi.newpipe;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import org.schabi.newpipe.services.VideoInfo;
/**
* Created by Christian Schabesberger on 18.08.15.
*
* Copyright (C) Christian Schabesberger 2015 <chris.schabesberger@mailbox.org>
* DetailsMenuHandler.java is part of NewPipe.
*
* NewPipe 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.
*
* NewPipe 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 NewPipe. If not, see <http://www.gnu.org/licenses/>.
*/
class ActionBarHandler {
private static final String TAG = ActionBarHandler.class.toString();
private static final String KORE_PACKET = "org.xbmc.kore";
private int serviceId;
private String websiteUrl = "";
private Bitmap videoThumbnail = null;
private String channelName = "";
private AppCompatActivity activity;
private VideoInfo.VideoStream[] videoStreams = null;
private VideoInfo.AudioStream audioStream = null;
private int selectedStream = -1;
private String videoTitle = "";
private SharedPreferences defaultPreferences = null;
private int startPosition;
@SuppressWarnings("deprecation")
private class FormatItemSelectListener implements ActionBar.OnNavigationListener {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
selectFormatItem((int)itemId);
return true;
}
}
public ActionBarHandler(AppCompatActivity activity) {
this.activity = activity;
}
@SuppressWarnings({"deprecation", "ConstantConditions"})
public void setupNavMenu(AppCompatActivity activity) {
this.activity = activity;
try {
activity.getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
} catch(NullPointerException e) {
e.printStackTrace();
}
}
public void setServiceId(int id) {
serviceId = id;
}
public void setSetVideoThumbnail(Bitmap bitmap) {
videoThumbnail = bitmap;
}
public void setChannelName(String name) {
channelName = name;
}
@SuppressWarnings("deprecation")
public void setStreams(VideoInfo.VideoStream[] videoStreams, VideoInfo.AudioStream[] audioStreams) {
this.videoStreams = videoStreams;
selectedStream = 0;
defaultPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
String[] itemArray = new String[videoStreams.length];
String defaultResolution = defaultPreferences
.getString(activity.getString(R.string.defaultResolutionPreference),
activity.getString(R.string.defaultResolutionListItem));
int defaultResolutionPos = 0;
for(int i = 0; i < videoStreams.length; i++) {
itemArray[i] = MediaFormat.getNameById(videoStreams[i].format) + " " + videoStreams[i].resolution;
if(defaultResolution.equals(videoStreams[i].resolution)) {
defaultResolutionPos = i;
}
}
ArrayAdapter<String> itemAdapter = new ArrayAdapter<>(activity.getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, itemArray);
if(activity != null) {
ActionBar ab = activity.getSupportActionBar();
assert ab != null : "Could not get actionbar";
ab.setListNavigationCallbacks(itemAdapter
, new FormatItemSelectListener());
ab.setSelectedNavigationItem(defaultResolutionPos);
}
// set audioStream
audioStream = null;
String preferedFormat = defaultPreferences
.getString(activity.getString(R.string.defaultAudioFormatPreference), "webm");
if(preferedFormat.equals("webm")) {
for(VideoInfo.AudioStream s : audioStreams) {
if(s.format == MediaFormat.WEBMA.id) {
audioStream = s;
}
}
} else if(preferedFormat.equals("m4a")){
for(VideoInfo.AudioStream s : audioStreams) {
if(s.format == MediaFormat.M4A.id &&
(audioStream == null || audioStream.bandwidth > s.bandwidth)) {
audioStream = s;
}
}
}
else {
Log.e(TAG, "FAILED to set audioStream value!");
}
}
private void selectFormatItem(int i) {
selectedStream = i;
}
public void setupMenu(Menu menu, MenuInflater inflater) {
// CAUTION set item properties programmatically otherwise it would not be accepted by
// appcompat itemsinflater.inflate(R.menu.videoitem_detail, menu);
defaultPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
inflater.inflate(R.menu.videoitem_detail, menu);
MenuItem castItem = menu.findItem(R.id.action_play_with_kodi);
castItem.setVisible(defaultPreferences
.getBoolean(activity.getString(R.string.showPlayWithKodiPreference), false));
}
public boolean onItemSelected(MenuItem item) {
if(!videoTitle.isEmpty()) {
int id = item.getItemId();
switch (id) {
case R.id.menu_item_share: {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, websiteUrl);
intent.setType("text/plain");
activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.shareDialogTitle)));
return true;
}
case R.id.menu_item_openInBrowser: {
openInBrowser();
}
return true;
case R.id.menu_item_download:
downloadVideo();
return true;
case R.id.action_settings: {
Intent intent = new Intent(activity, SettingsActivity.class);
activity.startActivity(intent);
}
break;
case R.id.action_play_with_kodi:
playWithKodi();
return true;
case R.id.menu_item_play_audio:
playAudio();
return true;
default:
Log.e(TAG, "Menu Item not known");
}
} else {
// That line may not be necessary.
return true;
}
return false;
}
public void setVideoInfo(String websiteUrl, String videoTitle) {
this.websiteUrl = websiteUrl;
this.videoTitle = videoTitle;
}
public void playVideo() {
// ----------- THE MAGIC MOMENT ---------------
if(!videoTitle.isEmpty()) {
if (PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(activity.getString(R.string.useExternalVideoPlayer), false)) {
// External Player
Intent intent = new Intent();
try {
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(videoStreams[selectedStream].url),
MediaFormat.getMimeById(videoStreams[selectedStream].format));
intent.putExtra(Intent.EXTRA_TITLE, videoTitle);
intent.putExtra("title", videoTitle);
activity.startActivity(intent); // HERE !!!
} catch (Exception e) {
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(R.string.noPlayerFound)
.setPositiveButton(R.string.installStreamPlayer, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(activity.getString(R.string.fdroidVLCurl)));
activity.startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
} else {
// Internal Player
Intent intent = new Intent(activity, PlayVideoActivity.class);
intent.putExtra(PlayVideoActivity.VIDEO_TITLE, videoTitle);
intent.putExtra(PlayVideoActivity.STREAM_URL, videoStreams[selectedStream].url);
intent.putExtra(PlayVideoActivity.VIDEO_URL, websiteUrl);
intent.putExtra(PlayVideoActivity.START_POSITION, startPosition);
activity.startActivity(intent); //also HERE !!!
}
}
// --------------------------------------------
}
public void setStartPosition(int startPositionSeconds)
{
this.startPosition = startPositionSeconds;
}
private void downloadVideo() {
if(!videoTitle.isEmpty()) {
String videoSuffix = "." + MediaFormat.getSuffixById(videoStreams[selectedStream].format);
String audioSuffix = "." + MediaFormat.getSuffixById(audioStream.format);
Bundle args = new Bundle();
args.putString(DownloadDialog.FILE_SUFFIX_VIDEO, videoSuffix);
args.putString(DownloadDialog.FILE_SUFFIX_AUDIO, audioSuffix);
args.putString(DownloadDialog.TITLE, videoTitle);
args.putString(DownloadDialog.VIDEO_URL, videoStreams[selectedStream].url);
args.putString(DownloadDialog.AUDIO_URL, audioStream.url);
DownloadDialog downloadDialog = new DownloadDialog();
downloadDialog.setArguments(args);
downloadDialog.show(activity.getSupportFragmentManager(), "downloadDialog");
}
}
private void openInBrowser() {
if(!videoTitle.isEmpty()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(websiteUrl));
activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.chooseBrowser)));
}
}
private void playWithKodi() {
if(!videoTitle.isEmpty()) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setPackage(KORE_PACKET);
intent.setData(Uri.parse(websiteUrl.replace("https", "http")));
activity.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(R.string.koreNotFound)
.setPositiveButton(R.string.installeKore, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(activity.getString(R.string.fdroidKoreUrl)));
activity.startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
}
}
public void playAudio() {
boolean externalAudioPlayer = PreferenceManager.getDefaultSharedPreferences(activity)
.getBoolean(activity.getString(R.string.useExternalAudioPlayer), false);
Intent intent;
if (!externalAudioPlayer && android.os.Build.VERSION.SDK_INT >= 18) {
//internal music player: explicit intent
if (!BackgroundPlayer.isRunning && videoThumbnail != null) {
ActivityCommunicator.getCommunicator()
.backgroundPlayerThumbnail = videoThumbnail;
intent = new Intent(activity, BackgroundPlayer.class);
intent.setAction(Intent.ACTION_VIEW);
Log.i(TAG, "audioStream is null:" + (audioStream == null));
Log.i(TAG, "audioStream.url is null:" + (audioStream.url == null));
intent.setDataAndType(Uri.parse(audioStream.url),
MediaFormat.getMimeById(audioStream.format));
intent.putExtra(BackgroundPlayer.TITLE, videoTitle);
intent.putExtra(BackgroundPlayer.WEB_URL, websiteUrl);
intent.putExtra(BackgroundPlayer.SERVICE_ID, serviceId);
intent.putExtra(BackgroundPlayer.CHANNEL_NAME, channelName);
activity.startService(intent);
}
} else {
intent = new Intent();
try {
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(audioStream.url),
MediaFormat.getMimeById(audioStream.format));
intent.putExtra(Intent.EXTRA_TITLE, videoTitle);
intent.putExtra("title", videoTitle);
activity.startActivity(intent); // HERE !!!
} catch (Exception e) {
e.printStackTrace();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(R.string.noPlayerFound)
.setPositiveButton(R.string.installStreamPlayer, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(activity.getString(R.string.fdroidVLCurl)));
activity.startActivity(intent);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, "You unlocked a secret unicorn.");
}
});
builder.create().show();
Log.e(TAG, "Either no Streaming player for audio was installed, or something important crashed:");
e.printStackTrace();
}
}
}
}
| gpl-3.0 |
BrickCat/symphony | src/main/java/org/b3log/symphony/service/RevisionQueryService.java | 6137 | /*
* Symphony - A modern community (forum/SNS/blog) platform written in Java.
* Copyright (C) 2012-2017, b3log.org & hacpai.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.b3log.symphony.service;
import org.b3log.latke.Keys;
import org.b3log.latke.ioc.inject.Inject;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.repository.*;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Revision;
import org.b3log.symphony.repository.RevisionRepository;
import org.b3log.symphony.util.Markdowns;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collections;
import java.util.List;
/**
* Revision query service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.0.0.0, May 6, 2017
* @since 2.1.0
*/
@Service
public class RevisionQueryService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(RevisionQueryService.class);
/**
* Revision repository.
*/
@Inject
private RevisionRepository revisionRepository;
/**
* Gets a comment's revisions.
*
* @param commentId the specified comment id
* @return comment revisions, returns an empty list if not found
*/
public List<JSONObject> getCommentRevisions(final String commentId) {
final Query query = new Query().setFilter(CompositeFilterOperator.and(
new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, commentId),
new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, Revision.DATA_TYPE_C_COMMENT)
)).addSort(Keys.OBJECT_ID, SortDirection.ASCENDING);
try {
final List<JSONObject> ret = CollectionUtils.jsonArrayToList(revisionRepository.get(query).optJSONArray(Keys.RESULTS));
for (final JSONObject rev : ret) {
final JSONObject data = new JSONObject(rev.optString(Revision.REVISION_DATA));
String commentContent = data.optString(Comment.COMMENT_CONTENT);
commentContent = commentContent.replace("\n", "_esc_br_");
commentContent = Markdowns.clean(commentContent, "");
commentContent = commentContent.replace("_esc_br_", "\n");
data.put(Comment.COMMENT_CONTENT, commentContent);
rev.put(Revision.REVISION_DATA, data);
}
return ret;
} catch (final RepositoryException | JSONException e) {
LOGGER.log(Level.ERROR, "Gets comment revisions failed", e);
return Collections.emptyList();
}
}
/**
* Gets an article's revisions.
*
* @param articleId the specified article id
* @return article revisions, returns an empty list if not found
*/
public List<JSONObject> getArticleRevisions(final String articleId) {
final Query query = new Query().setFilter(CompositeFilterOperator.and(
new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, articleId),
new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, Revision.DATA_TYPE_C_ARTICLE)
)).addSort(Keys.OBJECT_ID, SortDirection.ASCENDING);
try {
final List<JSONObject> ret = CollectionUtils.jsonArrayToList(revisionRepository.get(query).optJSONArray(Keys.RESULTS));
for (final JSONObject rev : ret) {
final JSONObject data = new JSONObject(rev.optString(Revision.REVISION_DATA));
String articleTitle = data.optString(Article.ARTICLE_TITLE);
articleTitle = articleTitle.replace("<", "<").replace(">", ">");
articleTitle = Markdowns.clean(articleTitle, "");
data.put(Article.ARTICLE_TITLE, articleTitle);
String articleContent = data.optString(Article.ARTICLE_CONTENT);
// articleContent = Markdowns.toHTML(articleContent); https://hacpai.com/article/1490233597586
articleContent = articleContent.replace("\n", "_esc_br_");
articleContent = Markdowns.clean(articleContent, "");
articleContent = articleContent.replace("_esc_br_", "\n");
data.put(Article.ARTICLE_CONTENT, articleContent);
rev.put(Revision.REVISION_DATA, data);
}
return ret;
} catch (final RepositoryException | JSONException e) {
LOGGER.log(Level.ERROR, "Gets article revisions failed", e);
return Collections.emptyList();
}
}
/**
* Counts revision specified by the given data id and data type.
*
* @param dataId the given data id
* @param dataType the given data type
* @return count result
*/
public int count(final String dataId, final int dataType) {
final Query query = new Query().setFilter(CompositeFilterOperator.and(
new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, dataId),
new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, dataType)
));
try {
return (int) revisionRepository.count(query);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Counts revisions failed", e);
return 0;
}
}
}
| gpl-3.0 |
DSI-Ville-Noumea/sirh-ws | src/main/java/nc/noumea/mairie/model/bean/Spbhor.java | 1139 | package nc.noumea.mairie.model.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.PersistenceUnit;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "SPBHOR")
@PersistenceUnit(unitName = "sirhPersistenceUnit")
@NamedQuery(name = "Spbhor.whereCdTauxNotZero", query = "SELECT sp from Spbhor sp WHERE (sp.taux <> 0 and sp.taux <> 1) order by sp.taux DESC")
public class Spbhor {
@Id
@Column(name = "CDTHOR", columnDefinition = "decimal")
private Integer cdThor;
@NotNull
@Column(name = "LIBHOR", columnDefinition = "char")
private String libHor;
@Column(name = "CDTAUX", columnDefinition = "decimal")
private Double taux;
public Integer getCdThor() {
return cdThor;
}
public void setCdThor(Integer cdThor) {
this.cdThor = cdThor;
}
public String getLibHor() {
return libHor;
}
public void setLibHor(String libHor) {
this.libHor = libHor;
}
public Double getTaux() {
return taux;
}
public void setTaux(Double taux) {
this.taux = taux;
}
}
| gpl-3.0 |
meltzow/MultiverseKing_JME | MultiverseKingCore/src/org/multiverseking/ability/AbilityComponent.java | 2237 | package battleSystem.ability;
import com.simsilica.es.EntityComponent;
import org.hexgridapi.utility.Vector2Int;
import org.multiverseking.field.Collision;
import org.multiverseking.utility.ElementalAttribut;
/**
*
* @author roah
*/
public class AbilityComponent implements EntityComponent {
private final String name;
private final int power;
private final byte activationCost;
private final Vector2Int castRange;
private final ElementalAttribut eAttribut;
private final String description;
private final Collision collision;
/**
* Create a new ability for an entity unit.
*
* @param activationRange ability trigger.
* @param effectSize when activated.
* @param eAttribut of the effect.
* @param loadTime between activation.
*/
public AbilityComponent(String name, Vector2Int castRange, ElementalAttribut eAttribut,
byte activationCost, int power, Collision collision, String description) {
this.name = name;
this.castRange = castRange;
this.collision = collision;
this.eAttribut = eAttribut;
this.activationCost = activationCost;
this.power = power;
this.description = description;
}
/**
* Power this ability have.
*
* @return
*/
public int getPower() {
return power;
}
/**
* Area range trigger of the ability.
*
* @return
*/
public Vector2Int getCastRange() {
return castRange;
}
/**
* Where the ability will hit when activated.
*/
public Collision getHitCollision() {
return collision;
}
/**
* Segment needed for activation.
*
* @return
*/
public byte getSegment() {
return activationCost;
}
/**
* Elemental Attribut of the ability effect.
*
* @return
*/
public ElementalAttribut getEAttribut() {
return eAttribut;
}
/**
* Description of the ability.
*
* @return
*/
public String getDescription() {
return description;
}
/**
* Name of the ability.
*
* @return
*/
public String getName() {
return name;
}
}
| gpl-3.0 |
Diveboard/diveboard-web | test/Integration/src/OtherPrivateDive.java | 8202 |
import org.junit.Test;
import diveboard.SimpleDiveActions;
public class OtherPrivateDive extends SimpleDiveActions{
// test the permissions between two accounts
public static String smn_private_dive = "ksso/488";
// public static String smn_draft_dive = "https://stage.diveboard.com/ksso/488";
// public static String other_user_id;
public static String other_user_puplic_dive;
public static String other_user_private_dive;
public static String other_user_draft;
@Test
public void test_OtherDive() throws Exception {
register();
create_other_user_puplic_dive();
create_other_user_private_dive();
create_other_user_draft();
logout();
fb_user_id= createTestFBUser();
loginTempFBUser();
view_other_public();
view_other_private(other_user_private_dive);
view_other_private(other_user_draft);
view_other_private(smn_private_dive);
logout();
view_other_public();
view_other_private(other_user_private_dive);
view_other_private(other_user_draft);
deleteTempFBUser(fb_user_id);
sel.stop();
}
private void view_other_private(String link) {
sel.open(link);
sel.waitForPageToLoad("50000");
verifyEquals("Dive unavailable", getText("css=h1"));
verifyTrue(getText("css=div.no_content").startsWith("Dive unavailable Sorry this dive is not public but feel free to check out other dives from"));
// verifyTrue(sel.isTextPresent("Sorry this dive is not public but feel free to check out other dives"));
// verifyTrue(sel.isTextPresent("Bubbling on Diveboard:"));
System.out.println("Unavailable dive checked");
}
private void view_other_public() throws InterruptedException {
open(other_user_puplic_dive);
sel.waitForPageToLoad("500000");
waitForElement("css=span.header_title");
verifyTrue(isElementPresent("id=add_buddy"));
verifyTrue(isElementPresent("SnapABug_bImg"));
verifyTrue(isElementPresent("country_title"));
verifyTrue(isElementPresent("link=Gozo"));
verifyTrue(isElementPresent("link=Mediterranean Sea"));
// verifyTrue(isElementPresent("css=img[alt=Add as buddy]"));
verifyEquals("Blue Hole", getText("css=span.header_title"));
waitForElement("css=div.main_content_header ");
verifyTrue(isElementPresent("css=img.tooltiped-js"));
verifyTrue(isElementPresent("css=span.liketext"));
verifyTrue(isElementPresent("css=div.thumbs_up_icon"));
verifyTrue(isElementPresent("css=div.msgIcon"));
verifyText("//div[@id='tab_overview']/div[1]/ul/li[2]", "Max Depth: 25m Duration:45mins");
waitForVisible("id=graph_small");
verifyEquals("true", sel.getEval("window.document.getElementById(\"graph_small\").innerHTML.indexOf(\"" + graph_small + "\") > 0"));
click(tab_profile);
waitForVisible("id=graphs");
verifyEquals("true", sel.getEval("window.document.getElementById(\"graphs\").innerHTML.indexOf(\"" + prifile_graph + "\") > 0"));
System.out.println("Other public dive checked");
}
protected void create_other_user_puplic_dive() throws InterruptedException {
sel.open("/");
waitForElement("create_dive_2");
click("create_dive_2");
// waitForElement("spotsearch");
waitForVisible(saveDiveBut);
//LOCATION Search your Dive Spot:
System.out.println("Fill in spotsearch..");
spotSearch("blu ho go",2);
// Profile
click(tab_overview);
//* with only the mandatory information
// click("wizard-date");
// click("css=a.ui-state-default.ui-state-hover");
type("wizard-date", date);
type("wizard-time-in-hrs", "22");
type("wizard-time-in-mins", "59");
type("wizard-duration-mins", "45");
type("wizard-max-depth", "25");
// click("link=Dive Notes");
type("wizard-dive-notes", "Test public dive");
click(saveDiveBut);
// waitForVisible("css=span.fwb.fcb"); //changed from mask
// waitForVisible("css=label.desc");
waitForNotVisible("id=file_spinning");
waitForDiveLink();
//wait for Dive Editor to close
for (int second = 0;; second++) {
if (second >= minute) fail("FAIL: Element id=dialog is still on page " + sel.getLocation());
try { if (!isElementPresent("id=dialog")) break; }
catch (Exception e) {System.out.println(e.getMessage());}
Thread.sleep(1000);
}
// waitForVisible("//div[@id='main_content_area']/div[1]/ul[1]/li[1]/span");
verifyTrue(isElementPresent("//img[@alt='Public']"));
verifyTrue(getText("css=span.header_title").equals("Blue Hole"));
waitForDiveLink();
// String host = sel.getEval("window.document.domain");
other_user_puplic_dive = sel.getLocation();
System.out.println("New Public Dive created. " + other_user_puplic_dive);
}
protected void create_other_user_private_dive() throws InterruptedException {
// sel.open("/");
click("create_dive_2");
// waitForElement("spotsearch");
waitForVisible(saveDiveBut);
//LOCATION Search your Dive Spot:
System.out.println("fill in spotsearch with 'gho indon'");
spotSearch("gho indon",1);
waitForElement("//img[@src='/img/flags/id.gif']"); //indonesia flag
System.out.println("'Ghost Bay, Amed, Laut Bali, Indonesia' - found ");
/*
for (int second = 0;; second++) {
if (second >= minute) fail("could not find text 'Search for another spot or correct data'");
try { if ("Search for another spot or correct data".equals(getText("//div[@id='correct_submit_spot_data']/label"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
*/
// click("wizard_next");
click(tab_overview);
waitForVisible("wizard-surface-temperature");
// Profile
// click("link=Profile Data");
//* with only the mandatory information
// click("wizard-date");
// click("css=a.ui-state-default.ui-state-hover");
type("wizard-date", date);
type("wizard-time-in-hrs", "22");
type("wizard-time-in-mins", "59");
type("wizard-duration-mins", "45");
type("wizard-max-depth", "25");
// click("link=Dive Notes");
type("wizard-dive-notes", "Test private dive");
click(saveDiveBut);
// waitForVisible("css=span.fwb.fcb"); //changed from mask
waitForNotVisible("id=file_spinning");
waitForDiveLink();
// waitForVisible("css=label.desc");
//wait for Dive Editor to close
for (int second = 0;; second++) {
if (second >= minute) fail("FAIL: Element id=dialog is still on page " + sel.getLocation());
try { if (!isElementPresent("id=dialog")) break; }
catch (Exception e) {System.out.println(e.getMessage());}
Thread.sleep(1000);
}
// waitForElement("//div[@id='main_content_area']/div[1]/ul[1]/li[1]/span");
changeToPrivate();
//check if counters not present
verifyFalse(isElementPresent("aggregateCount"));
verifyFalse(isElementPresent("//div[@id='plusone']/div/a"));
verifyFalse(isElementPresent("css=div.msgIcon"));
verifyTrue(getText("css=span.header_title").equals("Ghost Bay"));
// String host = sel.getEval("window.document.domain");
other_user_private_dive = sel.getLocation();
System.out.println("New Private Dive created. " + other_user_private_dive);
}
protected void create_other_user_draft() throws InterruptedException {
sel.open("/");
click("create_dive_2");
waitForVisible(saveDiveBut);
type("wizard-date", date);
type("wizard-time-in-hrs", "22");
type("wizard-time-in-mins", "59");
type("wizard-duration-mins", "45");
type("wizard-max-depth", "25");
//Notes
type("wizard-dive-notes", "Test draft");
// Save
click(saveDiveBut);
waitForNotVisible("id=file_spinning");
// waitForVisible("//div[@id='main_content_area']/div[3]/a/img"); //changed from mask
// waitForElement("//div[@id='main_content_area']/div[1]/ul[1]/li[1]/span");
verifyTrue(getText("css=span.header_title").equals("New Dive"));
verifyTrue(isElementPresent("//img[@alt='Private']"));
waitForDiveLink();
// String host = sel.getEval("window.document.domain");
other_user_draft = sel.getLocation();
System.out.println("New draft created. " + other_user_draft);
}
} | gpl-3.0 |
Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchConstants.java | 14720 | /*******************************************************************************
* Copyright (c) 2000, 2017 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.core.search;
import org.eclipse.jdt.internal.core.search.processing.*;
/**
* <p>
* This interface defines the constants used by the search engine.
* </p>
* <p>
* This interface declares constants only.
* </p>
* @see org.eclipse.jdt.core.search.SearchEngine
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface IJavaSearchConstants {
/**
* The nature of searched element or the nature
* of match in unknown.
*/
int UNKNOWN = -1;
/* Nature of searched element */
/**
* The searched element is a type, which may include classes, interfaces,
* enums, and annotation types.
*
* @category searchFor
*/
int TYPE= 0;
/**
* The searched element is a method.
*
* @category searchFor
*/
int METHOD= 1;
/**
* The searched element is a package.
*
* @category searchFor
*/
int PACKAGE= 2;
/**
* The searched element is a constructor.
*
* @category searchFor
*/
int CONSTRUCTOR= 3;
/**
* The searched element is a field.
*
* @category searchFor
*/
int FIELD= 4;
/**
* The searched element is a class.
* More selective than using {@link #TYPE}.
*
* @category searchFor
*/
int CLASS= 5;
/**
* The searched element is an interface.
* More selective than using {@link #TYPE}.
*
* @category searchFor
*/
int INTERFACE= 6;
/**
* The searched element is an enum.
* More selective than using {@link #TYPE}.
*
* @since 3.1
* @category searchFor
*/
int ENUM= 7;
/**
* The searched element is an annotation type.
* More selective than using {@link #TYPE}.
*
* @since 3.1
* @category searchFor
*/
int ANNOTATION_TYPE= 8;
/**
* The searched element is a class or enum type.
* More selective than using {@link #TYPE}.
*
* @since 3.1
* @category searchFor
*/
int CLASS_AND_ENUM= 9;
/**
* The searched element is a class or interface type.
* More selective than using {@link #TYPE}.
*
* @since 3.1
* @category searchFor
*/
int CLASS_AND_INTERFACE= 10;
/**
* The searched element is an interface or annotation type.
* More selective than using {@link #TYPE}.
* @since 3.3
* @category searchFor
*/
int INTERFACE_AND_ANNOTATION= 11;
/**
* The searched element is a module.
* @since 3.14
* @category searchFor
*/
int MODULE= 12;
/* Nature of match */
/**
* The search result is a declaration.
* Can be used in conjunction with any of the nature of searched elements
* so as to better narrow down the search.
*
* @category limitTo
*/
int DECLARATIONS= 0;
/**
* The search result is a type that implements an interface or extends a class.
* Used in conjunction with either TYPE or CLASS or INTERFACE, it will
* respectively search for any type implementing/extending a type,
* or rather exclusively search for classes implementing/extending the type, or
* interfaces extending the type.
*
* @category limitTo
*/
int IMPLEMENTORS= 1;
/**
* The search result is a reference.
* Can be used in conjunction with any of the nature of searched elements
* so as to better narrow down the search.
* References can contain implementers since they are more generic kind
* of matches.
*
* @category limitTo
*/
int REFERENCES= 2;
/**
* The search result is a declaration, a reference, or an implementer
* of an interface.
* Can be used in conjunction with any of the nature of searched elements
* so as to better narrow down the search.
*
* @category limitTo
*/
int ALL_OCCURRENCES= 3;
/**
* When searching for field matches, it will exclusively find read accesses, as
* opposed to write accesses. Note that some expressions are considered both
* as field read/write accesses: for example, x++; x+= 1;
*
* @since 2.0
* @category limitTo
*/
int READ_ACCESSES = 4;
/**
* When searching for field matches, it will exclusively find write accesses, as
* opposed to read accesses. Note that some expressions are considered both
* as field read/write accesses: for example, x++; x+= 1;
*
* @since 2.0
* @category limitTo
*/
int WRITE_ACCESSES = 5;
/**
* When searching for Type Declaration matches, and if a module is given, this
* will find type declaration matches in this module as well as the dependent
* module graph of the given module.
*
* @since 3.14
* @category limitTo
*/
int MODULE_GRAPH = 6;
/**
* Ignore declaring type while searching result.
* Can be used in conjunction with any of the nature of match.
*
* @since 3.1
* @category limitTo
*/
int IGNORE_DECLARING_TYPE = 0x10;
/**
* Ignore return type while searching result.
* Can be used in conjunction with any other nature of match.
* Note that:
* <ul>
* <li>for fields search, pattern will ignore field type</li>
* <li>this flag will have no effect for types search</li>
* </ul>
*
* @since 3.1
* @category limitTo
*/
int IGNORE_RETURN_TYPE = 0x20;
/**
* Return only type references used as the type of a field declaration.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int FIELD_DECLARATION_TYPE_REFERENCE = 0x40;
/**
* Return only type references used as the type of a local variable declaration.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int LOCAL_VARIABLE_DECLARATION_TYPE_REFERENCE = 0x80;
/**
* Return only type references used as the type of a method parameter
* declaration.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int PARAMETER_DECLARATION_TYPE_REFERENCE = 0x100;
/**
* Return only type references used as a super type or as a super interface.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int SUPERTYPE_TYPE_REFERENCE = 0x200;
/**
* Return only type references used in a throws clause.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int THROWS_CLAUSE_TYPE_REFERENCE = 0x400;
/**
* Return only type references used in a cast expression.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int CAST_TYPE_REFERENCE = 0x800;
/**
* Return only type references used in a catch header.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int CATCH_TYPE_REFERENCE = 0x1000;
/**
* Return only type references used in class instance creation.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p><p>
* Example:
*<pre>
* public class Test {
* Test() {}
* static Test bar() {
* return new <i>Test</i>();
* }
* }
*</pre>
* Searching references to the type <code>Test</code> using this flag in the
* above snippet will match only the reference in italic.
* </p><p>
* Note that array creations are not returned when using this flag.
* </p>
* @since 3.4
* @category limitTo
*/
int CLASS_INSTANCE_CREATION_TYPE_REFERENCE = 0x2000;
/**
* Return only type references used as a method return type.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int RETURN_TYPE_REFERENCE = 0x4000;
/**
* Return only type references used in an import declaration.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int IMPORT_DECLARATION_TYPE_REFERENCE = 0x8000;
/**
* Return only type references used as an annotation.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int ANNOTATION_TYPE_REFERENCE = 0x10000;
/**
* Return only type references used as a type argument in a parameterized
* type or a parameterized method.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int TYPE_ARGUMENT_TYPE_REFERENCE = 0x20000;
/**
* Return only type references used as a type variable bound.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int TYPE_VARIABLE_BOUND_TYPE_REFERENCE = 0x40000;
/**
* Return only type references used as a wildcard bound.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int WILDCARD_BOUND_TYPE_REFERENCE = 0x80000;
/**
* Return only type references used as a type of an <code>instanceof</code>
* expression.
* <p>
* When this flag is set, only {@link TypeReferenceMatch} matches will be
* returned.
*</p>
* @since 3.4
* @category limitTo
*/
int INSTANCEOF_TYPE_REFERENCE = 0x100000;
/**
* Return only super field accesses or super method invocations (e.g. using the
* <code>super</code> qualifier).
* <p>
* When this flag is set, the kind of returned matches will depend on the
* specified nature of the searched element:
* <ul>
* <li>for the {@link #FIELD} nature, only {@link FieldReferenceMatch}
* matches will be returned,</li>
* <li>for the {@link #METHOD} nature, only {@link MethodReferenceMatch}
* matches will be returned.</li>
* </ul>
*</p>
* @since 3.4
* @category limitTo
*/
int SUPER_REFERENCE = 0x1000000;
/**
* Return only qualified field accesses or qualified method invocations.
* <p>
* When this flag is set, the kind of returned matches will depend on the
* specified nature of the searched element:
* <ul>
* <li>for the {@link #FIELD} nature, only {@link FieldReferenceMatch}
* matches will be returned,</li>
* <li>for the {@link #METHOD} nature, only {@link MethodReferenceMatch}
* matches will be returned.</li>
* </ul>
*</p>
* @since 3.4
* @category limitTo
*/
int QUALIFIED_REFERENCE = 0x2000000;
/**
* Return only primary field accesses or primary method invocations (e.g. using
* the <code>this</code> qualifier).
* <p>
* When this flag is set, the kind of returned matches will depend on the
* specified nature of the searched element:
* <ul>
* <li>for the {@link #FIELD} nature, only {@link FieldReferenceMatch}
* matches will be returned,</li>
* <li>for the {@link #METHOD} nature, only {@link MethodReferenceMatch}
* matches will be returned.</li>
* </ul>
*</p>
* @since 3.4
* @category limitTo
*/
int THIS_REFERENCE = 0x4000000;
/**
* Return only field accesses or method invocations without any qualification.
* <p>
* When this flag is set, the kind of returned matches will depend on the
* specified nature of the searched element:
* <ul>
* <li>for the {@link #FIELD} nature, only {@link FieldReferenceMatch}
* matches will be returned,</li>
* <li>for the {@link #METHOD} nature, only {@link MethodReferenceMatch}
* matches will be returned.</li>
* </ul>
*</p>
* @since 3.4
* @category limitTo
*/
int IMPLICIT_THIS_REFERENCE = 0x8000000;
/**
* Return only method reference expressions, e.g. <code>A::foo</code>.
* <p>
* When this flag is set, only {@link MethodReferenceMatch} matches will be
* returned.
*</p>
* @since 3.10
* @category limitTo
*/
int METHOD_REFERENCE_EXPRESSION = 0x10000000;
/* Syntactic match modes */
/**
* The search pattern matches exactly the search result,
* that is, the source of the search result equals the search pattern.
*
* @deprecated Use {@link SearchPattern#R_EXACT_MATCH} instead.
* @category matchRule
*/
int EXACT_MATCH = 0;
/**
* The search pattern is a prefix of the search result.
*
* @deprecated Use {@link SearchPattern#R_PREFIX_MATCH} instead.
* @category matchRule
*/
int PREFIX_MATCH = 1;
/**
* The search pattern contains one or more wild cards ('*') where a
* wild-card can replace 0 or more characters in the search result.
*
* @deprecated Use {@link SearchPattern#R_PATTERN_MATCH} instead.
* @category matchRule
*/
int PATTERN_MATCH = 2;
/* Case sensitivity */
/**
* The search pattern matches the search result only
* if cases are the same.
*
* @deprecated Use the methods that take the matchMode
* with {@link SearchPattern#R_CASE_SENSITIVE} as a matchRule instead.
* @category matchRule
*/
boolean CASE_SENSITIVE = true;
/**
* The search pattern ignores cases in the search result.
*
* @deprecated Use the methods that take the matchMode
* without {@link SearchPattern#R_CASE_SENSITIVE} as a matchRule instead.
* @category matchRule
*/
boolean CASE_INSENSITIVE = false;
/* Waiting policies */
/**
* The search operation starts immediately, even if the underlying indexer
* has not finished indexing the workspace. Results will more likely
* not contain all the matches.
*/
int FORCE_IMMEDIATE_SEARCH = IJob.ForceImmediate;
/**
* The search operation throws an <code>org.eclipse.core.runtime.OperationCanceledException</code>
* if the underlying indexer has not finished indexing the workspace.
*/
int CANCEL_IF_NOT_READY_TO_SEARCH = IJob.CancelIfNotReady;
/**
* The search operation waits for the underlying indexer to finish indexing
* the workspace before starting the search.
*/
int WAIT_UNTIL_READY_TO_SEARCH = IJob.WaitUntilReady;
/* Special Constant for module search */
/**
* The unnamed module is represented by this constant for making the intent explicit
* in searches involving modules
* @since 3.14
*/
char[] ALL_UNNAMED = "ALL-UNNAMED".toCharArray(); ////$NON-NLS-1$
}
| gpl-3.0 |
Mapleroid/cm-server | server-5.11.0.src/com/cloudera/server/web/cmf/rman/pools/include/RuleDialogImpl.java | 12746 | package com.cloudera.server.web.cmf.rman.pools.include;
import com.cloudera.cmf.Environment;
import com.cloudera.server.web.common.I18n;
import com.cloudera.server.web.common.ModalDialogBaseImpl;
import java.io.IOException;
import java.io.Writer;
import org.jamon.TemplateManager;
import org.jamon.emit.StandardEmitter;
import org.jamon.escaping.Escaping;
public class RuleDialogImpl extends ModalDialogBaseImpl
implements RuleDialog.Intf
{
private final boolean destroyOnClose;
private final String dialogClass;
private final String id;
private final boolean defaultVisible;
private final String templateId;
protected static RuleDialog.ImplData __jamon_setOptionalArguments(RuleDialog.ImplData p_implData)
{
if (!p_implData.getDestroyOnClose__IsNotDefault())
{
p_implData.setDestroyOnClose(false);
}
if (!p_implData.getDialogClass__IsNotDefault())
{
p_implData.setDialogClass("rule-dialog modal-lg");
}
if (!p_implData.getId__IsNotDefault())
{
p_implData.setId("ruleDialog");
}
if (!p_implData.getDefaultVisible__IsNotDefault())
{
p_implData.setDefaultVisible(false);
}
if (!p_implData.getTemplateId__IsNotDefault())
{
p_implData.setTemplateId("tmpl-rman-rule-dialog");
}
ModalDialogBaseImpl.__jamon_setOptionalArguments(p_implData);
return p_implData;
}
public RuleDialogImpl(TemplateManager p_templateManager, RuleDialog.ImplData p_implData) {
super(p_templateManager, __jamon_setOptionalArguments(p_implData));
this.destroyOnClose = p_implData.getDestroyOnClose();
this.dialogClass = p_implData.getDialogClass();
this.id = p_implData.getId();
this.defaultVisible = p_implData.getDefaultVisible();
this.templateId = p_implData.getTemplateId();
}
protected void child_render_1(Writer jamonWriter)
throws IOException
{
jamonWriter.write("<form class=\"form-horizontal\">\n <!-- ko template: {name: 'tmpl-rman-edit-rule', data: selectedEntry} --><!-- /ko -->\n</form>\n\n");
}
protected void __jamon_innerUnit__title(Writer jamonWriter)
throws IOException
{
jamonWriter.write("<span data-bind=\"visible: isAddMode\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.createSchedulingRule")), jamonWriter);
jamonWriter.write("</span>\n<span data-bind=\"visible: isEditMode\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.editSchedulingRule")), jamonWriter);
jamonWriter.write("</span>\n");
}
protected void __jamon_innerUnit__footer(Writer jamonWriter)
throws IOException
{
__jamon_innerUnit__cancelButton(jamonWriter);
jamonWriter.write("\n<button class=\"btn\" data-bind=\"click: onOK, css: { 'btn-primary': enableOKButton }, enable: enableOKButton\"><span data-bind=\"if: isAddMode\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.create")), jamonWriter);
jamonWriter.write("</span><span data-bind=\"if: isEditMode\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.save")), jamonWriter);
jamonWriter.write("</span>\n <i data-bind=\"css: { 'cui-spinner': isSaving }\"></i>\n</button>\n");
}
protected void __jamon_innerUnit__end(Writer jamonWriter)
throws IOException
{
jamonWriter.write("<!-- Renders the content of an Add/Edit Rule dialog. $data is a Rule -->\n<script type=\"text/html\" id=\"tmpl-rman-edit-rule\">\n<!-- Enable Schedule [ Select One v ] -->\n<div class=\"control-group\">\n <label class=\"control-label\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.pool.configSet")), jamonWriter);
jamonWriter.write("</label>\n <div class=\"controls\">\n <!-- ko if: $parent.mode() === 'edit' -->\n <span class=\"uneditable-input\" data-bind=\"text: scheduleName\"></span>\n <!-- /ko -->\n <!-- ko if: $parent.mode() === 'add' -->\n <label class=\"radio\">\n <input type=\"radio\" name=\"showingNewScheduleName\" value=\"true\" data-bind=\"checked: showingNewScheduleName.editing\"/>\n <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.pool.configSet.createNew")), jamonWriter);
jamonWriter.write("</span>\n </label>\n <p class=\"help-block\" data-bind=\"visible: showingNewScheduleName\">\n <input type=\"text\" placeholder=\"");
Escaping.STRICT_HTML.write(StandardEmitter.valueOf(I18n.t("label.name")), jamonWriter);
jamonWriter.write("\" data-bind=\"value: newScheduleName, valueUpdate: 'afterkeydown'\"/>\n <span class=\"help-inline\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.pool.configSet.cloneFrom")), jamonWriter);
jamonWriter.write("</span> \n <select data-bind=\"options: existingScheduleNames, value: newScheduleNameSource\"></select>\n <span class=\"help-block\" data-bind=\"visible: !isNewScheduleNameExisting()\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.pool.configSet.cloneFrom.tip")), jamonWriter);
jamonWriter.write("</span>\n <span class=\"help-inline error\" data-bind=\"visible: isNewScheduleNameExisting\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.nameAlreadyExists")), jamonWriter);
jamonWriter.write("</span>\n </p>\n <p/>\n <label class=\"radio\">\n <input type=\"radio\" name=\"showingNewScheduleName\" value=\"false\" data-bind=\"checked: showingNewScheduleName.editing, disable: existingScheduleNames().length === 1\"/>\n <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.pool.configSet.existing")), jamonWriter);
jamonWriter.write("</span>\n </label>\n <div class=\"help-inline btn-group inline-block\" data-bind=\"visible: !showingNewScheduleName()\">\n <a class=\"btn dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\" data-bind=\"css: { 'error': !showingNewScheduleName() && scheduleName() === undefined }\">\n <!-- ko if: scheduleName() !== undefined -->\n <span data-bind=\"text: scheduleName\"></span>\n <!-- /ko -->\n\n <!-- ko if: scheduleName() === undefined -->\n <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.selectOne")), jamonWriter);
jamonWriter.write("</span>\n <!-- /ko -->\n\n <span class='caret'></span>\n </a>\n <ul class=\"dropdown-menu\">\n <!-- ko if: existingScheduleNames().length > 1 -->\n <!-- ko foreach: existingScheduleNames -->\n <!-- ko if: $data !== 'default' -->\n <li>\n <a href=\"#\" data-bind=\"click: function() { $parent.scheduleName($data); $parent.showingNewScheduleName(false); }\"><span data-bind=\"text: $data\"></span></a>\n </li>\n <!-- /ko -->\n <!-- /ko -->\n <!-- /ko -->\n </ul>\n </div>\n <!-- /ko -->\n </div>\n</div>\n\n<!-- Repeat Type [x] Repeat -->\n<div class=\"control-group\">\n <label class=\"control-label\">\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.rule.repeat")), jamonWriter);
jamonWriter.write("\n </label>\n <div class=\"controls\">\n <label class=\"checkbox\">\n <input type=\"checkbox\" data-bind=\"checked: repeat\"/>\n </label>\n </div>\n</div>\n\n<!-- [ Daily, Weekly*, Monthly] -->\n<div class=\"control-group\" data-bind=\"visible: repeat()\">\n <div class=\"controls\">\n <select data-bind=\"visible: repeat, options: repeatTypes, optionsText: 'label', optionsValue: 'name', value: repeatSelection\"></select>\n </div>\n</div>\n\n<!-- Repeat On [ 2 ] -->\n<div class=\"control-group\" data-bind=\"visible: repeat() && repeatSelection() === 'MONTHLY_BY_DATE'\">\n <label class=\"control-label\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.rule.repeatOn")), jamonWriter);
jamonWriter.write("</label>\n <div class=\"controls\">\n <select class=\"input-mini\" data-bind=\"options: datesOfMonth, value: dateOfMonth\"></select>\n </div>\n</div>\n\n<!-- Repeat On [ ] Sun, [ ] Mon, [ ] Tue ... [ ] Sat -->\n<div class=\"control-group\" data-bind=\"visible: repeat() && repeatSelection() === 'WEEKLY'\">\n <label class=\"control-label\">");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.rule.repeatOn")), jamonWriter);
jamonWriter.write("</label>\n <div class=\"controls\">\n <label class=\"checkbox inlineBlock\"><input type=\"checkbox\" data-bind=\"checked: daysOfWeek\" value=\"7\"/> <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.weekday.sun")), jamonWriter);
jamonWriter.write("</span></label>\n <label class=\"checkbox inlineBlock\"><input type=\"checkbox\" data-bind=\"checked: daysOfWeek\" value=\"1\"/> <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.weekday.mon")), jamonWriter);
jamonWriter.write("</span></label>\n <label class=\"checkbox inlineBlock\"><input type=\"checkbox\" data-bind=\"checked: daysOfWeek\" value=\"2\"/> <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.weekday.tue")), jamonWriter);
jamonWriter.write("</span></label>\n <label class=\"checkbox inlineBlock\"><input type=\"checkbox\" data-bind=\"checked: daysOfWeek\" value=\"3\"/> <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.weekday.wed")), jamonWriter);
jamonWriter.write("</span></label>\n <label class=\"checkbox inlineBlock\"><input type=\"checkbox\" data-bind=\"checked: daysOfWeek\" value=\"4\"/> <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.weekday.thu")), jamonWriter);
jamonWriter.write("</span></label>\n <label class=\"checkbox inlineBlock\"><input type=\"checkbox\" data-bind=\"checked: daysOfWeek\" value=\"5\"/> <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.weekday.fri")), jamonWriter);
jamonWriter.write("</span></label>\n <label class=\"checkbox inlineBlock\"><input type=\"checkbox\" data-bind=\"checked: daysOfWeek\" value=\"6\"/> <span>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.weekday.sat")), jamonWriter);
jamonWriter.write("</span></label>\n </div>\n</div>\n\n<!-- [ ] All Day -->\n<div class=\"control-group\" data-bind=\"visible: repeat()\">\n <div class=\"controls\">\n <label class=\"checkbox\">\n <input type=\"checkbox\" data-bind=\"checked: isAllDay\"/>");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.rman.rule.allDay")), jamonWriter);
jamonWriter.write("\n </label>\n </div>\n</div>\n\n<div class=\"control-group\" data-bind=\"visible: repeat() && !isAllDay()\">\n <label class=\"control-label\">\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.between")), jamonWriter);
jamonWriter.write("\n </label>\n <div class=\"controls\">\n <select class=\"input-medium\" data-bind=\"enable: !isAllDay(), options: hours, value: fromHour, optionsText: 'label', optionsValue: 'value'\"></select>\n <select class=\"input-medium\" data-bind=\"enable: !isAllDay(), options: hours, value: toHour, optionsText: 'label', optionsValue: 'value'\"></select>\n </div>\n</div>\n\n<div class=\"control-group\" data-bind=\"visible: !repeat()\">\n <label class=\"control-label\">\n ");
Escaping.HTML.write(StandardEmitter.valueOf(I18n.t("label.on")), jamonWriter);
jamonWriter.write("\n </label>\n <div class=\"controls\">\n <input type=\"text\" class=\"input-medium\" name=\"fromDate\" placeholder=\"\"/> (<span data-bind=\"text: timezoneDisplayName\"></span>) —\n <input type=\"text\" class=\"input-medium\" name=\"toDate\" placeholder=\"\"/> (<span data-bind=\"text: timezoneDisplayName\"></span>)\n <span data-bind=\"text: durationText, visible: duration() > 0\"></span>\n </div>\n</div>\n\n");
if (Environment.getDevMode())
{
jamonWriter.write("\nFirst Occurrence: <span data-bind=\"text: firstOccurrenceDate\"></span>\nDuration: <span data-bind=\"text: durationText\"></span>\n");
}
jamonWriter.write("\n</script>\n");
}
} | gpl-3.0 |
TinyGroup/tiny | web/org.tinygroup.weblayer/src/main/java/org/tinygroup/weblayer/webcontext/session/impl/SessionModelImpl.java | 5304 | /**
* Copyright (c) 1997-2013, www.tinygroup.org (luo_guo@icloud.com).
*
* Licensed under the GPL, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tinygroup.weblayer.webcontext.session.impl;
import org.tinygroup.commons.tools.ToStringBuilder;
import org.tinygroup.commons.tools.ToStringBuilder.MapBuilder;
import org.tinygroup.weblayer.webcontext.session.SessionConfig;
import org.tinygroup.weblayer.webcontext.session.SessionModel;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import static org.tinygroup.commons.tools.Assert.assertNotNull;
/**
* 代表一个session本身的信息。该对象是可序列化的。
*
* @author Michael Zhou
*/
public class SessionModelImpl implements SessionModel {
private transient SessionConfig sessionConfig;
private String sessionID;
private long creationTime;
private long lastAccessedTime;
private int maxInactiveInterval;
public SessionModelImpl(SessionImpl session) {
setSession(session);
reset();
}
public SessionModelImpl(String sessionID, long creationTime, long lastAccessedTime, int maxInactiveInterval) {
this.sessionID = sessionID;
this.creationTime = creationTime;
this.lastAccessedTime = lastAccessedTime;
this.maxInactiveInterval = maxInactiveInterval;
}
private SessionConfig getSessionConfig() {
return assertNotNull(sessionConfig, "sessionConfig");
}
public void reset() {
getSessionConfig();
this.creationTime = System.currentTimeMillis();
this.lastAccessedTime = creationTime;
this.maxInactiveInterval = sessionConfig.getMaxInactiveInterval();
}
/** 设置model所在的session。 */
public void setSession(SessionImpl session) {
this.sessionConfig = session.getSessionWebContext().getSessionConfig();
this.sessionID = session.getId();
}
/**
* 取得session ID。
*
* @return session ID
*/
public String getSessionID() {
return sessionID;
}
/**
* 取得session的创建时间。
*
* @return 创建时间戮
*/
public long getCreationTime() {
return creationTime;
}
/**
* 取得最近访问时间。
*
* @return 最近访问时间戮
*/
public long getLastAccessedTime() {
return lastAccessedTime;
}
/**
* 取得session的最大不活动期限,超过此时间,session就会失效。
*
* @return 不活动期限的秒数
*/
public int getMaxInactiveInterval() {
return maxInactiveInterval;
}
/**
* 设置session的最大不活动期限,超过此时间,session就会失效。
*
* @param maxInactiveInterval 不活动期限的秒数
*/
public void setMaxInactiveInterval(int maxInactiveInterval) {
this.maxInactiveInterval = maxInactiveInterval;
}
/**
* 判断session有没有过期。
*
* @return 如果过期了,则返回<code>true</code>
*/
public boolean isExpired() {
int maxInactiveInterval = getMaxInactiveInterval();
long forceExpirationPeriod = getSessionConfig().getForceExpirationPeriod();
long current = System.currentTimeMillis();
// 如果从创建之时算起,已经超过了forceExpirationPeriod,则强制作废。
if (forceExpirationPeriod > 0) {
long expires = getCreationTime() + forceExpirationPeriod * 1000;
if (expires < current) {
return true;
}
}
// 如果从上次访问时间算起,已经超过maxInactiveInterval没动静了,则作废。
if (maxInactiveInterval > 0) {
long expires = getLastAccessedTime() + maxInactiveInterval * 1000;
if (expires < current) {
return true;
}
}
return false;
}
/** 更新session的访问时间。 */
public void touch() {
lastAccessedTime = System.currentTimeMillis();
}
public String toString() {
MapBuilder mb = new MapBuilder();
DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US);
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
mb.append("sessionID", sessionID);
mb.append("creationTime", creationTime <= 0 ? "n/a" : fmt.format(new Date(creationTime)));
mb.append("lastAccessedTime", lastAccessedTime <= 0 ? "n/a" : fmt.format(new Date(lastAccessedTime)));
mb.append("maxInactiveInterval", maxInactiveInterval);
return new ToStringBuilder().append("SessionModel").append(mb).toString();
}
}
| gpl-3.0 |
cdbfoster/recraft | source/recraft/core/InputDevice.java | 1970 | /********************************************************************************
* *
* This file is part of Recraft. *
* *
* Recraft 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. *
* *
* Recraft 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 Recraft. If not, see <http://www.gnu.org/licenses/>. *
* *
* Copyright 2012 Chris Foster. *
* *
********************************************************************************/
package recraft.core;
public interface InputDevice
{
String getName();
Input getInputState();
boolean receiveBinding(InputBinding binding);
void resetBindings();
public static interface InputBinding
{
String getBindingString();
boolean isActive();
Object getValue();
boolean receive();
void reset();
}
}
| gpl-3.0 |
azyrus66/newmod | src/main/java/azyrus66/newmod/item/tool/ItemSword.java | 618 | package azyrus66.newmod.item.tool;
import azyrus66.newmod.item.ItemModelProvider;
import azyrus66.newmod.newmod;
import net.minecraft.item.Item;
public class ItemSword extends net.minecraft.item.ItemSword implements ItemModelProvider {
private String name;
public ItemSword(ToolMaterial material, String name) {
super(material);
setUnlocalizedName(name);
setRegistryName(name);
setCreativeTab(newmod.creativeTab);
this.name = name;
}
@Override
public void registerItemModel(Item item) {
newmod.proxy.registerItemRenderer(this, 0, name);
}
}
| gpl-3.0 |
Kittychanley/TFCraft | src/Common/com/bioxx/tfc/Handlers/Client/FarmlandHighlightHandler.java | 15108 | package com.bioxx.tfc.Handlers.Client;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
import org.lwjgl.opengl.GL11;
import com.bioxx.tfc.TFCBlocks;
import com.bioxx.tfc.TFCItems;
import com.bioxx.tfc.Core.TFC_Time;
import com.bioxx.tfc.Core.Player.PlayerManagerTFC;
import com.bioxx.tfc.Food.CropIndex;
import com.bioxx.tfc.Food.CropManager;
import com.bioxx.tfc.Items.Tools.ItemCustomHoe;
import com.bioxx.tfc.TileEntities.TECrop;
import com.bioxx.tfc.TileEntities.TEFarmland;
import com.bioxx.tfc.api.TFCOptions;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class FarmlandHighlightHandler
{
@SubscribeEvent
public void DrawBlockHighlightEvent(DrawBlockHighlightEvent evt)
{
World world = evt.player.worldObj;
double var8 = evt.player.lastTickPosX + (evt.player.posX - evt.player.lastTickPosX) * evt.partialTicks;
double var10 = evt.player.lastTickPosY + (evt.player.posY - evt.player.lastTickPosY) * evt.partialTicks;
double var12 = evt.player.lastTickPosZ + (evt.player.posZ - evt.player.lastTickPosZ) * evt.partialTicks;
boolean isMetalHoe = false;
if(evt.currentItem != null &&
evt.currentItem.getItem() != TFCItems.IgInHoe &&
evt.currentItem.getItem() != TFCItems.IgExHoe &&
evt.currentItem.getItem() != TFCItems.SedHoe &&
evt.currentItem.getItem() != TFCItems.MMHoe)
{
isMetalHoe = true;
}
if(evt.currentItem != null && evt.currentItem.getItem() instanceof ItemCustomHoe && isMetalHoe && PlayerManagerTFC.getInstance().getClientPlayer().hoeMode == 1)
{
Block b = world.getBlock(evt.target.blockX,evt.target.blockY,evt.target.blockZ);
int crop = 0;
if(b == TFCBlocks.Crops && (
world.getBlock(evt.target.blockX, evt.target.blockY - 1, evt.target.blockZ) == TFCBlocks.tilledSoil ||
world.getBlock(evt.target.blockX, evt.target.blockY - 1, evt.target.blockZ) == TFCBlocks.tilledSoil2))
{
b = TFCBlocks.tilledSoil;
crop = 1;
}
if(b == TFCBlocks.tilledSoil || b == TFCBlocks.tilledSoil2)
{
TEFarmland te = (TEFarmland) world.getTileEntity(evt.target.blockX, evt.target.blockY - crop, evt.target.blockZ);
te.requestNutrientData();
float timeMultiplier = TFC_Time.daysInYear / 360f;
int soilMax = (int) (25000 * timeMultiplier);
//Setup GL for the depthbox
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_CULL_FACE);
//GL11.glLineWidth(6.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(false);
double offset = 0;
double fertilizer = 1.02 + ((double)te.nutrients[3] / (double)soilMax)*0.5;
GL11.glColor4ub(TFCOptions.cropFertilizerColor[0], TFCOptions.cropFertilizerColor[1], TFCOptions.cropFertilizerColor[2], TFCOptions.cropFertilizerColor[3]);
drawBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop,
evt.target.blockZ,
evt.target.blockX + 1,
evt.target.blockY + fertilizer - crop,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
double nutrient = 1.02 + ((double)te.nutrients[0] / (double)soilMax) * 0.5;
GL11.glColor4ub(TFCOptions.cropNutrientAColor[0], TFCOptions.cropNutrientAColor[1], TFCOptions.cropNutrientAColor[2], TFCOptions.cropNutrientAColor[3]);
drawBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop + fertilizer - 1.02,
evt.target.blockZ,
evt.target.blockX + offset + 0.3333,
evt.target.blockY + nutrient - crop + fertilizer - 1.02,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
offset = 0.3333;
nutrient = 1.02 + ((double)te.nutrients[1] / (double)soilMax) * 0.5;
GL11.glColor4ub(TFCOptions.cropNutrientBColor[0], TFCOptions.cropNutrientBColor[1], TFCOptions.cropNutrientBColor[2], TFCOptions.cropNutrientBColor[3]);
drawBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop + fertilizer - 1.02,
evt.target.blockZ,
evt.target.blockX + offset + 0.3333,
evt.target.blockY + nutrient - crop + fertilizer - 1.02,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
offset = 0.6666;
nutrient = 1.02 + ((double)te.nutrients[2] / (double)soilMax) * 0.5;
GL11.glColor4ub(TFCOptions.cropNutrientCColor[0], TFCOptions.cropNutrientCColor[1], TFCOptions.cropNutrientCColor[2], TFCOptions.cropNutrientCColor[3]);
drawBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop + fertilizer - 1.02,
evt.target.blockZ,
evt.target.blockX + offset + 0.3333,
evt.target.blockY + nutrient - crop + fertilizer - 1.02,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
GL11.glEnable(GL11.GL_CULL_FACE);
/**
* Draw the outliens around the boxes
* */
GL11.glColor4f(0.1F, 0.1F, 0.1F, 1.0F);
GL11.glLineWidth(3.0F);
GL11.glDepthMask(false);
offset = 0;
drawOutlinedBoundingBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop,
evt.target.blockZ,
evt.target.blockX + 1,
evt.target.blockY + fertilizer - crop,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
nutrient = 1.02 + ((double)te.nutrients[0] / (double)soilMax) * 0.5;
drawOutlinedBoundingBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop + fertilizer - 1.02,
evt.target.blockZ,
evt.target.blockX + offset + 0.3333,
evt.target.blockY + nutrient - crop + fertilizer - 1.02,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
offset = 0.3333;
nutrient = 1.02 + ((double)te.nutrients[1] / (double)soilMax) * 0.5;
drawOutlinedBoundingBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop + fertilizer - 1.02,
evt.target.blockZ,
evt.target.blockX + offset + 0.3333,
evt.target.blockY + nutrient - crop + fertilizer - 1.02,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
offset = 0.6666;
nutrient = 1.02 + ((double)te.nutrients[2] / (double)soilMax) * 0.5;
drawOutlinedBoundingBox(AxisAlignedBB.getBoundingBox(
evt.target.blockX + offset,
evt.target.blockY + 1.01 - crop + fertilizer - 1.02,
evt.target.blockZ,
evt.target.blockX + offset + 0.3333,
evt.target.blockY + nutrient - crop + fertilizer - 1.02,
evt.target.blockZ + 1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
}
}
else if(evt.currentItem != null && evt.currentItem.getItem() instanceof ItemCustomHoe &&
PlayerManagerTFC.getInstance().getClientPlayer().hoeMode == 2)
{
Block b = world.getBlock(evt.target.blockX,evt.target.blockY,evt.target.blockZ);
int crop = 0;
if(b == TFCBlocks.Crops && (
world.getBlock(evt.target.blockX,evt.target.blockY-1,evt.target.blockZ) == TFCBlocks.tilledSoil ||
world.getBlock(evt.target.blockX,evt.target.blockY-1,evt.target.blockZ) == TFCBlocks.tilledSoil2))
{
b = TFCBlocks.tilledSoil;
crop = 1;
}
if(b == TFCBlocks.tilledSoil || b == TFCBlocks.tilledSoil2)
{
boolean water = com.bioxx.tfc.Blocks.BlockFarmland.isFreshWaterNearby(world, evt.target.blockX, evt.target.blockY-crop, evt.target.blockZ);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(water)
GL11.glColor4ub((byte)14, (byte)23, (byte)212, (byte)200);
else
GL11.glColor4ub((byte)0, (byte)0, (byte)0, (byte)200);
GL11.glDisable(GL11.GL_CULL_FACE);
//GL11.glLineWidth(6.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(false);
drawFace(AxisAlignedBB.getBoundingBox(
evt.target.blockX,
evt.target.blockY + 1.01 - crop,
evt.target.blockZ,
evt.target.blockX+1,
evt.target.blockY + 1.02 - crop,
evt.target.blockZ+1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
GL11.glEnable(GL11.GL_CULL_FACE);
}
}
else if(evt.currentItem != null && evt.currentItem.getItem() instanceof ItemCustomHoe &&
PlayerManagerTFC.getInstance().getClientPlayer().hoeMode == 3)
{
Block b = world.getBlock(evt.target.blockX,evt.target.blockY,evt.target.blockZ);
if(b == TFCBlocks.Crops && (
world.getBlock(evt.target.blockX,evt.target.blockY-1,evt.target.blockZ) == TFCBlocks.tilledSoil ||
world.getBlock(evt.target.blockX,evt.target.blockY-1,evt.target.blockZ) == TFCBlocks.tilledSoil2))
{
TECrop te = (TECrop) world.getTileEntity(evt.target.blockX, evt.target.blockY, evt.target.blockZ);
CropIndex index = CropManager.getInstance().getCropFromId(te.cropId);
boolean fullyGrown = te.growth >= index.numGrowthStages;
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(fullyGrown)
GL11.glColor4ub((byte)64, (byte)200, (byte)37, (byte)200);
else
GL11.glColor4ub((byte)200, (byte)37, (byte)37, (byte)200);
GL11.glDisable(GL11.GL_CULL_FACE);
//GL11.glLineWidth(6.0F);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(false);
drawFace(AxisAlignedBB.getBoundingBox(
evt.target.blockX,
evt.target.blockY + 0.01,
evt.target.blockZ,
evt.target.blockX+1,
evt.target.blockY + 0.02,
evt.target.blockZ+1
).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12));
GL11.glEnable(GL11.GL_CULL_FACE);
}
}
}
void drawFace(AxisAlignedBB par1AxisAlignedBB)
{
Tessellator var2 = Tessellator.instance;
//Top
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.draw();
}
void drawBox(AxisAlignedBB par1AxisAlignedBB)
{
Tessellator var2 = Tessellator.instance;
//Top
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.draw();
//-x
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.draw();
//+x
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.draw();
//-z
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.draw();
//+z
var2.startDrawing(GL11.GL_QUADS);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.draw();
}
void drawOutlinedBoundingBox(AxisAlignedBB par1AxisAlignedBB)
{
Tessellator var2 = Tessellator.instance;
var2.startDrawing(3);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.draw();
var2.startDrawing(3);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.draw();
var2.startDrawing(GL11.GL_LINES);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ);
var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ);
var2.draw();
}
}
| gpl-3.0 |
umlet/umlet | umlet-elements/src/test/java/com/baselet/element/sticking/StickablesTest.java | 4374 | package com.baselet.element.sticking;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baselet.control.basics.geom.PointDouble;
import com.baselet.element.sticking.StickingPolygon.StickLine;
public class StickablesTest {
@Test
public void moveLineLeft40_pointLeft40() throws Exception {
PointChange change = calcChange(point(20, 20), vLine(20, 10, 30), -40, 0);
assertPoint(-40, 0, change);
}
@Test
public void moveLineRight40_pointRight40() throws Exception {
PointChange change = calcChange(point(20, 20), vLine(20, 10, 30), 40, 0);
assertPoint(40, 0, change);
}
@Test
public void moveLineUp40_pointUp40() throws Exception {
PointChange change = calcChange(point(20, 20), hLine(10, 30, 20), 0, -40);
assertPoint(0, -40, change);
}
@Test
public void moveLineLeftDown40_pointLeftDown40() throws Exception {
PointChange change = calcChange(point(20, 20), hLine(10, 30, 20), 40, 40);
assertPoint(40, 40, change);
}
@Test
public void moveLineRightDown10_pointRightDown10() throws Exception {
PointChange change = calcChange(point(20, 20), vLine(20, 10, 30), 10, 10);
assertPoint(10, 10, change);
}
@Test
public void resizeLineVertical_pointStaysSame() throws Exception {
PointChange change = calcChange(point(20, 20), vLine(20, 10, 80), vLine(20, 10, 20));
assertPoint(0, 0, change);
}
@Test
public void resizeLineVertical_pointMovesToLowerEnd() throws Exception {
PointChange change = calcChange(point(20, 70), vLine(20, 10, 80), vLine(20, 10, 30));
assertPoint(0, -40, change);
}
@Test
public void resizeLineHorizontal_pointStaysOnLeftEnd() throws Exception {
PointChange change = calcChange(point(20, 50), hLine(20, 150, 50), hLine(100, 150, 50));
assertPoint(80, 0, change);
}
@Test
public void resizeLineVertical_pointStaysOnUpperEnd() throws Exception {
PointChange change = calcChange(point(20, 50), vLine(20, 50, 200), vLine(20, 150, 200));
assertPoint(0, 100, change);
}
@Test
public void resizeLineHorizontal_pointStaysSame() throws Exception {
PointChange change = calcChange(point(20, 50), hLine(20, 150, 50), hLine(100, 150, 50));
assertPoint(80, 0, change);
}
@Test
public void moveHorizontalResizeVertical_pointMovesHorizontalAndStaysSameVertical() throws Exception {
PointChange change = calcChange(point(100, 100), vLine(100, 10, 200), vLine(60, 10, 150));
assertPoint(-40, 0, change);
}
@Test
public void moveHorizontalResizeVertical_pointMovesHorizontalAndMovesToEndVertical() throws Exception {
PointChange change = calcChange(point(50, 50), vLine(50, 10, 200), vLine(100, 10, 30));
assertPoint(50, -20, change);
}
@Test
public void moveVerticalResizeHorizontal_pointMovesVerticalAndStaysSameHorizontal() throws Exception {
PointChange change = calcChange(point(50, 50), hLine(10, 200, 50), hLine(10, 50, 100));
assertPoint(0, 50, change);
}
@Test
public void moveVerticalResizeHorizontal_pointMovesVerticalAndStaysOnLeftEnd() throws Exception {
PointChange change = calcChange(point(50, 50), hLine(10, 200, 50), hLine(10, 20, 100));
assertPoint(-30, 50, change);
}
private void assertPoint(int x, int y, PointChange change) {
assertEquals("correct x movement", x, change.getDiffX());
assertEquals("correct y movement", y, change.getDiffY());
}
private PointChange calcChange(PointDouble point, StickLine oldLine, int xChange, int yChange) {
PointDouble oStart = oldLine.getStart();
PointDouble oEnd = oldLine.getEnd();
return Stickables.calcPointDiffBasedOnStickLineChange(0, point, new StickLineChange(oldLine, line(oStart.getX() + xChange, oStart.getY() + yChange, oEnd.getX() + xChange, oEnd.getY() + yChange)));
}
private PointChange calcChange(PointDouble point, StickLine oldLine, StickLine newLine) {
return Stickables.calcPointDiffBasedOnStickLineChange(0, point, new StickLineChange(oldLine, newLine));
}
private static PointDouble point(double x, double y) {
return new PointDouble(x, y);
}
private static StickLine line(double xStart, double yStart, double xEnd, double yEnd) {
return new StickLine(point(xStart, yStart), point(xEnd, yEnd));
}
private static StickLine hLine(double xStart, double xEnd, double y) {
return line(xStart, y, xEnd, y);
}
private static StickLine vLine(double x, double yStart, double yEnd) {
return line(x, yStart, x, yEnd);
}
}
| gpl-3.0 |
RTykulsker/JavaBeanstalkClient | src/main/java/com/surftools/BeanstalkClientImpl/ExpectedResponse.java | 1252 | package com.surftools.BeanstalkClientImpl;
/*
Copyright 2009-2020 Robert Tykulsker
This file is part of JavaBeanstalkCLient.
JavaBeanstalkCLient 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, or alternatively, the BSD license supplied
with this project in the file "BSD-LICENSE".
JavaBeanstalkCLient 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 JavaBeanstalkCLient. If not, see <http://www.gnu.org/licenses/>.
*/
public enum ExpectedResponse {
None(0), ByteArray(1), List(2), Map(3);
private int id = 0;
ExpectedResponse(int id) {
this.id = id;
}
public int getId() {
return id;
}
public static ExpectedResponse getById(int id) {
for (ExpectedResponse t : values()) {
if (t.id == id) {
return t;
}
}
return null;
}
}
| gpl-3.0 |
ticktockdata/test-drive-1 | ClassicAccDatePicker.java | 3935 | package classicacctapp;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXDatePicker;
/**
* Adds a custom listener to deal with date formatting where input is 1/1/15
* and you want date to be 1/1/2015
*
* @author jaz
*/
public class ClassicAccDatePicker extends JXDatePicker {
private static final Logger logger = Logger.getLogger(ClassicAccDatePicker.class);
public ClassicAccDatePicker() {
addPropertyChangeListener(new java.beans.PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
fixDate();
}
});
// KeyListener added to add year to abbreviated text (2016-04-21, JAM)
getEditor().addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent ke) {
// Only run when Enter pressed
if (ke.getKeyChar() == KeyEvent.VK_ENTER) addYear();
}
});
// FocusListener added to add year to abbreviated text (2016-04-21, JAM)
getEditor().addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent fe) {
addYear();
}
});
}
/**
* This method does sets year to current if date typed w/o year.<br>
* Also parses date if entered with period or dash instead of slash.<br>
* Should not be any need for this method to be public.<br>
* Needed to trap this before the PropertyChange event, couldn't
* accomplish it with single event, used keyPressed and focusLost.<br>
* @author JAM
* @since 2016-04-21, version 2.4.2.1
*/
private void addYear() {
// Get the control's text
String sText = getEditor().getText();
if (sText == null || sText.equals("")) return;
if (sText.matches(".*/.*/..*")) return; // exit ASAP if valid!
SimpleDateFormat format = new SimpleDateFormat( "MM/dd/yy" );
String current = format.format(Calendar.getInstance().getTime());
String a1[] = null;
// Try splitting with / - or .
if (sText.contains("-")) sText = sText.replace("-", "/");
else if (sText.contains(".")) sText = sText.replace(".", "/");
if (sText.contains("/")) a1 = sText.split("/");
// If split done, then generate to date
if (a1 != null) { // if split, then parse to date
switch (a1.length) {
case 3:
sText = a1[0] + "/" + a1[1] + "/" + a1[2];
break;
case 2:
sText = a1[0] + "/" + a1[1] + "/" + current.split("/")[2];
break;
default:
return; // parse error, do nothing
}
getEditor().setText(sText);
}
// If not splittable, then check if now or today
if (sText.toLowerCase().contains("today")
|| sText.toLowerCase().contains("now")) {
getEditor().setText(current);
}
}
public void fixDate() {
Date current = getDate();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1970);
Date cutoff = cal.getTime();
if (current != null && current.compareTo(cutoff) < 0)
{
SimpleDateFormat format = new SimpleDateFormat( "MM/dd/yy" );
String currentFormat = format.format(current);
try {
Date good = format.parse(currentFormat);
setDate(good);
} catch (ParseException ex) {
logger.error("", ex);
}
}
}
}
| gpl-3.0 |