repo_name
stringlengths 5
108
| path
stringlengths 6
333
| size
stringlengths 1
6
| content
stringlengths 4
977k
| license
stringclasses 15
values |
---|---|---|---|---|
ohtuprojekti/OKKoPa_all | OKKoPa_core/src/main/java/fi/helsinki/cs/okkopa/main/stage/GetEmailStage.java | 2409 | package fi.helsinki.cs.okkopa.main.stage;
import fi.helsinki.cs.okkopa.mail.read.EmailRead;
import fi.helsinki.cs.okkopa.main.ExceptionLogger;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.mail.Message;
import javax.mail.MessagingException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Retrieves new emails and processes the attachments one by one by calling the next stage repeatedly.
*/
@Component
public class GetEmailStage extends Stage<Object, InputStream> {
private static final Logger LOGGER = Logger.getLogger(GetEmailStage.class.getName());
private EmailRead emailReader;
private ExceptionLogger exceptionLogger;
/**
*
* @param server
* @param exceptionLogger
*/
@Autowired
public GetEmailStage(EmailRead server, ExceptionLogger exceptionLogger) {
this.exceptionLogger = exceptionLogger;
this.emailReader = server;
}
@Override
public void process(Object in) {
try {
emailReader.connect();
LOGGER.debug("Kirjauduttu sisään.");
loopMessagesAsLongAsThereAreNew();
LOGGER.debug("Ei lisää viestejä.");
} catch (MessagingException | IOException ex) {
exceptionLogger.logException(ex);
} finally {
emailReader.closeQuietly();
}
}
private void processAttachments(Message nextMessage) throws MessagingException, IOException {
List<InputStream> messagesAttachments = emailReader.getMessagesAttachments(nextMessage);
for (InputStream attachment : messagesAttachments) {
LOGGER.debug("Käsitellään liitettä.");
processNextStages(attachment);
IOUtils.closeQuietly(attachment);
}
}
private void loopMessagesAsLongAsThereAreNew() throws MessagingException, IOException {
Message nextMessage = emailReader.getNextMessage();
while (nextMessage != null) {
LOGGER.debug("Sähköposti haettu.");
processAttachments(nextMessage);
emailReader.cleanUpMessage(nextMessage);
nextMessage = emailReader.getNextMessage();
}
}
}
| mit |
blackphenol/SimpleSpring | src/main/java/simple/practice/Greeting.java | 438 | package simple.practice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import simple.practice.service.GreetingService;
@Component
public class Greeting {
@Autowired
private GreetingService greetingService;
public String printGreeting(String name){
String msg = greetingService.greetingMessage() + " User: " + name;
System.out.println(msg);
return msg;
}
}
| mit |
sftrabbit/StackAnswers | src/uk/co/sftrabbit/stackanswers/fragment/AuthInfoFragment.java | 1678 | /*
* Copyright (C) 2013 Joseph Mansfield
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package uk.co.sftrabbit.stackanswers.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import uk.co.sftrabbit.stackanswers.R;
public class AuthInfoFragment extends Fragment {
public AuthInfoFragment() {
// Do nothing
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.authentication_info, container, false);
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/product/dao/impl/SkuSaleMappingDaoImpl.java | 419 | package com.swfarm.biz.product.dao.impl;
import com.swfarm.biz.product.bo.SkuSaleMapping;
import com.swfarm.biz.product.dao.SkuSaleMappingDao;
import com.swfarm.pub.framework.dao.GenericDaoHibernateImpl;
public class SkuSaleMappingDaoImpl extends GenericDaoHibernateImpl<SkuSaleMapping, Long> implements SkuSaleMappingDao {
public SkuSaleMappingDaoImpl(Class<SkuSaleMapping> type) {
super(type);
}
} | mit |
manniwood/cl4pg | src/test/java/com/manniwood/cl4pg/v1/test/types/IntegerSmallIntTest.java | 5707 | /*
The MIT License (MIT)
Copyright (c) 2014 Manni Wood
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.manniwood.cl4pg.v1.test.types;
import com.manniwood.cl4pg.v1.datasourceadapters.DataSourceAdapter;
import com.manniwood.cl4pg.v1.PgSession;
import com.manniwood.cl4pg.v1.datasourceadapters.PgSimpleDataSourceAdapter;
import com.manniwood.cl4pg.v1.commands.DDL;
import com.manniwood.cl4pg.v1.commands.Insert;
import com.manniwood.cl4pg.v1.commands.Select;
import com.manniwood.cl4pg.v1.resultsethandlers.GuessScalarListHandler;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* Please note that these tests must be run serially, and not all at once.
* Although they depend as little as possible on state in the database, it is
* very convenient to have them all use the same db session; so they are all run
* one after the other so that they don't all trip over each other.
*
* @author mwood
*
*/
public class IntegerSmallIntTest {
private PgSession pgSession;
private DataSourceAdapter adapter;
@BeforeClass
public void init() {
adapter = PgSimpleDataSourceAdapter.buildFromDefaultConfFile();
pgSession = adapter.getSession();
pgSession.run(DDL.config().sql("create temporary table test(col smallint)").done());
pgSession.commit();
}
@AfterClass
public void tearDown() {
pgSession.close();
adapter.close();
}
/**
* Truncate the users table before each test.
*/
@BeforeMethod
public void truncateTable() {
pgSession.run(DDL.config().sql("truncate table test").done());
pgSession.commit();
}
@Test(priority = 1)
public void testValue() {
Integer expected = 3;
pgSession.run(Insert.usingVariadicArgs()
.sql("insert into test (col) values (#{java.lang.Integer})")
.args(expected)
.done());
pgSession.commit();
GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>();
pgSession.run(Select.<Integer> usingVariadicArgs()
.sql("select col from test limit 1")
.resultSetHandler(handler)
.done());
pgSession.rollback();
Integer actual = handler.getList().get(0);
Assert.assertEquals(actual, expected, "scalars must match");
}
@Test(priority = 2)
public void testNull() {
Integer expected = null;
pgSession.run(Insert.usingVariadicArgs()
.sql("insert into test (col) values (#{java.lang.Integer})")
.args(expected)
.done());
pgSession.commit();
GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>();
pgSession.run(Select.<Integer> usingVariadicArgs()
.sql("select col from test limit 1")
.resultSetHandler(handler)
.done());
pgSession.rollback();
Integer actual = handler.getList().get(0);
Assert.assertEquals(actual, expected, "scalars must match");
}
@Test(priority = 3)
public void testSpecialValue1() {
Integer expected = 32767;
pgSession.run(Insert.usingVariadicArgs()
.sql("insert into test (col) values (#{java.lang.Integer})")
.args(expected)
.done());
pgSession.commit();
GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>();
pgSession.run(Select.<Integer> usingVariadicArgs()
.sql("select col from test limit 1")
.resultSetHandler(handler)
.done());
pgSession.rollback();
Integer actual = handler.getList().get(0);
Assert.assertEquals(actual, expected, "scalars must match");
}
@Test(priority = 4)
public void testSpecialValu21() {
Integer expected = -32768;
pgSession.run(Insert.usingVariadicArgs()
.sql("insert into test (col) values (#{java.lang.Integer})")
.args(expected)
.done());
pgSession.commit();
GuessScalarListHandler<Integer> handler = new GuessScalarListHandler<Integer>();
pgSession.run(Select.<Integer> usingVariadicArgs()
.sql("select col from test limit 1")
.resultSetHandler(handler)
.done());
pgSession.rollback();
Integer actual = handler.getList().get(0);
Assert.assertEquals(actual, expected, "scalars must match");
}
}
| mit |
fqc/Java_Basic | src/main/java/com/fqc/jdk8/test06.java | 927 | package com.fqc.jdk8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class test06 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
ArrayList<Integer> list = Arrays.stream(arr).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Set<Integer> set = list.stream().collect(Collectors.toSet());
System.out.println(set.contains(33));
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add(new User("name:" + i));
}
Map<String, User> map = users.stream().collect(Collectors.toMap(u -> u.username, u -> u));
map.forEach((s, user) -> System.out.println(user.username));
}
}
class User {
String username;
public User(String username) {
this.username = username;
}
}
| mit |
rchain/Rholang | src/main/java/rholang/parsing/delimc/Absyn/TType2.java | 753 | package rholang.parsing.delimc.Absyn; // Java Package generated by the BNF Converter.
public class TType2 extends TType {
public final Type type_1, type_2;
public TType2(Type p1, Type p2) { type_1 = p1; type_2 = p2; }
public <R,A> R accept(rholang.parsing.delimc.Absyn.TType.Visitor<R,A> v, A arg) { return v.visit(this, arg); }
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof rholang.parsing.delimc.Absyn.TType2) {
rholang.parsing.delimc.Absyn.TType2 x = (rholang.parsing.delimc.Absyn.TType2)o;
return this.type_1.equals(x.type_1) && this.type_2.equals(x.type_2);
}
return false;
}
public int hashCode() {
return 37*(this.type_1.hashCode())+this.type_2.hashCode();
}
}
| mit |
gggordon/JavaCSVTransform | src/com/igonics/transformers/simple/JavaCSVTransform.java | 4527 | package com.igonics.transformers.simple;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.relique.jdbc.csv.CsvDriver;
import com.igonics.transformers.simple.helpers.CSVDirWalker;
import com.igonics.transformers.simple.helpers.CSVLogger;
/**
* @author gggordon <https://github.com/gggordon>
* @version 1.0.0
* @description Transforms sub-directories of similar CSV files into one database file
* @created 1.11.2015
*
* */
public class JavaCSVTransform {
/**
* @param baseDir Base Directory to Check for CSV Files
* @param dbFile Database File Name or Path
* @param subDirectoryDepth Recursive Depth to check for CSV Files. -1 will recurse indefinitely
* @param keepTemporaryFile Keep Temporary Buffer File or Delete
* */
public void createCSVDatabase(String baseDir, String dbFile,int subDirectoryDepth,boolean keepTemporaryFile){
final String BASE_DIR =baseDir==null? System.getProperty("user.dir") + "\\dataFiles" : baseDir;
final String DB_FILE = dbFile==null?"DB-" + System.currentTimeMillis() + ".csv":dbFile;
long startTime = System.currentTimeMillis();
CSVLogger.info("Base Dir : " + BASE_DIR);
try {
CSVDirWalker dirWalker = new CSVDirWalker(BASE_DIR, subDirectoryDepth);
//Process Directories
dirWalker.start();
CSVLogger.debug("Column Names : " + dirWalker.getHeader());
CSVLogger.info("Temporary Buffer File Complete. Starting Database Queries");
// Writing to database
// Load the driver.
Class.forName("org.relique.jdbc.csv.CsvDriver");
// Create a connection. The first command line parameter is the directory containing the .csv files.
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ System.getProperty("user.dir"));
// Create a Statement object to execute the query with.
Statement stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("SELECT * FROM "
+ dirWalker.getTempBufferPath().replaceAll(".csv", ""));
CSVLogger.info("Retrieved Records From Temporary File");
// Dump out the results to a CSV file with the same format
// using CsvJdbc helper function
CSVLogger.info("Writing Records to database file");
long databaseSaveStartTime = System.currentTimeMillis();
//Create redirect stream to database file
PrintStream printStream = new PrintStream(DB_FILE);
//print column headings
printStream.print(dirWalker.getHeader()+System.lineSeparator());
CsvDriver.writeToCsv(results, printStream, false);
CSVLogger.info("Time taken to save records to database (ms): "+(System.currentTimeMillis() - databaseSaveStartTime));
//delete temporary file
if(!keepTemporaryFile){
CSVLogger.info("Removing Temporary File");
dirWalker.removeTemporaryFile();
}
//Output Program Execution Completed
CSVLogger.info("Total execution time (ms) : "
+ (System.currentTimeMillis() - startTime)
+ " | Approx Size (bytes) : "
+ dirWalker.getTotalBytesRead());
} catch (Exception ioe) {
CSVLogger.error(ioe.getMessage(), ioe);
}
}
// TODO: Modularize Concepts
public static void main(String args[]) {
//Parse Command Line Options
Options opts = new Options();
HelpFormatter formatter = new HelpFormatter();
opts.addOption("d", "dir", false, "Base Directory of CSV files. Default : Current Directory");
opts.addOption("db", "database", false, "Database File Name. Default DB-{timestamp}.csv");
opts.addOption("depth", "depth", false, "Recursive Depth. Set -1 to recurse indefintely. Default : -1");
opts.addOption("keepTemp",false,"Keeps Temporary file. Default : false");
opts.addOption("h", "help", false, "Display Help");
try {
CommandLine cmd = new DefaultParser().parse(opts,args);
if(cmd.hasOption("h") || cmd.hasOption("help")){
formatter.printHelp( "javacsvtransform", opts );
return;
}
//Create CSV Database With Command Line Options or Defaults
new JavaCSVTransform().createCSVDatabase(cmd.getOptionValue("d"), cmd.getOptionValue("db"),Integer.parseInt(cmd.getOptionValue("depth", "-1")), cmd.hasOption("keepTemp"));
} catch (ParseException e) {
formatter.printHelp( "javacsvtransform", opts );
}
}
}
| mit |
adrianherrera/jdivisitor | src/main/java/org/jdivisitor/debugger/launcher/RemoteVMConnector.java | 2991 | /*
* JDIVisitor
* Copyright (C) 2014 Adrian Herrera
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jdivisitor.debugger.launcher;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.Validate;
import com.sun.jdi.Bootstrap;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.AttachingConnector;
import com.sun.jdi.connect.Connector;
/**
* Attach (via a socket) to a listening virtual machine in debug mode.
*
* @author Adrian Herrera
*
*/
public class RemoteVMConnector extends VMConnector {
/**
* Socket connection details.
*/
private final InetSocketAddress socketAddress;
/**
* Constructor.
*
* @param hostname Name of the host to connect to
* @param port Port number the virtual machine is listening on
*/
public RemoteVMConnector(String hostname, int port) {
this(new InetSocketAddress(hostname, port));
}
/**
* Constructor.
*
* @param sockAddr Socket address structure to connect to.
*/
public RemoteVMConnector(InetSocketAddress sockAddr) {
socketAddress = Validate.notNull(sockAddr);
}
@Override
public VirtualMachine connect() throws Exception {
List<AttachingConnector> connectors = Bootstrap.virtualMachineManager()
.attachingConnectors();
AttachingConnector connector = findConnector(
"com.sun.jdi.SocketAttach", connectors);
Map<String, Connector.Argument> arguments = connectorArguments(connector);
VirtualMachine vm = connector.attach(arguments);
// TODO - redirect stdout and stderr?
return vm;
}
/**
* Set the socket-attaching connector's arguments.
*
* @param connector A socket-attaching connector
* @return The socket-attaching connector's arguments
*/
private Map<String, Connector.Argument> connectorArguments(
AttachingConnector connector) {
Map<String, Connector.Argument> arguments = connector
.defaultArguments();
arguments.get("hostname").setValue(socketAddress.getHostName());
arguments.get("port").setValue(
Integer.toString(socketAddress.getPort()));
return arguments;
}
}
| mit |
CatsProject/CycleAssistantTools | mobile/src/main/java/com/catsprogrammer/catsfourthv/MatrixCalculator.java | 2238 | package com.catsprogrammer.catsfourthv;
/**
* Created by C on 2016-09-14.
*/
public class MatrixCalculator {
public static float[] getRotationMatrixFromOrientation(float[] o) {
float[] xM = new float[9];
float[] yM = new float[9];
float[] zM = new float[9];
float sinX = (float) Math.sin(o[1]);
float cosX = (float) Math.cos(o[1]);
float sinY = (float) Math.sin(o[2]);
float cosY = (float) Math.cos(o[2]);
float sinZ = (float) Math.sin(o[0]);
float cosZ = (float) Math.cos(o[0]);
// rotation about x-axis (pitch)
xM[0] = 1.0f;
xM[1] = 0.0f;
xM[2] = 0.0f;
xM[3] = 0.0f;
xM[4] = cosX;
xM[5] = sinX;
xM[6] = 0.0f;
xM[7] = -sinX;
xM[8] = cosX;
// rotation about y-axis (roll)
yM[0] = cosY;
yM[1] = 0.0f;
yM[2] = sinY;
yM[3] = 0.0f;
yM[4] = 1.0f;
yM[5] = 0.0f;
yM[6] = -sinY;
yM[7] = 0.0f;
yM[8] = cosY;
// rotation about z-axis (azimuth)
zM[0] = cosZ;
zM[1] = sinZ;
zM[2] = 0.0f;
zM[3] = -sinZ;
zM[4] = cosZ;
zM[5] = 0.0f;
zM[6] = 0.0f;
zM[7] = 0.0f;
zM[8] = 1.0f;
// rotation order is y, x, z (roll, pitch, azimuth)
float[] resultMatrix = matrixMultiplication(xM, yM);
resultMatrix = matrixMultiplication(zM, resultMatrix); //????????????????왜?????????????
return resultMatrix;
}
public static float[] matrixMultiplication(float[] A, float[] B) {
float[] result = new float[9];
result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];
result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];
return result;
}
}
| mit |
jeslopalo/flash-messages | flash-messages-core/src/main/java/es/sandbox/ui/messages/argument/LinkArgument.java | 2828 | package es.sandbox.ui.messages.argument;
import es.sandbox.ui.messages.resolver.MessageResolver;
import es.sandbox.ui.messages.resolver.Resolvable;
import java.util.ArrayList;
import java.util.List;
class LinkArgument implements Link, Resolvable {
private static final String LINK_FORMAT = "<a href=\"%s\" title=\"%s\" class=\"%s\">%s</a>";
private static final String LINK_FORMAT_WITHOUT_CSS_CLASS = "<a href=\"%s\" title=\"%s\">%s</a>";
private String url;
private Text text;
private String cssClass;
public LinkArgument(String url) {
url(url);
}
private void assertThatUrlIsValid(String url) {
if (url == null) {
throw new NullPointerException("Link url can't be null");
}
if (url.trim().isEmpty()) {
throw new IllegalArgumentException("Link url can't be empty");
}
}
@Override
public LinkArgument url(String url) {
assertThatUrlIsValid(url);
this.url = url;
return this;
}
@Override
public LinkArgument title(Text text) {
this.text = text;
return this;
}
@Override
public LinkArgument title(String code, Object... arguments) {
this.text = new TextArgument(code, arguments);
return this;
}
@Override
public LinkArgument cssClass(String cssClass) {
this.cssClass = trimToNull(cssClass);
return this;
}
private static final String trimToNull(final String theString) {
if (theString == null) {
return null;
}
final String trimmed = theString.trim();
return trimmed.isEmpty() ? null : trimmed;
}
@Override
public String resolve(MessageResolver messageResolver) {
MessageResolver.assertThatIsNotNull(messageResolver);
return String.format(linkFormat(), arguments(messageResolver));
}
private String linkFormat() {
return this.cssClass == null ? LINK_FORMAT_WITHOUT_CSS_CLASS : LINK_FORMAT;
}
private Object[] arguments(MessageResolver messageResolver) {
final List<Object> arguments = new ArrayList<Object>();
final String title = resolveTitle(messageResolver);
arguments.add(this.url);
arguments.add(title == null ? this.url : title);
if (this.cssClass != null) {
arguments.add(this.cssClass);
}
arguments.add(title == null ? this.url : title);
return arguments.toArray(new Object[0]);
}
private String resolveTitle(MessageResolver messageResolver) {
return trimToNull(this.text == null ? null : ((Resolvable) this.text).resolve(messageResolver));
}
@Override
public String toString() {
return String.format("link{%s, %s, %s}", this.url, this.text, this.cssClass);
}
}
| mit |
Ocramius/idea-php-symfony2-plugin | tests/fr/adrienbrault/idea/symfony2plugin/tests/ServiceMapParserTest.java | 2039 | package fr.adrienbrault.idea.symfony2plugin.tests;
import fr.adrienbrault.idea.symfony2plugin.ServiceMap;
import fr.adrienbrault.idea.symfony2plugin.ServiceMapParser;
import org.junit.Test;
import org.junit.Assert;
import java.io.ByteArrayInputStream;
import java.util.Map;
/**
* @author Adrien Brault <adrien.brault@gmail.com>
*/
public class ServiceMapParserTest extends Assert {
@Test
public void testParse() throws Exception {
ServiceMapParser serviceMapParser = new ServiceMapParser();
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<container>" +
"<service id=\"adrienbrault\" class=\"AdrienBrault\\Awesome\"/>" +
"<service id=\"secret\" class=\"AdrienBrault\\Secret\" public=\"false\"/>" +
"</container>";
ServiceMap serviceMap = serviceMapParser.parse(new ByteArrayInputStream(xmlString.getBytes()));
assertTrue(serviceMap instanceof ServiceMap);
assertEquals("\\AdrienBrault\\Awesome", serviceMap.getMap().get("adrienbrault"));
assertEquals("\\AdrienBrault\\Awesome", serviceMap.getPublicMap().get("adrienbrault"));
assertEquals("\\AdrienBrault\\Secret", serviceMap.getMap().get("secret"));
assertNull(serviceMap.getPublicMap().get("secret"));
assertEquals("\\Symfony\\Component\\HttpFoundation\\Request", serviceMap.getMap().get("request"));
assertEquals("\\Symfony\\Component\\HttpFoundation\\Request", serviceMap.getPublicMap().get("request"));
assertEquals("\\Symfony\\Component\\DependencyInjection\\ContainerInterface", serviceMap.getMap().get("service_container"));
assertEquals("\\Symfony\\Component\\DependencyInjection\\ContainerInterface", serviceMap.getPublicMap().get("service_container"));
assertEquals("\\Symfony\\Component\\HttpKernel\\KernelInterface", serviceMap.getMap().get("kernel"));
assertEquals("\\Symfony\\Component\\HttpKernel\\KernelInterface", serviceMap.getPublicMap().get("kernel"));
}
}
| mit |
fof1092/WeatherVote | src/me/F_o_F_1092/WeatherVote/PluginManager/Spigot/HelpPageListener.java | 2808 | package me.F_o_F_1092.WeatherVote.PluginManager.Spigot;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.F_o_F_1092.WeatherVote.Options;
import me.F_o_F_1092.WeatherVote.PluginManager.Command;
import me.F_o_F_1092.WeatherVote.PluginManager.CommandListener;
import me.F_o_F_1092.WeatherVote.PluginManager.HelpMessage;
public class HelpPageListener extends me.F_o_F_1092.WeatherVote.PluginManager.HelpPageListener {
public static void sendMessage(Player p, int page) {
List<HelpMessage> personalHelpMessages = getAllPersonalHelpMessages(p);
List<HelpMessage> personalHelpPageMessages = getHelpPageMessages(p, personalHelpMessages, page);
p.sendMessage("");
JSONMessageListener.send(p, getNavBar(personalHelpMessages, personalHelpPageMessages, page));
p.sendMessage("");
for (HelpMessage hm : personalHelpPageMessages) {
JSONMessageListener.send(p, hm.getJsonString());
}
p.sendMessage("");
if (getMaxPlayerPages(personalHelpMessages) != 1) {
p.sendMessage(Options.msg.get("helpTextGui.4").replace("[PAGE]", (page + 1) + ""));
}
JSONMessageListener.send(p, getNavBar(personalHelpMessages, personalHelpPageMessages, page));
p.sendMessage("");
}
public static void sendNormalMessage(CommandSender cs) {
cs.sendMessage(Options.msg.get("color.1") + "§m----------------§r " + pluginNametag + Options.msg.get("color.1") + "§m----------------");
cs.sendMessage("");
for (Command command : CommandListener.getAllCommands()) {
cs.sendMessage(command.getHelpMessage().getNormalString());
}
cs.sendMessage("");
cs.sendMessage(Options.msg.get("color.1") + "§m----------------§r " + pluginNametag + Options.msg.get("color.1") + "§m----------------");
}
private static List<HelpMessage> getHelpPageMessages(Player p, List<HelpMessage> personalHelpMessages, int page) {
List<HelpMessage> personalHelpPageMessages = new ArrayList<HelpMessage>();
for (int i = 0; i < maxHelpMessages; i++) {
if (personalHelpMessages.size() >= (page * maxHelpMessages + i + 1)) {
personalHelpPageMessages.add(personalHelpMessages.get(page * maxHelpMessages + i));
}
}
return personalHelpPageMessages;
}
public static int getMaxPlayerPages(Player p) {
return (int) java.lang.Math.ceil(((double)getAllPersonalHelpMessages(p).size() / (double)maxHelpMessages));
}
private static List<HelpMessage> getAllPersonalHelpMessages(Player p) {
List<HelpMessage> personalHelpMessages = new ArrayList<HelpMessage>();
for (Command command : CommandListener.getAllCommands()) {
if (command.getPermission()== null || p.hasPermission(command.getPermission())) {
personalHelpMessages.add(command.getHelpMessage());
}
}
return personalHelpMessages;
}
} | mit |
A-D-I-T-Y-A/Zeon-Client | src/minecraft/zeonClient/mods/KillAura.java | 2021 | package zeonClient.mods;
import java.util.Iterator;
import org.lwjgl.input.Keyboard;
import net.minecraft.client.entity.EntityOtherPlayerMP;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.network.play.client.CPacketPlayerDigging.Action;
import net.minecraft.network.play.client.CPacketUseEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import zeonClient.main.Category;
public class KillAura extends Mod {
private int ticks = 0;
public KillAura() {
super("KillAura", "KillAura", Keyboard.KEY_R, Category.COMBAT);
}
public void onUpdate() {
if(this.isToggled()) {
ticks++;
if(ticks >= 20 - speed()) {
ticks = 0;
mc.player.rotationYaw +=0.2F;
for(Iterator<Entity> entities = mc.world.loadedEntityList.iterator(); entities.hasNext();) {
Object object = entities.next();
if(object instanceof EntityLivingBase) {
EntityLivingBase e = (EntityLivingBase) object;
if(e instanceof EntityPlayerSP) continue;
if(mc.player.getDistanceToEntity(e) <= 7F) {
if(e.isInvisible()) {
break;
}
if(e.isEntityAlive()) {
if(mc.player.getHeldItemMainhand() != null) {
mc.player.attackTargetEntityWithCurrentItem(e);
}
if(mc.player.isActiveItemStackBlocking()) {
mc.player.connection.sendPacket(new CPacketPlayerDigging(Action.RELEASE_USE_ITEM, new BlockPos(0, 0, 0), EnumFacing.UP));
}
mc.player.connection.sendPacket(new CPacketUseEntity(e));
mc.player.swingArm(EnumHand.MAIN_HAND);
break;
}
}
}
}
}
}
}
private int speed() {
return 18;
}
}
| mit |
CannibalVox/Schematica | src/main/java/com/github/lunatrius/schematica/client/gui/GuiSchematicMaterialsSlot.java | 2204 | package com.github.lunatrius.schematica.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiSlot;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
class GuiSchematicMaterialsSlot extends GuiSlot {
private final Minecraft minecraft = Minecraft.getMinecraft();
private final GuiSchematicMaterials guiSchematicMaterials;
protected int selectedIndex = -1;
private final String strUnknownBlock = I18n.format("schematica.gui.unknownblock");
public GuiSchematicMaterialsSlot(GuiSchematicMaterials par1) {
super(Minecraft.getMinecraft(), par1.width, par1.height, 16, par1.height - 34, 24);
this.guiSchematicMaterials = par1;
this.selectedIndex = -1;
}
@Override
protected int getSize() {
return this.guiSchematicMaterials.blockList.size();
}
@Override
protected void elementClicked(int index, boolean par2, int par3, int par4) {
this.selectedIndex = index;
}
@Override
protected boolean isSelected(int index) {
return index == this.selectedIndex;
}
@Override
protected void drawBackground() {
}
@Override
protected void drawContainerBackground(Tessellator tessellator) {
}
@Override
protected void drawSlot(int index, int x, int y, int par4, Tessellator tessellator, int par6, int par7) {
ItemStack itemStack = this.guiSchematicMaterials.blockList.get(index);
String itemName;
String amount = Integer.toString(itemStack.stackSize);
if (itemStack.getItem() != null) {
itemName = itemStack.getItem().getItemStackDisplayName(itemStack);
} else {
itemName = this.strUnknownBlock;
}
GuiHelper.drawItemStack(this.minecraft.renderEngine, this.minecraft.fontRenderer, x, y, itemStack);
this.guiSchematicMaterials.drawString(this.minecraft.fontRenderer, itemName, x + 24, y + 6, 0xFFFFFF);
this.guiSchematicMaterials.drawString(this.minecraft.fontRenderer, amount, x + 215 - this.minecraft.fontRenderer.getStringWidth(amount), y + 6, 0xFFFFFF);
}
}
| mit |
cryxli/SpiritHealer | src/main/java/li/cryx/minecraft/death/ISpiritHealer.java | 609 | package li.cryx.minecraft.death;
import java.util.logging.Logger;
import li.cryx.minecraft.death.i18n.ITranslator;
import li.cryx.minecraft.death.persist.AbstractPersistManager;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
public interface ISpiritHealer {
void addAltarLocation(Location loc);
Material getAltarBaseMaterial();
Material getAltarMaterial();
// FileConfiguration getConfig();
Logger getLogger();
AbstractPersistManager getPersist();
ITranslator getTranslator();
boolean isAltar(Location loc);
void restoreItems(Player player);
}
| mit |
pixlepix/Aura-Cascade | src/main/java/pixlepix/auracascade/data/Quest.java | 1082 | package pixlepix.auracascade.data;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
/**
* Created by localmacaccount on 5/31/15.
*/
public class Quest {
//TODO QUEST
public static int nextId;
public final ItemStack target;
public final ItemStack result;
public final int id;
public String string;
public Quest(String string, ItemStack target, ItemStack result) {
this.target = target;
this.result = result;
this.string = string;
this.id = nextId;
nextId++;
}
public boolean hasCompleted(EntityPlayer player) {
// QuestData questData = (QuestData) player.getExtendedProperties(QuestData.EXT_PROP_NAME);
// return questData.completedQuests.contains(this);
return false;
}
public void complete(EntityPlayer player) {
//QuestData questData = (QuestData) player.getExtendedProperties(QuestData.EXT_PROP_NAME);
// questData.completedQuests.add(this);
// AuraCascade.analytics.eventDesign("questComplete", id);
}
}
| mit |
zgqq/mah | mah-core/src/main/java/mah/ui/util/UiUtils.java | 1999 | /**
* MIT License
*
* Copyright (c) 2017 zgqq
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mah.ui.util;
import mah.ui.key.KeystateManager;
import mah.ui.layout.Layout;
import mah.ui.pane.input.InputPane;
import mah.ui.pane.input.InputPaneProvider;
import mah.ui.window.WindowManager;
import org.jetbrains.annotations.Nullable;
/**
* Created by zgq on 2017-01-12 11:17
*/
public final class UiUtils {
private UiUtils(){}
public static void hideWindow() {
KeystateManager.getInstance().reset();
WindowManager.getInstance().getCurrentWindow().hide();
}
@Nullable
public static InputPane getInputPane() {
Layout currentLayout = WindowManager.getInstance().getCurrentWindow().getCurrentLayout();
if (currentLayout instanceof InputPaneProvider) {
InputPaneProvider layout = (InputPaneProvider) currentLayout;
return layout.getInputPane();
}
return null;
}
}
| mit |
Belpois/pixelpainter | src/main/java/com/missingeye/pixelpainter/events/network/texture/ServerUpdatedTexturePacketEvent.java | 470 | package com.missingeye.pixelpainter.events.network.texture;
import com.missingeye.pixelpainter.common.PixelMetadata;
import net.minecraft.util.ResourceLocation;
/**
* Created on 1/17/2015.
*
* @auhtor Samuel Agius (Belpois)
*/
public class ServerUpdatedTexturePacketEvent extends UpdatedTexturePacketEvent
{
public ServerUpdatedTexturePacketEvent(ResourceLocation resourceLocation, PixelMetadata[] pixelMetadata)
{
super(resourceLocation, pixelMetadata);
}
}
| mit |
ayshen/caek | src/com/example/aperture/core/contacts/EmailFilter.java | 5607 | package com.example.aperture.core.contacts;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import java.util.List;
import java.util.ArrayList;
import com.example.aperture.core.Module;
public class EmailFilter extends Filter {
private final static String[] DATA_PROJECTION = new String[] {
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Data.DATA1
};
private final static String MIMETYPE_SELECTION =
ContactsContract.Data.MIMETYPE + "=?";
private final static String[] EMAIL_MIMETYPE = new String[] {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
};
private final static String[] PREFIXES = new String[] {
"send an email to ",
"send email to ",
"email "
};
private final static class EmailComparer implements java.util.Comparator<Intent> {
private String mFragment;
public EmailComparer(String fragment) {
mFragment = fragment;
}
@Override
public boolean equals(Object o) { return false; }
@Override
public int compare(Intent a, Intent b) {
// Get the emails from the intents.
String x = a.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
String y = b.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
// Split the emails into usernames and domains.
String xu = x.substring(0, x.indexOf('@'));
String yu = y.substring(0, y.indexOf('@'));
String xd = x.substring(x.indexOf('@')+1);
String yd = y.substring(y.indexOf('@')+1);
// Get the locations of the query in the usernames and domains.
int ixu = xu.indexOf(mFragment), iyu = yu.indexOf(mFragment);
int ixd = xd.indexOf(mFragment), iyd = yd.indexOf(mFragment);
// TODO refactor this to be less iffy
// Explicitly writing out the comparision logic to avoid violating
// general sorting contract for total ordering.
if(ixu != -1 && iyu != -1) {
if(ixu < iyu) return -1;
else if(iyu < ixu) return 1;
else return xu.compareTo(yu);
}
else if(ixu != -1 && iyu == -1) {
return -1;
}
else if(ixu == -1 && iyu != -1) {
return 1;
}
else {
if(ixd != -1 && iyd != -1) {
if(ixd < iyd) return -1;
else if(iyd < ixd) return 1;
else return xd.compareTo(yd);
}
else if(ixd != -1 && iyd == -1) {
return -1;
}
else if(ixd == -1 && iyd != -1) {
return 1;
}
else
return x.compareTo(y);
}
}
}
private void sort(List<Intent> results, String query) {
Intent[] buffer = new Intent[results.size()];
java.util.Arrays.sort(results.toArray(buffer), 0, buffer.length,
new EmailComparer(query));
results.clear();
for(int i = 0; i < buffer.length; ++i)
results.add(buffer[i]);
}
@Override
public List<Intent> filter(Context context, String query) {
List<Intent> results = new ArrayList<Intent>();
boolean hasPrefix = false;
for(String prefix: PREFIXES) {
if(query.startsWith(prefix)) {
query = query.substring(prefix.length());
hasPrefix = true;
break;
}
}
Cursor data = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
DATA_PROJECTION,
MIMETYPE_SELECTION,
EMAIL_MIMETYPE,
null);
if(hasPrefix)
results.addAll(filterByName(data, query));
results.addAll(filterByAddress(data, query));
data.close();
return results;
}
private List<Intent> filterByName(Cursor data, String query) {
List<Intent> results = new ArrayList<Intent>();
query = query.toLowerCase();
for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
String name = data.getString(1).toLowerCase();
if(name.contains(query))
results.add(intentFor(data.getString(1), data.getString(2)));
}
return results;
}
private List<Intent> filterByAddress(Cursor data, String query) {
List<Intent> results = new ArrayList<Intent>();
for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
String email = data.getString(2);
if(email.contains(query))
results.add(intentFor(data.getString(1), email));
}
sort(results, query);
return results;
}
private Intent intentFor(String displayName, String email) {
Intent result = new Intent(Intent.ACTION_SENDTO,
new Uri.Builder().scheme("mailto").opaquePart(email).build());
result.putExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, email);
result.putExtra(Module.RESPONSE_TEXT,
String.format("%1$s <%2$s>", displayName, email));
return result;
}
}
| mit |
deanpanayotov/simple_weather | SimpleWeather/app/src/main/java/com/dpanayotov/simpleweather/api/base/BaseForecastResponse.java | 87 | package com.dpanayotov.simpleweather.api.base;
public class BaseForecastResponse {
}
| mit |
jermeyjungbeker/VP11B2 | src/main/java/edu/avans/hartigehap/web/util/UrlUtil.java | 833 | package edu.avans.hartigehap.web.util;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UrlUtil {
private UrlUtil() {
}
public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
String enc = httpServletRequest.getCharacterEncoding();
if (enc == null) {
enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
}
try {
pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
} catch (UnsupportedEncodingException uee) {
log.error("UnsupportedEncodingException", uee);
}
return pathSegment;
}
}
| mit |
ejw0013/vegemite-smoothie | com/veggie/src/java/controllers/transaction/ReturnController.java | 1973 | package com.veggie.src.java.controllers.transaction;
import java.util.List;
import com.veggie.src.java.controllers.Controller;
import com.veggie.src.java.form.Form;
import com.veggie.src.java.form.AbstractFormBuilder;
import com.veggie.src.java.form.AbstractFormBuilderFactory;
import com.veggie.src.java.notification.Notification;
import com.veggie.src.java.notification.AbstractNotificationFactory;
import com.veggie.src.java.database.AbstractDatabaseManagerFactory;
import com.veggie.src.java.database.TransactionDatabaseManager;
import com.veggie.src.java.database.ItemDatabaseManager;
public class ReturnController implements Controller
{
private AbstractFormBuilder formBuilder;
private int itemid;
public ReturnController(){}
public Form activate()
{
formBuilder = AbstractFormBuilderFactory.getInstance().createFormBuilder();
formBuilder.addField("Item ID");
return formBuilder.getResult();
}
public Notification submitForm(Form form)
{
Notification notification;
List<String> formData = form.getData();
try{
itemid = Integer.parseInt(formData.get(0));
TransactionDatabaseManager transactionDBManager = AbstractDatabaseManagerFactory.getInstance().createTransactionDatabaseManager();
ItemDatabaseManager itemDBManager = AbstractDatabaseManagerFactory.getInstance().createItemDatabaseManager();
if(itemDBManager.getItem(itemid) == null){
return AbstractNotificationFactory.getInstance().createErrorNotification("Error item does not exist!");
}
transactionDBManager.finalizeTransaction(itemid);
notification = AbstractNotificationFactory.getInstance().createSuccessNotification("Item sucessfully returned!");
}catch(Exception e){
notification = AbstractNotificationFactory.getInstance().createErrorNotification("Error form data failure");
}
return notification; //???????
}
public void respondToNotification(Notification notif) {
//TO DO
}
}
| mit |
ytimesru/kkm-pc-client | src/main/java/org/bitbucket/ytimes/client/main/Main.java | 372 | package org.bitbucket.ytimes.client.main;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by andrey on 27.05.17.
*/
public class Main {
public static void main( String[] args ) throws Exception {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("root-context.xml");
}
}
| mit |
ericjin527/MockInterview | src/main/java/alexp/blog/service/ScheduleServiceImpl.java | 569 | package alexp.blog.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import alexp.blog.repository.*;
import alexp.blog.model.Schedule;
@Service("ScheduleService")
public class ScheduleServiceImpl implements ScheduleService{
@Autowired
private ScheduleRepository schedulerepository;
@Override
public Schedule getSchedule(String username) {
// TODO Auto-generated method stub
System.out.println("I am in service");
return schedulerepository.findByUsernameIgnoreCase(username);
}
}
| mit |
palatable/lambda | src/test/java/com/jnape/palatable/lambda/optics/prisms/MapPrismTest.java | 1147 | package com.jnape.palatable.lambda.optics.prisms;
import org.junit.Test;
import java.util.HashMap;
import java.util.LinkedHashMap;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonMap;
import static testsupport.assertion.PrismAssert.assertPrismLawfulness;
public class MapPrismTest {
@Test
public void valueAtWithConstructor() {
assertPrismLawfulness(MapPrism.valueAt(LinkedHashMap::new, "foo"),
asList(new LinkedHashMap<>(),
new LinkedHashMap<>(singletonMap("foo", 1)),
new LinkedHashMap<>(singletonMap("bar", 2))),
singleton(1));
}
@Test
public void valueAtWithoutConstructor() {
assertPrismLawfulness(MapPrism.valueAt("foo"),
asList(new HashMap<>(),
new HashMap<>(singletonMap("foo", 1)),
new HashMap<>(singletonMap("bar", 2))),
singleton(1));
}
} | mit |
agileapes/jpowerpack | string-tools/src/main/java/com/agileapes/powerpack/string/exception/NoMoreTextException.java | 1068 | /*
* Copyright (c) 2012 M. M. Naseri <m.m.naseri@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*/
package com.agileapes.powerpack.string.exception;
/**
* @author Mohammad Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (2012/12/3, 17:47)
*/
public class NoMoreTextException extends DocumentReaderException {
private static final long serialVersionUID = -1822455471711418794L;
public NoMoreTextException() {
}
public NoMoreTextException(String message) {
super(message);
}
}
| mit |
gochaorg/lang2 | src/test/java/xyz/cofe/lang2/parser/vref/L2EngineVarRef2.java | 4141 | /*
* The MIT License
*
* Copyright 2014 Kamnev Georgiy (nt.gocha@gmail.com).
*
* Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного
* обеспечения и сопутствующей документации (в дальнейшем именуемыми "Программное Обеспечение"),
* использовать Программное Обеспечение без ограничений, включая неограниченное право на
* использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование
* и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется
* данное Программное Обеспечение, при соблюдении следующих условий:
*
* Вышеупомянутый копирайт и данные условия должны быть включены во все копии
* или значимые части данного Программного Обеспечения.
*
* ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ,
* ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ,
* СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ
* ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ
* ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ
* ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ
* ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ.
*/
package xyz.cofe.lang2.parser.vref;
import java.net.URL;
import xyz.cofe.lang2.parser.BasicParserTest;
import xyz.cofe.lang2.parser.L2Engine;
import xyz.cofe.lang2.vm.Callable;
import xyz.cofe.lang2.vm.Value;
import org.junit.Test;
import xyz.cofe.log.CLILoggers;
/**
* Тестирование парсера
* @author gocha
*/
public class L2EngineVarRef2 extends BasicParserTest
{
protected L2Engine l2Engine = null;
@Override
protected Value parseExpressions(String source) {
if( l2Engine==null ){
l2Engine = new L2Engine();
l2Engine.setMemory(memory);
}
return l2Engine.parse(source);
}
@Test
public void varRef2(){
return;
// TODO используется альтернативный способ поиска переменных
//
// String src = "var v = \"abc\";\n"
// + "var obj = \n"
// + " {\n"
// + " f : function ( a )\n"
// + " {\n"
// + " a + v\n"
// + " }\n"
// + " };\n"
// + "v = \"def\";\n"
// + "obj.f( \"xcv\" )";
// String must = "xcvabc";
//
// CLILoggers logger = new CLILoggers();
// URL logConf = L2EngineVarRefTest.class.getResource("L2EngineVarRefTest2.logconf.xml");
// logger.parseXmlConfig(logConf);
//
// assertParseExpressions(src, must);
//
// if( logger.getNamedHandler().containsKey("console") ){
// logger.removeHandlerFromRoot(logger.getNamedHandler().get("console"));
// }
}
}
| mit |
MrGaoRen/secretProject | cw/src/db/test.java | 232 | package db;
import db.*;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Database.getInstance().register("111", "22");
// Database.getInstance().login("111", "22");
}
}
| mit |
mseclab/AHE17 | Token-Generator/src/main/java/DotNet.java | 3987 | import java.security.Security;
import java.util.Base64;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class DotNet {
static byte[] buffer = new byte[] {
(byte)17,
(byte)185,
(byte)186,
(byte)161,
(byte)188,
(byte)43,
(byte)253,
(byte)224,
(byte)76,
(byte)24,
(byte)133,
(byte)9,
(byte)201,
(byte)173,
(byte)255,
(byte)152,
(byte)113,
(byte)171,
(byte)225,
(byte)163,
(byte)121,
(byte)177,
(byte)211,
(byte)18,
(byte)50,
(byte)50,
(byte)219,
(byte)190,
(byte)168,
(byte)138,
(byte)97,
(byte)197
};
static byte[] initVector = new byte[] {
(byte) 8,
(byte) 173,
(byte) 47,
(byte) 130,
(byte) 199,
(byte) 242,
(byte) 20,
(byte) 211,
(byte) 63,
(byte) 47,
(byte) 254,
(byte) 173,
(byte) 163,
(byte) 245,
(byte) 242,
(byte) 232,
(byte) 11,
(byte) 244,
(byte) 134,
(byte) 249,
(byte) 44,
(byte) 123,
(byte) 138,
(byte) 109,
(byte) 155,
(byte) 173,
(byte) 122,
(byte) 76,
(byte) 93,
(byte) 125,
(byte) 185,
(byte) 66
};
public static String decrypt(byte[] key, byte[] initVector, byte[] encrypted) {
try {
BlockCipher engine = new RijndaelEngine(256);
CBCBlockCipher cbc = new CBCBlockCipher(engine);
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc, new PKCS7Padding());
cipher.init(false, new ParametersWithIV(new KeyParameter(key), initVector));
int minSize = cipher.getOutputSize(encrypted.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(encrypted, 0, encrypted.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return new String(result);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String sha64 = "SxTgWtrMjXY/dA50Kk20PkNeNLQ=";
byte[] k = Base64.getDecoder().decode(sha64);
System.out.println("Buffer :: "+Base64.getEncoder().encodeToString(buffer)+" --> length "+buffer.length);
System.out.println("Key(Sha) :: "+Base64.getEncoder().encodeToString(k)+" --> length "+k.length);
System.out.println("IV :: "+Base64.getEncoder().encodeToString(initVector)+" --> length "+initVector.length);
System.out.println(decrypt(k, initVector, buffer));
}
}
| mit |
jgrillo/wordcount-service | src/test/java/com/jgrillo/wordcount/api/CountsTest.java | 3572 | package com.jgrillo.wordcount.api;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import static org.quicktheories.QuickTheory.qt;
import static org.quicktheories.generators.SourceDSL.*;
import static io.dropwizard.testing.FixtureHelpers.*;
import static org.assertj.core.api.Assertions.assertThat;
public final class CountsTest {
private static final ObjectMapper mapper = new ObjectMapper()
.disable(SerializationFeature.CLOSE_CLOSEABLE)
.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
private static final ObjectWriter writer = mapper.writerFor(Counts.class);
private static final ObjectReader reader = mapper.readerFor(Counts.class);
private static final JsonFactory factory = mapper.getFactory();
/**
* Test the encode-decode invariant for the Counts model.
*/
@Test
public void testCountsEncodeDecode() throws Exception {
qt().forAll(
lists().of(strings().allPossible().ofLengthBetween(0, 100)).ofSize(1000).describedAs(
Object::toString
),
lists().of(longs().all()).ofSize(1000).describedAs(Object::toString)
).as((words, counts) -> {
final ImmutableMap.Builder<String, Long> mapBuilder = ImmutableMap.builder();
final List<String> distinctWords = words.stream().distinct().collect(Collectors.toList());
for (int i = 0; i < distinctWords.size(); i++) {
mapBuilder.put(distinctWords.get(i), counts.get(i)); // counts.size() >= distinctWords.size()
}
return mapBuilder.build();
}).checkAssert((wordCounts) -> {
try {
final byte[] bytes = writer.writeValueAsBytes(new Counts(wordCounts));
final JsonParser parser = factory.createParser(bytes);
final Counts countsModel = reader.readValue(parser);
assertThat(countsModel.getCounts()).isEqualTo(wordCounts);
} catch (IOException e) {
throw new RuntimeException("Caught IOE while checking counts", e);
}
});
}
@Test
public void testCountsSerializesToJSON() throws Exception {
final Counts counts = new Counts(
ImmutableMap.<String, Long>builder()
.put("word", 3L)
.put("wat", 1L)
.build()
);
final String expected = writer.writeValueAsString(reader.readValue(fixture("fixtures/counts.json")));
assertThat(writer.writeValueAsString(counts)).isEqualTo(expected);
}
@Test
public void testCountsDeserializesFromJSON() throws Exception {
final Counts counts = new Counts(
ImmutableMap.<String, Long>builder()
.put("word", 3L)
.put("wat", 1L)
.build()
);
final Counts deserializedCounts = reader.readValue(fixture("fixtures/counts.json"));
assertThat(deserializedCounts.getCounts()).isEqualTo(counts.getCounts());
}
} | mit |
borisbrodski/jmockit | main/test/mockit/integration/junit4/DependencyTests.java | 366 | /*
* Copyright (c) 2006-2012 Rogério Liesenfeld
* This file is subject to the terms of the MIT license (see LICENSE.txt).
*/
package mockit.integration.junit4;
import org.junit.runner.*;
import org.junit.runners.*;
@RunWith(Suite.class)
@Suite.SuiteClasses({MockDependencyTest.class, UseDependencyTest.class})
public final class DependencyTests {}
| mit |
e-baloo/it-keeps | it-keeps-core/src/main/java/org/ebaloo/itkeeps/core/domain/vertex/vAclGroup.java | 6089 |
package org.ebaloo.itkeeps.core.domain.vertex;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.ebaloo.itkeeps.api.enumeration.enAclAdmin;
import org.ebaloo.itkeeps.api.enumeration.enAclData;
import org.ebaloo.itkeeps.api.model.jAclGroup;
import org.ebaloo.itkeeps.api.model.jBaseLight;
import org.ebaloo.itkeeps.core.database.annotation.DatabaseVertrex;
import org.ebaloo.itkeeps.core.domain.edge.DirectionType;
import org.ebaloo.itkeeps.core.domain.edge.notraverse.eAclNoTraverse;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph;
/**
*
*
*/
@DatabaseVertrex()
final class vAclGroup extends vBase {
vAclGroup() {
super();
}
/*
* CHILD
*/
vAclGroup(final jAclGroup j) {
super(j);
try {
this.update(j);
} catch (Exception e) {
this.delete();
throw e;
}
}
final jBaseLight getChild() {
vAclGroup child = this.getEdge(vAclGroup.class, DirectionType.CHILD, false, eAclNoTraverse.class);
return child == null ? null : getJBaseLight(child);
}
/*
* PARENTS
*/
final void setChild(final jBaseLight group) {
vAclGroup child = get(this.getGraph(), vAclGroup.class, group, false);
setEdges(this.getGraph(), vAclGroup.class, this, vAclGroup.class, child, DirectionType.CHILD, eAclNoTraverse.class, false);
}
final List<jBaseLight> getParents() {
return this.getEdges(
vAclGroup.class,
DirectionType.PARENT,
false,
eAclNoTraverse.class).stream().map(vBase::getJBaseLight).collect(Collectors.toList());
}
/*
* ACL ADMIN
*/
final void setParents(List<jBaseLight> list) {
if (list == null)
list = new ArrayList<>();
// Optimization
OrientBaseGraph graph = this.getGraph();
setEdges(
graph,
vAclGroup.class,
this,
vAclGroup.class,
list.stream().map(e -> get(graph, vAclGroup.class, e, false)).collect(Collectors.toList()),
DirectionType.PARENT,
eAclNoTraverse.class,
false);
}
final List<enAclAdmin> getAclAdmin() {
return this.getEdges(
vAclAdmin.class,
DirectionType.PARENT,
true,
eAclNoTraverse.class)
.stream().map(e -> enAclAdmin.valueOf(e.getName())).collect(Collectors.toList());
}
/*
* ACL DATA
*/
final void setAclAdmin(List<enAclAdmin> list) {
if(list == null)
list = new ArrayList<>();
// Optimization
OrientBaseGraph graph = this.getGraph();
setEdges(
graph,
vAclGroup.class,
this,
vAclAdmin.class,
list.stream().map(e -> vAclAdmin.get(graph, vAclAdmin.class, e.name())).collect(Collectors.toList()),
DirectionType.PARENT,
eAclNoTraverse.class,
false);
}
final List<enAclData> getAclData() {
return this.getEdges(
vAclData.class,
DirectionType.PARENT,
true,
eAclNoTraverse.class)
.stream().map(e -> enAclData.valueOf(e.getName())).collect(Collectors.toList());
}
// API
final void setAclData(List<enAclData> list) {
if(list == null)
list = new ArrayList<>();
// Optimization
OrientBaseGraph graph = this.getGraph();
setEdges(
graph,
vAclGroup.class,
this,
vAclData.class,
list.stream().map(e -> vAclData.get(graph, vAclData.class, e.name())).collect(Collectors.toList()),
DirectionType.PARENT,
eAclNoTraverse.class,
false);
}
final jAclGroup read() {
jAclGroup j = new jAclGroup();
this.readBase(j);
j.setAclAdmin(this.getAclAdmin());
j.setAclData(this.getAclData());
j.setChild(this.getChild());
j.setParents(this.getParents());
return j;
}
/*
public static final jAclGroup create(Rid requesteurRid, jAclGroup j) {
SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL);
if(!sAcl.isRoleRoot())
throw ExceptionPermission.NOT_ROOT;
vAclGroup aclGroup = new vAclGroup(j);
return vAclGroup.read(requesteurRid, aclGroup.getId());
}
*/
/*
public static final jAclGroup delete(Rid requesteurRid, Rid guid) {
SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL);
if(!sAcl.isRoleRoot())
throw ExceptionPermission.NOT_ROOT;
vAclGroup aclGroup = vAclGroup.get(null, vAclGroup.class, guid, false);
jAclGroup j = aclGroup.read();
aclGroup.delete();
return j;
}
*/
/*
public static final jAclGroup read(Rid requesteurRid, Rid guid) {
SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL);
if(!sAcl.isRoleRoot())
throw ExceptionPermission.NOT_ROOT;
vAclGroup aclGroup = vAclGroup.get(null, vAclGroup.class, guid, false);
return aclGroup.read();
}
*/
/*
public static final jAclGroup update(Rid requesteurRid, jAclGroup j) {
SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL);
if(!sAcl.isRoleRoot())
throw ExceptionPermission.NOT_ROOT;
vAclGroup aclGroup = vAclGroup.get(null, vAclGroup.class, j.getId(), false);
aclGroup.checkVersion(j);
aclGroup.update(j);
return vAclGroup.read(requesteurRid, j.getId());
}
*/
final void update(jAclGroup j) {
this.setAclAdmin(j.getAclAdmin());
this.setAclData(j.getAclData());
this.setParents(j.getParents());
this.setChild(j.getChild());
}
/*
public static final List<jAclGroup> readAll(Rid requesteurRid) {
SecurityAcl sAcl = SecurityFactory.getSecurityAcl(requesteurRid, Rid.NULL);
if(!sAcl.isRoleRoot())
throw ExceptionPermission.NOT_ROOT;
List<jAclGroup> list = vAclGroup.getAllBase(null, vAclGroup.class, false).stream().map(e -> e.read()).collect(Collectors.toList());
return list;
}
*/
}
| mit |
jenkinsci/chatwork-plugin | src/main/java/com/vexus2/jenkins/chatwork/jenkinschatworkplugin/api/Room.java | 992 | package com.vexus2.jenkins.chatwork.jenkinschatworkplugin.api;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown=true)
public class Room {
@JsonProperty("room_id")
public String roomId;
@JsonProperty("name")
public String name;
@JsonProperty("type")
public String type;
@Override
public int hashCode(){
return new HashCodeBuilder()
.append(name)
.append(roomId)
.append(type)
.toHashCode();
}
@Override
public boolean equals(final Object obj){
if(obj instanceof Room){
final Room other = (Room) obj;
return new EqualsBuilder()
.append(name, other.name)
.append(roomId, other.roomId)
.append(type, other.type)
.isEquals();
} else{
return false;
}
}
}
| mit |
defunct/cafe | src/test/java/com/goodworkalan/mix/builder/BasicJavaProjectTest.java | 196 | package com.goodworkalan.mix.builder;
import org.testng.annotations.Test;
// TODO Document.
public class BasicJavaProjectTest {
// TODO Document.
@Test
public void build() {
}
}
| mit |
ihiroky/reservoir | src/main/java/net/ihiroky/reservoir/coder/ByteBufferOutputStream.java | 1244 | package net.ihiroky.reservoir.coder;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
/**
* Created on 12/10/04, 19:26
*
* @author Hiroki Itoh
*/
public class ByteBufferOutputStream extends OutputStream {
ByteBuffer byteBuffer;
ByteBufferOutputStream(int initialCapacity) {
byteBuffer = ByteBuffer.allocate(initialCapacity);
}
private void ensureCapacity(int minimumIncrement) {
int c = byteBuffer.capacity();
int newSize = c / 2 * 3;
if (newSize < c + minimumIncrement) {
newSize = c + minimumIncrement;
}
ByteBuffer t = ByteBuffer.allocate(newSize);
byteBuffer.flip();
t.put(byteBuffer);
byteBuffer = t;
}
@Override
public void write(int b) throws IOException {
if (!byteBuffer.hasRemaining()) {
ensureCapacity(1);
}
byteBuffer.put((byte) b);
}
@Override
public void write(byte[] bytes, int offset, int length) {
if (byteBuffer.remaining() < length) {
ensureCapacity(length);
}
byteBuffer.put(bytes, offset, length);
}
@Override
public void close() {
byteBuffer.flip();
}
}
| mit |
cowthan/Ayo2022 | Ayo/app/src/main/java/org/ayo/ui/sample/material/ScaleTitlebarBehavior.java | 2886 | package org.ayo.ui.sample.material;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import org.ayo.animate.yoyo.Techniques;
import org.ayo.animate.yoyo.YoYo;
import org.ayo.view.widget.TitleBar;
/**
* FloatingActionBar会跟着ScrollView缩小
*/
public class ScaleTitlebarBehavior extends CoordinatorLayout.Behavior<TitleBar> {
public ScaleTitlebarBehavior(Context context, AttributeSet attrs) {
super();
}
@Override
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, TitleBar child,
View directTargetChild, View target, int nestedScrollAxes) {
return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target,
nestedScrollAxes);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, final TitleBar child,
View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
//child.setVisibility(View.GONE);
YoYo.with(Techniques.ZoomOut).duration(300).listen(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
child.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).playOn(child);
} else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
YoYo.with(Techniques.ZoomIn).duration(300).listen(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
child.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).playOn(child);
}
}
}
| mit |
intuit/karate | karate-core/src/main/java/com/intuit/karate/job/JobUtils.java | 5009 | /*
* The MIT License
*
* Copyright 2019 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.job;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
*
* @author pthomas3
*/
public class JobUtils {
public static void zip(File src, File dest) {
try {
src = src.getCanonicalFile();
FileOutputStream fos = new FileOutputStream(dest);
ZipOutputStream zipOut = new ZipOutputStream(fos);
zip(src, "", zipOut, 0);
zipOut.close();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void zip(File fileToZip, String fileName, ZipOutputStream zipOut, int level) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
String entryName = fileName;
zipOut.putNextEntry(new ZipEntry(entryName + "/"));
zipOut.closeEntry();
File[] children = fileToZip.listFiles();
for (File childFile : children) {
String childFileName = childFile.getName();
// TODO improve ?
if (childFileName.equals("target") || childFileName.equals("build")) {
continue;
}
if (level != 0) {
childFileName = entryName + "/" + childFileName;
}
zip(childFile, childFileName, zipOut, level + 1);
}
return;
}
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(fileToZip);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
public static void unzip(File src, File dest) {
try {
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(src));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = createFile(dest, zipEntry);
if (zipEntry.isDirectory()) {
newFile.mkdirs();
} else {
File parentFile = newFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static File createFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath)) {
throw new IOException("entry outside target dir: " + zipEntry.getName());
}
return destFile;
}
public static File getFirstFileMatching(File parent, Predicate<String> predicate) {
File[] files = parent.listFiles((f, n) -> predicate.test(n));
return files == null || files.length == 0 ? null : files[0];
}
}
| mit |
bennyguo/AssemblyNews | app/src/main/java/com/java/group34/NewsPictures.java | 500 | package com.java.group34;
import java.util.ArrayList;
/**
* Created by dell-pc on 2017/9/11.
*/
public class NewsPictures {
private Value[] value;
private static class Value
{
String contentUrl;
}
public ArrayList<String> getFirstNthPictures(int n)
{
ArrayList<String> ans=new ArrayList<String>();
System.out.println(value.length);
for(int i=0;i<n&&i<value.length;++i)
ans.add(value[i].contentUrl);
return ans;
}
}
| mit |
OurCraft/OurCraft | src/main/java/org/craft/client/render/blocks/BlockModelRenderer.java | 8599 | package org.craft.client.render.blocks;
import java.util.*;
import java.util.Map.Entry;
import com.google.common.collect.*;
import org.craft.blocks.*;
import org.craft.blocks.states.*;
import org.craft.client.*;
import org.craft.client.models.*;
import org.craft.client.render.*;
import org.craft.client.render.texture.TextureIcon;
import org.craft.client.render.texture.TextureMap;
import org.craft.maths.*;
import org.craft.utils.*;
import org.craft.world.*;
public class BlockModelRenderer extends AbstractBlockRenderer
{
private HashMap<BlockVariant, HashMap<String, TextureIcon>> icons;
private List<BlockVariant> blockVariants;
private static Quaternion rotationQuaternion;
/**
* Creates a new renderer for given block variants
*/
public BlockModelRenderer(List<BlockVariant> list)
{
this.blockVariants = list;
icons = Maps.newHashMap();
for(BlockVariant v : list)
icons.put(v, new HashMap<String, TextureIcon>());
if(rotationQuaternion == null)
rotationQuaternion = new Quaternion();
}
@Override
public void render(RenderEngine engine, OffsettedOpenGLBuffer buffer, World w, Block b, int x, int y, int z)
{
if(!b.shouldRender())
return;
Chunk chunk = null;
if(w != null)
chunk = w.getChunk(x, y, z);
BlockVariant variant = null;
float lightValue = 1f;
if(chunk == null)
variant = blockVariants.get(0);
else
{
variant = getVariant(w, b, x, y, z);
lightValue = chunk.getLightValue(w, x, y, z);
}
if(variant == null)
variant = blockVariants.get(0);
Model blockModel = variant.getModels().get(w == null ? 0 : w.getRNG().nextInt(variant.getModels().size())); // TODO: random model ?
for(int i = 0; i < blockModel.getElementsCount(); i++ )
{
ModelElement element = blockModel.getElement(i);
if(element.hasRotation())
{
Vector3 axis = Vector3.xAxis;
if(element.getRotationAxis() == null)
;
else if(element.getRotationAxis().equalsIgnoreCase("y"))
axis = Vector3.yAxis;
else if(element.getRotationAxis().equalsIgnoreCase("z"))
axis = Vector3.zAxis;
rotationQuaternion.init(axis, (float) Math.toRadians(element.getRotationAngle()));
}
Set<Entry<String, ModelFace>> entries = element.getFaces().entrySet();
Vector3 startPos = element.getFrom();
Vector3 size = element.getTo().sub(startPos);
for(Entry<String, ModelFace> entry : entries)
{
Vector3 faceStart = Vector3.NULL;
Vector3 faceSize = Vector3.NULL;
TextureIcon icon = getTexture(blockModel, variant, entry.getValue().getTexture());
boolean flip = false;
EnumSide cullface = EnumSide.fromString(entry.getValue().getCullface());
EnumSide side = EnumSide.fromString(entry.getKey());
if(side != null)
{
if(entry.getValue().hideIfSameAdjacent() && w.getBlockNextTo(x, y, z, side) == b)
{
continue;
}
}
if(cullface != EnumSide.UNDEFINED)
{
Block next = Blocks.air;
if(w != null)
next = w.getBlockNextTo(x, y, z, cullface);
if(next.isSideOpaque(w, x, y, z, cullface.opposite()))
{
continue;
}
}
if(entry.getKey().equals("up"))
{
faceStart = Vector3.get(startPos.getX(), startPos.getY() + size.getY(), startPos.getZ());
faceSize = Vector3.get(size.getX(), 0, size.getZ());
flip = true;
}
else if(entry.getKey().equals("down"))
{
faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ());
faceSize = Vector3.get(size.getX(), 0, size.getZ());
flip = true;
}
else if(entry.getKey().equals("west"))
{
faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ());
faceSize = Vector3.get(0, size.getY(), size.getZ());
}
else if(entry.getKey().equals("east"))
{
faceStart = Vector3.get(startPos.getX() + size.getX(), startPos.getY(), startPos.getZ());
faceSize = Vector3.get(0, size.getY(), size.getZ());
}
else if(entry.getKey().equals("north"))
{
faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ());
faceSize = Vector3.get(size.getX(), size.getY(), 0);
}
else if(entry.getKey().equals("south"))
{
faceStart = Vector3.get(startPos.getX(), startPos.getY(), startPos.getZ() + size.getZ());
faceSize = Vector3.get(size.getX(), size.getY(), 0);
}
else
{
continue;
}
renderFace(lightValue, buffer, x, y, z, icon, faceStart, faceSize, flip, entry.getValue().getMinUV(), entry.getValue().getMaxUV(), element.getRotationOrigin(), rotationQuaternion, element.shouldRescale());
faceSize.dispose();
faceStart.dispose();
}
size.dispose();
}
}
/**
* Returns most revelant variant depending on block states values at (x,y,z)
*/
private BlockVariant getVariant(World w, Block b, int x, int y, int z)
{
BlockVariant variant = null;
variantLoop: for(BlockVariant v : blockVariants)
{
if(v.getBlockStates() == null && variant == null)
{
variant = v;
}
else if(v.getBlockStates().isEmpty() && variant == null)
{
variant = v;
}
else
{
for(int i = 0; i < v.getBlockStates().size(); i++ )
{
BlockState state = v.getBlockStates().get(i);
IBlockStateValue value = v.getBlockStateValues().get(i);
if(w.getBlockState(x, y, z, state) != value)
{
continue variantLoop;
}
}
if(variant != null)
{
if(variant.getBlockStates().size() <= v.getBlockStates().size())
{
variant = v;
}
else if(variant.getBlockStates().size() > v.getBlockStates().size())
continue variantLoop;
}
else
{
variant = v;
}
}
}
return variant;
}
/**
* Gets TextureIcon from texture variable found in json model file
*/
private TextureIcon getTexture(Model blockModel, BlockVariant variant, String texture)
{
if(texture == null)
return null;
if(!icons.get(variant).containsKey(texture))
{
if(texture.startsWith("#"))
{
TextureIcon icon = getTexture(blockModel, variant, blockModel.getTexturePath(texture.substring(1)));
icons.get(variant).put(texture, icon);
}
else
{
TextureMap blockMap = OurCraft.getOurCraft().getRenderEngine().blocksAndItemsMap;
icons.get(variant).put(texture, blockMap.get(texture + ".png"));
}
}
return icons.get(variant).get(texture);
}
@Override
public boolean shouldRenderInPass(EnumRenderPass currentPass, World w, Block b, int x, int y, int z)
{
BlockVariant variant = getVariant(w, b, x, y, z);
if(variant == null)
return false;
return currentPass == variant.getPass();
}
}
| mit |
cscfa/bartleby | library/logBack/logback-1.1.3/logback-core/src/main/java/ch/qos/logback/core/pattern/color/GrayCompositeConverter.java | 970 | /**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.core.pattern.color;
import static ch.qos.logback.core.pattern.color.ANSIConstants.*;
/**
* Encloses a given set of converter output in gray using the appropriate ANSI
* escape codes.
*
* @param <E>
* @author Ceki Gülcü
* @since 1.0.5
*/
public class GrayCompositeConverter<E> extends ForegroundCompositeConverterBase<E> {
@Override
protected String getForegroundColorCode(E event) {
return BOLD + BLACK_FG;
}
}
| mit |
thekant/myCodeRepo | src/com/kant/datastructure/stacks/StockSpanProblem.java | 2329 | /**
*
*/
package com.kant.datastructure.stacks;
import com.kant.sortingnsearching.MyUtil;
/**
* http://www.geeksforgeeks.org/the-stock-span-problem/ <br/>
*
*
* The stock span problem is a financial problem where we have a series of n
* daily price quotes for a stock and we need to calculate span of stocks price
* for all n days. The span Si of the stocks price on a given day i is defined
* as the maximum number of consecutive days just before the given day, for
* which the price of the stock on the current day is less than or equal to its
* price on the given day. For example, if an array of 7 days prices is given as
* {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days
* are {1, 1, 1, 2, 1, 4, 6}
*
* @author shaskant
*
*/
public class StockSpanProblem {
int[] stockData;// prices
/**
*
*/
public StockSpanProblem(int[] stockData) {
this.stockData = stockData;
}
/**
* General approach. TESTED
*
* @return
*/
public int[] getStackSpan() {
int[] result = new int[stockData.length];
for (int i = 0; i < stockData.length; i++) {
result[i] = 1;
for (int j = i - 1; j > 0; j--) {
if (stockData[i] > stockData[j])
result[i]++;
}
}
return result;
}
/**
* TESTED
*
* @return
*/
public int[] getStackSpanOptimal() {
int[] result = new int[stockData.length];
result[0] = 1;
// store indexes
Stack<Integer> stack = new StackListImplementation<>(false);
stack.push(0);
for (int i = 1; i < stockData.length; i++) {
// pop as long as top element is lesser.
while (!stack.isEmpty()
&& stockData[stack.peek().intValue()] <= stockData[i]) {
stack.pop();
}
// if stack is empty , current stock price is greater than all
// before it , else index difference between current and index of
// greater element at top of stack
result[i] = (stack.isEmpty()) ? (i + 1) : (i - stack.peek());
stack.push(i);
}
return result;
}
/**
*
* @param args
*/
public static void main(String[] args) {
StockSpanProblem stockSpan = new StockSpanProblem(new int[] { 100, 80,
60, 70, 60, 75, 85 });
int[] result = stockSpan.getStackSpanOptimal();
MyUtil.printArrayInt(result);
}
}
| mit |
jasonlam604/StockTechnicals | src/com/jasonlam604/stocktechnicals/indicators/MovingAverageConvergenceDivergence.java | 2631 | package com.jasonlam604.stocktechnicals.indicators;
import com.jasonlam604.stocktechnicals.util.NumberFormatter;
/**
* Moving Average Convergence/Divergence Oscillator
*/
public class MovingAverageConvergenceDivergence {
private static final int CROSSOVER_NONE = 0;
private static final int CROSSOVER_POSITIVE = 1;
private static final int CROSSOVER_NEGATIVE = -1;
private double[] prices;
private double[] macd;
private double[] signal;
private double[] diff;
private int[] crossover;
public MovingAverageConvergenceDivergence calculate(double[] prices, int fastPeriod, int slowPeriod,
int signalPeriod) throws Exception {
this.prices = prices;
this.macd = new double[prices.length];
this.signal = new double[prices.length];
this.diff = new double[prices.length];
this.crossover = new int[prices.length];
ExponentialMovingAverage emaShort = new ExponentialMovingAverage();
emaShort.calculate(prices, fastPeriod).getEMA();
ExponentialMovingAverage emaLong = new ExponentialMovingAverage();
emaLong.calculate(prices, slowPeriod).getEMA();
for (int i = slowPeriod - 1; i < this.prices.length; i++) {
this.macd[i] = NumberFormatter.round(emaShort.getEMA()[i] - emaLong.getEMA()[i]);
}
ExponentialMovingAverage signalEma = new ExponentialMovingAverage();
this.signal = signalEma.calculate(this.macd, signalPeriod).getEMA();
for (int i = 0; i < this.macd.length; i++) {
this.diff[i] = this.macd[i] - this.signal[i];
if (this.diff[i] > 0 && this.diff[i - 1] < 0) {
this.crossover[i] = MovingAverageConvergenceDivergence.CROSSOVER_POSITIVE;
} else if (this.diff[i] < 0 && this.diff[i - 1] > 0) {
this.crossover[i] = MovingAverageConvergenceDivergence.CROSSOVER_NEGATIVE;
} else {
this.crossover[i] = MovingAverageConvergenceDivergence.CROSSOVER_NONE;
}
}
return this;
}
public double[] getMACD() {
return this.macd;
}
public double[] getSignal() {
return this.signal;
}
public double[] getDiff() {
return this.diff;
}
public int[] getCrossover() {
return this.crossover;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.prices.length; i++) {
sb.append(String.format("%02.2f", this.prices[i]));
sb.append(" ");
sb.append(String.format("%02.2f", this.macd[i]));
sb.append(" ");
sb.append(String.format("%02.2f", this.signal[i]));
sb.append(" ");
sb.append(String.format("%02.2f", this.diff[i]));
sb.append(" ");
sb.append(String.format("%d", this.crossover[i]));
sb.append(" ");
sb.append("\n");
}
return sb.toString();
}
}
| mit |
guberti/AliensGame | ConsoleAliensGame/src/consolealiensgame/AlienContainer.java | 4017 | /*
* 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 consolealiensgame;
import alieninterfaces.*;
import java.lang.reflect.Constructor;
/**
*
* @author guberti
*/
public class AlienContainer {
public final String alienPackageName;
public final String alienClassName;
public final Constructor<?> alienConstructor;
private final Alien alien;
private final AlienAPI api;
int tech;
int energy;
boolean fought;
public int x;
public int y;
public boolean action; // Whether the alien has performed an action this turn
// Declare stats here
//
// Heads up: This constructs an AlienContainer and contained Alien
//
public AlienContainer(int x, int y, String alienPackageName, String alienClassName, Constructor<?> cns, int energy, int tech) {
Alien a;
this.alienPackageName = alienPackageName;
this.alienClassName = alienClassName;
this.alienConstructor = cns;
this.energy = energy;
this.tech = tech;
this.api = new AlienAPI(this);
// construct and initialize alien
try
{
a = (Alien) cns.newInstance();
a.init(this.api);
} catch (Throwable t)
{
a = null;
t.printStackTrace();
}
this.alien = a;
}
public void move(ViewImplementation view) throws NotEnoughTechException {
// Whether the move goes off the board will be determined by the grid
api.view = view;
MoveDir direction = alien.getMove();
checkMove(direction); // Throws an exception if illegal
x += direction.x();
y += direction.y();
}
public void kill() {
energy = Integer.MIN_VALUE;
}
public Action getAction(ViewImplementation view) throws NotEnoughEnergyException, UnknownActionException {
api.view = view;
Action action = alien.getAction();
switch (action.code) {
case None:
case Gain:
return new Action (action.code);
case Research:
if (tech > energy) { // If the tech can't be researched due to lack of energy
throw new NotEnoughEnergyException();
}
// Otherwise
return new Action (ActionCode.Research, tech);
case Spawn:
if (action.power + 3 > energy) {
throw new NotEnoughEnergyException();
}
return action;
default:
throw new UnknownActionException();
}
}
public int fight() throws NotEnoughEnergyException, NotEnoughTechException {
int fightPower = 0; //alien.getFightPower(api); GM need to fix this up after reconciling fighting into Action
// If the alien cannot fight with the amount of energy it wants
// Throw the appropriate exception
if (fightPower > energy) {
throw new NotEnoughEnergyException();
}
if (fightPower > tech) {
throw new NotEnoughTechException();
}
// If the move is valid, subtract the energy expended
energy -= fightPower;
// Return how much power the alien will fight with
return fightPower;
}
private void checkMove(MoveDir direction) throws NotEnoughTechException {
// If the move is farther than the alien has the tech to move
if (Math.pow(direction.x(), 2) + Math.pow(direction.y(), 2)
> Math.pow(tech, 2)) {
throw new NotEnoughTechException();
}
}
}
class NotEnoughEnergyException extends Exception {}
class NotEnoughTechException extends Exception {}
class UnknownActionException extends Exception {} | mit |
KhaledMuahamed/GameDevelop | Game/src/model/question/ImageQuestion.java | 1428 | package model.question;
import model.enums.QuestionTypes;
public class ImageQuestion implements QuestionIF {
private String imagePath;
private char[] answer;
private QuestionTypes type;
public ImageQuestion(String imagePath, char[] answer, QuestionTypes type){
this.setType(type);
this.setImagePath(imagePath);
this.setAnswer(answer);
}
private void setType(QuestionTypes type) {
// TODO Auto-generated method stub
this.type = type;
}
private void setAnswer(char[] answer) {
// TODO Auto-generated method stub
this.answer = answer;
}
private void setImagePath(String imagePath) {
// TODO Auto-generated method stub
this.imagePath = imagePath;
}
// ************************************************************************
// get question from file
// ************************************************************************
@Override
public String getQuestion() {
// TODO Auto-generated method stub
return imagePath;
}
// ************************************************************************
// get the answer read from file
// ************************************************************************
@Override
public char[] getAnswer() {
// TODO Auto-generated method stub
return answer;
}
@Override
public QuestionTypes getType() {
// TODO Auto-generated method stub
return type;
}
}
| mit |
kieranhogan13/Java | Distributed Systems/Labs/Week 7_Lab_Review/Week_3_T7/TCPSerServer.java | 1769 |
// Week 5 - Task 7
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class TCPSerServer
{
private static ServerSocket servSock;
private static final int PORT = 1234;
public static void main(String[] args)
{
System.out.println("!!!Opening port...\n");
try
{
servSock = new ServerSocket(PORT);
}
catch(IOException e)
{
System.out.println("Unable to attach to port!");
System.exit(1);
}
do
{
run();
}while (true);
}
private static void run()
{
Socket link = null;
try{
link = servSock.accept();
PrintWriter out = new PrintWriter(link.getOutputStream(),true);
ObjectInputStream istream = new ObjectInputStream (link.getInputStream());
Person p = null;
while(true){
try{
p = (Person)istream.readObject();
System.out.println("SERVER - Received: New object.\n");
System.out.println("SERVER - Received: Person name=" + p.getName());
System.out.println("SERVER - Received: Person age=" + p.getAge());
System.out.println("SERVER - Received: Person address=" + p.getAddress());
out.println("Person object received.");
}
catch (Exception e) {
System.out.println("Exception in run");
System.out.println("\n* Closing connection... *");
break;
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
System.out.println("\n* Closing connection... *");
link.close();
}
catch(IOException e)
{
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
| mit |
yht-fand/cardone-platform-usercenter | consumer/src/test/java/top/cardone/func/vx/usercenter/userDepartment/D0002FuncTest.java | 3282 | package top.cardone.func.vx.usercenter.userDepartment;
import com.google.common.base.Charsets;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StopWatch;
import top.cardone.ConsumerApplication;
import top.cardone.context.ApplicationContextHolder;
import java.io.IOException;
@Log4j2
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class D0002FuncTest {
@Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/vx/usercenter/userDepartment/d0002.json")
private String funcUrl;
@Value("file:src/test/resources/top/cardone/func/vx/usercenter/userDepartment/D0002FuncTest.func.input.json")
private Resource funcInputResource;
@Value("file:src/test/resources/top/cardone/func/vx/usercenter/userDepartment/D0002FuncTest.func.output.json")
private Resource funcOutputResource;
private HttpEntity<String> httpEntity;
private int pressure = 10000;
@Before
public void setup() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword("admin"));
headers.set("username", "admin");
if (!funcInputResource.exists()) {
FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8);
}
String input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8);
httpEntity = new HttpEntity<>(input, headers);
}
@Test
public void func() throws RuntimeException {
String output = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class);
try {
FileUtils.write(funcOutputResource.getFile(), output, Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void pressureFunc() throws Exception {
for (int i = 0; i < pressure; i++) {
val sw = new StopWatch();
sw.start(funcUrl);
new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class);
sw.stop();
if (sw.getTotalTimeMillis() > 500) {
log.error(sw.prettyPrint());
} else if (log.isDebugEnabled()) {
log.debug(sw.prettyPrint());
}
log.debug("pressured:" + (i + 1));
}
}
} | mit |
lg198/CodeFray | src/com/github/lg198/codefray/jfx/GameResultGui.java | 3347 | package com.github.lg198.codefray.jfx;
import com.github.lg198.codefray.api.game.Team;
import com.github.lg198.codefray.game.GameEndReason;
import com.github.lg198.codefray.game.GameStatistics;
import com.github.lg198.codefray.util.TimeFormatter;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
public class GameResultGui {
private final GameStatistics stats;
public GameResultGui(GameStatistics gs) {
stats = gs;
}
public VBox build() {
VBox root = new VBox();
root.setAlignment(Pos.CENTER);
root.setSpacing(10);
root.setPadding(new Insets(15));
Label title = new Label("Game Result");
title.setStyle("-fx-font-size: 30px");
title.setUnderline(true);
root.getChildren().add(title);
VBox.setMargin(title, new Insets(0, 0, 5, 0));
root.getChildren().addAll(
createWinnerStatBox(stats.reason),
createStatBox("Rounds:", "" + stats.rounds),
createStatBox("Length:", TimeFormatter.format(stats.timeInSeconds)),
createStatBox("Red Golems Left:", "" + stats.redLeft),
createStatBox("Blue Golems Left:", "" + stats.blueLeft),
createStatBox("Red Health:", stats.redHealthPercent, Team.RED),
createStatBox("Blue Health:", stats.blueHealthPercent, Team.BLUE)
);
return root;
}
private HBox createWinnerStatBox(GameEndReason reason) {
HBox box = new HBox();
box.setSpacing(6);
box.setAlignment(Pos.CENTER);
if (reason instanceof GameEndReason.Win) {
Label key = new Label("Winner:");
Label value = new Label(((GameEndReason.Win)reason).winner.name());
key.setStyle("-fx-font-size: 20px");
value.setStyle(key.getStyle());
box.getChildren().addAll(key, value);
return box;
} else if (reason instanceof GameEndReason.Infraction) {
Label key = new Label(((GameEndReason.Infraction)reason).guilty.name() + " cheated and lost");
key.setStyle("-fx-font-size: 20px");
box.getChildren().addAll(key);
return box;
} else {
Label key = new Label("Winner:");
Label value = new Label("None");
key.setStyle("-fx-font-size: 20px");
value.setStyle(key.getStyle());
box.getChildren().addAll(key, value);
return box;
}
}
private HBox createStatBox(String name, String value) {
HBox box = new HBox();
box.setSpacing(6);
box.setAlignment(Pos.CENTER);
box.getChildren().addAll(new Label(name), new Label(value));
return box;
}
private HBox createStatBox(String name, double perc, Team team) {
HBox box = new HBox();
box.setAlignment(Pos.CENTER);
box.setSpacing(6);
ProgressBar pb = new ProgressBar(perc);
if (team == Team.RED) {
pb.setStyle("-fx-accent: red");
} else {
pb.setStyle("-fx-accent: blue");
}
box.getChildren().addAll(new Label(name), pb);
return box;
}
}
| mit |
YourEmpire/YourEmpire | Your Empire API/src/main/java/pl/yourempire/api/event/Event.java | 1714 | package pl.yourempire.api.event;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Event
{
private static Map<Class<Event>, ArrayList<ListenerCaller>> listenerMap = new HashMap<>();
public static void callEvent(Event e)
{
if (listenerMap.containsKey(e.getClass()))
{
for (ListenerCaller lc : listenerMap.get(e.getClass()))
{
try
{
lc.getEventMethod().invoke(lc.getInstance(), e);
} catch (IllegalAccessException e1)
{
e1.printStackTrace();
} catch (InvocationTargetException e1)
{
e1.printStackTrace();
}
}
}
}
public static boolean isEvent(Class<?> clazz)
{
try
{
clazz.cast(Event.class);
return true;
} catch(ClassCastException e)
{
return false;
}
}
public static void registerListener(Listener l)
{
Arrays.asList(l.getClass().getMethods()).forEach(m -> {
if (m.getParameterTypes().length == 1 && isEvent(m.getParameterTypes()[0]))
{
listenerMap.get(m.getParameterTypes()[0]).add(new ListenerCaller(l, m));
}
});
}
protected boolean cancelled;
public Event()
{
cancelled = false;
}
public void setCancelled(boolean flag)
{
this.cancelled = flag;
}
public boolean isCancelled()
{
return this.cancelled;
}
}
| mit |
wipu/iwant | essential/iwant-planner-api/src/main/java/org/fluentjava/iwant/plannerapi/ResourcePool.java | 164 | package org.fluentjava.iwant.plannerapi;
public interface ResourcePool {
boolean hasFreeResources();
Resource acquire();
void release(Resource resource);
}
| mit |
nileshk/truedolist-java | src/main/java/com/myconnector/client/domain/TodoListClient.java | 1476 | package com.myconnector.client.domain;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.myconnector.client.domain.interfaces.ITodoContext;
import com.myconnector.client.domain.interfaces.ITodoItem;
import com.myconnector.client.domain.interfaces.ITodoList;
public class TodoListClient implements IsSerializable, ITodoList {
private Long id;
private String title;
private boolean todoItemsLoaded = false;
private List<ITodoItem> todoItems;
private Integer position;
private ITodoContext context;
public TodoListClient() {
}
public TodoListClient(Long id, String title) {
super();
this.id = id;
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<ITodoItem> getTodoItems() {
return todoItems;
}
public void setTodoItems(List<ITodoItem> todoItems) {
this.todoItems = todoItems;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public boolean isTodoItemsLoaded() {
return todoItemsLoaded;
}
public void setTodoItemsLoaded(boolean todoItemsLoaded) {
this.todoItemsLoaded = todoItemsLoaded;
}
public ITodoContext getContext() {
return context;
}
public void setContext(ITodoContext context) {
this.context = context;
}
}
| mit |
dst-hackathon/socialradar-android | hackathon2014/app/src/main/java/com/hackathon/hackathon2014/activity/QuestionActivity.java | 4070 | package com.hackathon.hackathon2014.activity;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.hackathon.hackathon2014.R;
import com.hackathon.hackathon2014.webservice.PostRequestHandler;
import com.hackathon.hackathon2014.webservice.RestProvider;
import com.hackathon.hackathon2014.adapter.QuestionListAdapter;
import com.hackathon.hackathon2014.model.Question;
import java.util.List;
public class QuestionActivity extends Activity {
public static String EXTRA_QUESTION = "question";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.question, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_question, container, false);
Toast.makeText(rootView.getContext(),"Loading...",Toast.LENGTH_LONG).show();
RestProvider.getQuestions(new PostRequestHandler<List<Question>>() {
@Override
public void handle(List<Question> questions) {
QuestionListAdapter questionListAdapter = new QuestionListAdapter(getActivity(), questions);
ListView listView = (ListView) rootView.findViewById(R.id.questionListView);
listView.setAdapter(questionListAdapter);
listView.setOnItemClickListener(new OpenAnswerEvent(getActivity(), questions));
}
});
return rootView;
}
private class OpenAnswerEvent implements android.widget.AdapterView.OnItemClickListener {
private List<Question> questions;
private Activity activity;
private OpenAnswerEvent(Activity activity, List<Question> questions) {
this.activity = activity;
this.questions = questions;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Question question = questions.get(i);
question.setSelected(true);
Intent intent = new Intent(activity,CategoryActivity.class);
intent.putExtra(EXTRA_QUESTION, question);
activity.startActivity(intent);
final ImageView questionIcon = (ImageView) view.findViewById(R.id.questionIcon);
QuestionListAdapter.renderChecked(question.isSelected(), questionIcon, R.drawable.ok_enable, R.drawable.ok_disable);
}
}
}
}
| mit |
craigfreilly/masters-project-submission | src/KnotTheory/JavaKh-v2/src/net/tqft/iterables/interfaces/Transformer.java | 126 | package net.tqft.iterables.interfaces;
public interface Transformer<S, T> {
public abstract T evaluate(S s);
}
| mit |
WOVNio/wovnjava | src/test/java/com/github/wovnio/wovnjava/HeadersTest.java | 21076 | package com.github.wovnio.wovnjava;
import java.util.HashMap;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import org.easymock.EasyMock;
import java.net.URL;
import java.net.MalformedURLException;
import junit.framework.TestCase;
public class HeadersTest extends TestCase {
private Lang japanese;
protected void setUp() throws Exception {
this.japanese = Lang.get("ja");
}
private static FilterConfig mockConfigPath() {
HashMap<String, String> parameters = new HashMap<String, String>() {{
put("urlPattern", "path");
}};
return TestUtil.makeConfigWithValidDefaults(parameters);
}
private static FilterConfig mockConfigSubdomain() {
HashMap<String, String> parameters = new HashMap<String, String>() {{
put("urlPattern", "subdomain");
}};
return TestUtil.makeConfigWithValidDefaults(parameters);
}
private static FilterConfig mockConfigQuery() {
HashMap<String, String> parameters = new HashMap<String, String>() {{
put("urlPattern", "query");
put("defaultLang", "en");
put("supportedLangs", "en,ja,zh-CHS");
}};
return TestUtil.makeConfigWithValidDefaults(parameters);
}
public void testHeaders() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/ja/test");
FilterConfig mockConfig = mockConfigPath();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertNotNull(h);
}
public void testGetRequestLangPath() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/ja/test");
FilterConfig mockConfig = mockConfigPath();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals(this.japanese, h.getRequestLang());
}
public void testGetRequestLangSubdomain() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://ja.example.com/test");
FilterConfig mockConfig = mockConfigSubdomain();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals(this.japanese, h.getRequestLang());
}
public void testGetRequestLangQuery() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/test?wovn=ja");
FilterConfig mockConfig = mockConfigQuery();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals(this.japanese, h.getRequestLang());
}
public void testConvertToDefaultLanguage__PathPattern() throws ConfigurationError, MalformedURLException {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/ja/test");
FilterConfig mockConfig = mockConfigPath();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
URL url = new URL("http://example.com/ja/test");
assertEquals("http://example.com/test", h.convertToDefaultLanguage(url).toString());
}
public void testConvertToDefaultLanguage__SubdomainPattern() throws ConfigurationError, MalformedURLException {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://ja.example.com/test");
FilterConfig mockConfig = mockConfigSubdomain();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
URL url = new URL("http://ja.example.com/test");
assertEquals("http://example.com/test", h.convertToDefaultLanguage(url).toString());
}
public void testConvertToDefaultLanguage__QueryPattern() throws ConfigurationError, MalformedURLException {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/test?wovn=ja");
FilterConfig mockConfig = mockConfigQuery();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
URL url = new URL("http://example.com/test?wovn=ja");
assertEquals("http://example.com/test", h.convertToDefaultLanguage(url).toString());
}
public void testConvertToDefaultLanguage__PathPatternWithSitePrefixPath() throws ConfigurationError, MalformedURLException {
Headers h = createHeaders("/global/en/foo", "/global/", "");
URL url;
url = new URL("http://site.com/global/en/");
assertEquals("http://site.com/global/", h.convertToDefaultLanguage(url).toString());
url = new URL("http://site.com/en/global/");
assertEquals("http://site.com/en/global/", h.convertToDefaultLanguage(url).toString());
}
public void testLocationWithDefaultLangCode() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/signin");
FilterConfig mockConfig = mockConfigPath();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals("http://example.com/", h.locationWithLangCode("http://example.com/"));
assertEquals("https://example.com/", h.locationWithLangCode("https://example.com/"));
assertEquals("https://example.com/dir/file", h.locationWithLangCode("https://example.com/dir/file"));
}
public void testLocationWithPath() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/ja/dir/signin");
FilterConfig mockConfig = mockConfigPath();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals("http://example.com/ja/", h.locationWithLangCode("http://example.com/"));
assertEquals("https://example.com/ja/", h.locationWithLangCode("https://example.com/"));
assertEquals("https://example.com/ja/dir/file", h.locationWithLangCode("https://example.com/dir/file"));
assertEquals("https://other.com/dir/file", h.locationWithLangCode("https://other.com/dir/file"));
assertEquals("https://example.com/ja/", h.locationWithLangCode("/"));
assertEquals("https://example.com/ja/dir/file", h.locationWithLangCode("/dir/file"));
assertEquals("https://example.com/ja/dir/file", h.locationWithLangCode("./file"));
assertEquals("https://example.com/ja/file", h.locationWithLangCode("../file"));
assertEquals("https://example.com/ja/file", h.locationWithLangCode("../../file"));
}
public void testLocationWithPathAndTrailingSlash() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/ja/dir/signin/");
FilterConfig mockConfig = mockConfigPath();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals("https://example.com/ja/dir/signin/file", h.locationWithLangCode("./file"));
assertEquals("https://example.com/ja/dir/file", h.locationWithLangCode("../file"));
assertEquals("https://example.com/ja/file", h.locationWithLangCode("../../file"));
assertEquals("https://example.com/ja/file", h.locationWithLangCode("../../../file"));
}
public void testLocationWithPathAndTopLevel() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/location.jsp?wovn=ja");
FilterConfig mockConfig = mockConfigQuery();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals("https://example.com/index.jsp?wovn=ja", h.locationWithLangCode("./index.jsp"));
}
public void testLocationWithQuery() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com/dir/signin?wovn=ja");
FilterConfig mockConfig = mockConfigQuery();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals("http://example.com/?wovn=ja", h.locationWithLangCode("http://example.com/"));
assertEquals("https://example.com/?wovn=ja", h.locationWithLangCode("https://example.com/"));
assertEquals("https://example.com/dir/file?wovn=ja", h.locationWithLangCode("https://example.com/dir/file"));
assertEquals("https://other.com/dir/file", h.locationWithLangCode("https://other.com/dir/file"));
assertEquals("https://example.com/?wovn=ja", h.locationWithLangCode("/"));
assertEquals("https://example.com/dir/file?wovn=ja", h.locationWithLangCode("/dir/file"));
assertEquals("https://example.com/dir/file?wovn=ja", h.locationWithLangCode("./file"));
assertEquals("https://example.com/file?wovn=ja", h.locationWithLangCode("../file"));
assertEquals("https://example.com/file?wovn=ja", h.locationWithLangCode("../../file"));
assertEquals("https://example.com/file?q=hello&wovn=ja", h.locationWithLangCode("../../file?q=hello&wovn=zh-CHS"));
assertEquals("https://example.com/file?wovn=ja", h.locationWithLangCode("../../file?wovn=zh-CHS"));
}
public void testLocationWithSubdomain() throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://ja.example.com/dir/signin");
FilterConfig mockConfig = mockConfigSubdomain();
Settings s = new Settings(mockConfig);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
Headers h = new Headers(mockRequest, s, ulph);
assertEquals("http://ja.example.com/", h.locationWithLangCode("http://example.com/"));
assertEquals("https://ja.example.com/", h.locationWithLangCode("https://example.com/"));
assertEquals("https://ja.example.com/dir/file", h.locationWithLangCode("https://example.com/dir/file"));
assertEquals("https://other.com/dir/file", h.locationWithLangCode("https://other.com/dir/file"));
assertEquals("https://fr.example.com/dir/file", h.locationWithLangCode("https://fr.example.com/dir/file"));
assertEquals("https://ja.example.com/", h.locationWithLangCode("/"));
assertEquals("https://ja.example.com/dir/file", h.locationWithLangCode("/dir/file"));
assertEquals("https://ja.example.com/dir/file", h.locationWithLangCode("./file"));
assertEquals("https://ja.example.com/file", h.locationWithLangCode("../file"));
assertEquals("https://ja.example.com/file", h.locationWithLangCode("../../file"));
}
public void testLocationWithSitePrefixPath() throws ConfigurationError {
Headers h = createHeaders("/global/ja/foo", "/global/", "");
assertEquals("http://example.com/", h.locationWithLangCode("http://example.com/"));
assertEquals("http://example.com/global/ja/", h.locationWithLangCode("http://example.com/global/"));
assertEquals("https://example.com/global/ja/", h.locationWithLangCode("https://example.com/global/"));
assertEquals("https://example.com/global/ja/", h.locationWithLangCode("https://example.com/global/ja/"));
assertEquals("https://example.com/global/ja/th/", h.locationWithLangCode("https://example.com/global/th/")); // `th` not in supportedLangs
assertEquals("https://example.com/global/ja/tokyo/", h.locationWithLangCode("https://example.com/global/tokyo/"));
assertEquals("https://example.com/global/ja/file.html", h.locationWithLangCode("https://example.com/global/file.html"));
assertEquals("https://example.com/global/ja/file.html", h.locationWithLangCode("https://example.com/pics/../global/file.html"));
assertEquals("https://example.com/global/../../file.html", h.locationWithLangCode("https://example.com/global/../../file.html"));
assertEquals("https://example.com/tokyo/", h.locationWithLangCode("https://example.com/tokyo/"));
assertEquals("https://example.com/tokyo/global/", h.locationWithLangCode("https://example.com/tokyo/global/"));
assertEquals("https://example.com/ja/global/", h.locationWithLangCode("https://example.com/ja/global/"));
assertEquals("https://example.com/th/global/", h.locationWithLangCode("https://example.com/th/global/"));
assertEquals("https://example.com/th/", h.locationWithLangCode("https://example.com/th/"));
}
public void testGetIsValidRequest() throws ConfigurationError {
Headers h;
h = createHeaders("/", "global", "");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/global", "global", "");
assertEquals(true, h.getIsValidRequest());
h = createHeaders("/global/ja/foo", "global", "");
assertEquals(true, h.getIsValidRequest());
h = createHeaders("/ja/global/foo", "global", "");
assertEquals(false, h.getIsValidRequest());
}
public void testGetIsValidRequest__withIgnoredPaths() throws ConfigurationError {
Headers h;
h = createHeaders("/", "", "/admin,/wp-admin");
assertEquals(true, h.getIsValidRequest());
h = createHeaders("/user/admin", "", "/admin,/wp-admin");
assertEquals(true, h.getIsValidRequest());
h = createHeaders("/adminpage", "", "/admin,/wp-admin");
assertEquals(true, h.getIsValidRequest());
h = createHeaders("/admin", "", "/admin,/wp-admin");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/wp-admin/", "", "/admin,/wp-admin");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/wp-admin/page", "", "/admin,/wp-admin");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/ja/admin", "", "/admin,/wp-admin");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/ja/wp-admin/", "", "/admin,/wp-admin");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/en/admin", "", "/admin,/wp-admin");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/en/wp-admin/", "", "/admin,/wp-admin");
assertEquals(false, h.getIsValidRequest());
h = createHeaders("/city/wp-admin", "city", "/admin,/wp-admin");
assertEquals(true, h.getIsValidRequest());
h = createHeaders("/city/wp-admin", "city", "/city/admin,/city/wp-admin");
assertEquals(false, h.getIsValidRequest());
}
private Headers createHeaders(String requestPath, String sitePrefixPath, String ignorePaths) throws ConfigurationError {
HttpServletRequest mockRequest = MockHttpServletRequest.create("https://example.com" + requestPath);
HashMap<String, String> option = new HashMap<String, String>() {{
put("urlPattern", "path");
put("sitePrefixPath", sitePrefixPath);
put("ignorePaths", ignorePaths);
}};
Settings s = TestUtil.makeSettings(option);
UrlLanguagePatternHandler ulph = UrlLanguagePatternHandlerFactory.create(s);
return new Headers(mockRequest, s, ulph);
}
public void testGetHreflangUrlMap__PathPattern() throws ConfigurationError {
Settings settings = TestUtil.makeSettings(new HashMap<String, String>() {{
put("defaultLang", "en");
put("supportedLangs", "en,ja,fr");
put("urlPattern", "path");
put("sitePrefixPath", "/home");
}});
UrlLanguagePatternHandler patternHandler = UrlLanguagePatternHandlerFactory.create(settings);
HttpServletRequest request = MockHttpServletRequest.create("https://example.com/home?user=123");
Headers sut = new Headers(request, settings, patternHandler);
HashMap<String, String> hreflangs = sut.getHreflangUrlMap();
assertEquals(3, hreflangs.size());
assertEquals("https://example.com/home?user=123", hreflangs.get("en"));
assertEquals("https://example.com/home/ja?user=123", hreflangs.get("ja"));
assertEquals("https://example.com/home/fr?user=123", hreflangs.get("fr"));
}
public void testGetHreflangUrlMap__QueryPattern() throws ConfigurationError {
Settings settings = TestUtil.makeSettings(new HashMap<String, String>() {{
put("defaultLang", "ja");
put("supportedLangs", "ko");
put("urlPattern", "query");
}});
UrlLanguagePatternHandler patternHandler = UrlLanguagePatternHandlerFactory.create(settings);
HttpServletRequest request = MockHttpServletRequest.create("https://example.com/home?user=123");
Headers sut = new Headers(request, settings, patternHandler);
HashMap<String, String> hreflangs = sut.getHreflangUrlMap();
assertEquals(2, hreflangs.size());
assertEquals("https://example.com/home?user=123", hreflangs.get("ja"));
assertEquals("https://example.com/home?user=123&wovn=ko", hreflangs.get("ko"));
}
public void testGetHreflangUrlMap__SubdomainPattern__WithChineseSupportedLangs() throws ConfigurationError {
Settings settings = TestUtil.makeSettings(new HashMap<String, String>() {{
put("defaultLang", "ja");
put("supportedLangs", "ko,th, zh-CHT, zh-CHS");
put("urlPattern", "subdomain");
}});
UrlLanguagePatternHandler patternHandler = UrlLanguagePatternHandlerFactory.create(settings);
HttpServletRequest request = MockHttpServletRequest.create("https://example.com/home?user=123");
Headers sut = new Headers(request, settings, patternHandler);
HashMap<String, String> hreflangs = sut.getHreflangUrlMap();
assertEquals(5, hreflangs.size());
assertEquals("https://example.com/home?user=123", hreflangs.get("ja"));
assertEquals("https://ko.example.com/home?user=123", hreflangs.get("ko"));
assertEquals("https://th.example.com/home?user=123", hreflangs.get("th"));
assertEquals("https://zh-CHT.example.com/home?user=123", hreflangs.get("zh-Hant"));
assertEquals("https://zh-CHS.example.com/home?user=123", hreflangs.get("zh-Hans"));
}
public void testIsSearchEngineBot_NoUserAgent_False() throws ConfigurationError {
String userAgent = null;
Settings settings = TestUtil.makeSettings();
UrlLanguagePatternHandler patternHandler = UrlLanguagePatternHandlerFactory.create(settings);
HttpServletRequest request = MockHttpServletRequest.create("https://example.com/home?user=123", userAgent);
Headers sut = new Headers(request, settings, patternHandler);
assertEquals(false, sut.isSearchEngineBot());
}
public void testIsSearchEngineBot_OrdinaryUserAgent_False() throws ConfigurationError {
String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.81 Safari/537.36";
Settings settings = TestUtil.makeSettings();
UrlLanguagePatternHandler patternHandler = UrlLanguagePatternHandlerFactory.create(settings);
HttpServletRequest request = MockHttpServletRequest.create("https://example.com/home?user=123");
Headers sut = new Headers(request, settings, patternHandler);
assertEquals(false, sut.isSearchEngineBot());
}
public void testIsSearchEngineBot_SearchEngineBotUserAgent_True() throws ConfigurationError {
String userAgent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
Settings settings = TestUtil.makeSettings();
UrlLanguagePatternHandler patternHandler = UrlLanguagePatternHandlerFactory.create(settings);
HttpServletRequest request = MockHttpServletRequest.create("https://example.com/home?user=123", userAgent);
Headers sut = new Headers(request, settings, patternHandler);
assertEquals(true, sut.isSearchEngineBot());
}
}
| mit |
widmofazowe/cyfronoid-core | src/eu/cyfronoid/core/configuration/evaluator/Stack.java | 694 | package eu.cyfronoid.core.configuration.evaluator;
import java.util.ArrayDeque;
public class Stack extends ArrayDeque<Double> {
private static final long serialVersionUID = 1L;
@Override
public void push(Double v) {
super.push(v);
}
@Override
public Double pop() {
Double v = super.pop();
return v;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
for (Double v: this) {
builder.append(v);
builder.append(" ");
}
builder.append("]");
return builder.toString();
}
}
| mit |
gabizou/SpongeAPI | src/main/java/org/spongepowered/api/text/Texts.java | 19598 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.text;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import org.spongepowered.api.scoreboard.Score;
import org.spongepowered.api.text.format.TextColor;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.format.TextStyle;
import org.spongepowered.api.text.format.TextStyles;
import org.spongepowered.api.text.selector.Selector;
import org.spongepowered.api.text.translation.Translatable;
import org.spongepowered.api.text.translation.Translation;
import java.util.Locale;
/**
* Utility class to work with and create {@link Text}.
*/
public final class Texts {
private static final TextFactory factory = null;
static final Text.Literal EMPTY = new Text.Literal();
private Texts() {
}
/**
* Returns an empty, unformatted {@link Text} instance.
*
* @return An empty text
*/
public static Text of() {
return EMPTY;
}
/**
* Creates a {@link Text} with the specified plain text. The created message
* won't have any formatting or events configured.
*
* @param content The content of the text
* @return The created text
* @see Text.Literal
*/
public static Text.Literal of(String content) {
if (checkNotNull(content, "content").isEmpty()) {
return EMPTY;
}
return new Text.Literal(content);
}
/**
* Creates a new unformatted {@link Text.Translatable} with the given
* {@link Translation} and arguments.
*
* @param translation The translation for the text
* @param args The arguments for the translation
* @return The created text
* @see Text.Translatable
*/
public static Text.Translatable of(Translation translation, Object... args) {
return new Text.Translatable(translation, ImmutableList.copyOf(checkNotNull(args, "args")));
}
/**
* Creates a new unformatted {@link Text.Translatable} from the given
* {@link Translatable}.
*
* @param translatable The translatable for the text
* @param args The arguments for the translation
* @return The created text
* @see Text.Translatable
*/
public static Text.Translatable of(Translatable translatable, Object... args) {
return of(checkNotNull(translatable, "translatable").getTranslation(), args);
}
/**
* Creates a new unformatted {@link Text.Selector} with the given selector.
*
* @param selector The selector for the text
* @return The created text
* @see Text.Selector
*/
public static Text.Selector of(Selector selector) {
return new Text.Selector(selector);
}
/**
* Creates a new unformatted {@link Text.Score} with the given score.
*
* @param score The score for the text
* @return The created text
* @see Text.Score
*/
public static Text.Score of(Score score) {
return new Text.Score(score);
}
/**
* Builds a {@link Text} from a given array of objects.
*
* <p>For instance, you can use this like
* <code>Texts.of(TextColors.DARK_AQUA, "Hi", TextColors.AQUA, "Bye")</code>
* </p>
*
* <p>This will create the correct {@link Text} instance if the input object
* is the input for one of the {@link Text} types or convert the object to a
* string otherwise.</p>
*
* @param objects The object array
* @return The built text object
*/
public static Text of(Object... objects) {
TextBuilder builder = builder();
TextColor color = TextColors.NONE;
TextStyle style = TextStyles.NONE;
for (Object obj : objects) {
if (obj instanceof TextColor) {
color = (TextColor) obj;
} else if (obj instanceof TextStyle) {
style = obj.equals(TextStyles.RESET) ? TextStyles.NONE : style.and((TextStyle) obj);
} else if (obj instanceof Text) {
builder.append((Text) obj);
} else if (obj instanceof TextBuilder) {
builder.append(((TextBuilder) obj).build());
} else {
TextBuilder childBuilder;
if (obj instanceof String) {
childBuilder = Texts.builder((String) obj);
} else if (obj instanceof Translation) {
childBuilder = Texts.builder((Translation) obj);
} else if (obj instanceof Selector) {
childBuilder = Texts.builder((Selector) obj);
} else if (obj instanceof Score) {
childBuilder = Texts.builder((Score) obj);
} else {
childBuilder = Texts.builder(String.valueOf(obj));
}
builder.append(childBuilder.color(color).style(style).build());
}
}
return builder.build();
}
/**
* Creates a {@link TextBuilder} with empty text.
*
* @return A new text builder with empty text
*/
public static TextBuilder builder() {
return new TextBuilder.Literal();
}
/**
* Creates a new unformatted {@link TextBuilder.Literal} with the specified
* content.
*
* @param content The content of the text
* @return The created text builder
* @see Text.Literal
* @see TextBuilder.Literal
*/
public static TextBuilder.Literal builder(String content) {
return new TextBuilder.Literal(content);
}
/**
* Creates a new {@link TextBuilder.Literal} with the formatting and actions
* of the specified {@link Text} and the given content.
*
* @param text The text to apply the properties from
* @param content The content for the text builder
* @return The created text builder
* @see Text.Literal
* @see TextBuilder.Literal
*/
public static TextBuilder.Literal builder(Text text, String content) {
return new TextBuilder.Literal(text, content);
}
/**
* Creates a new unformatted {@link TextBuilder.Translatable} with the given
* {@link Translation} and arguments.
*
* @param translation The translation for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Translation translation, Object... args) {
return new TextBuilder.Translatable(translation, args);
}
/**
* Creates a new unformatted {@link TextBuilder.Translatable} from the given
* {@link Translatable}.
*
* @param translatable The translatable for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Translatable translatable, Object... args) {
return new TextBuilder.Translatable(translatable, args);
}
/**
* Creates a new {@link TextBuilder.Translatable} with the formatting and
* actions of the specified {@link Text} and the given {@link Translation}
* and arguments.
*
* @param text The text to apply the properties from
* @param translation The translation for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Text text, Translation translation, Object... args) {
return new TextBuilder.Translatable(text, translation, args);
}
/**
* Creates a new {@link TextBuilder.Translatable} with the formatting and
* actions of the specified {@link Text} and the given {@link Translatable}.
*
* @param text The text to apply the properties from
* @param translatable The translatable for the builder
* @param args The arguments for the translation
* @return The created text builder
* @see Text.Translatable
* @see TextBuilder.Translatable
*/
public static TextBuilder.Translatable builder(Text text, Translatable translatable, Object... args) {
return new TextBuilder.Translatable(text, translatable, args);
}
/**
* Creates a new unformatted {@link TextBuilder.Selector} with the given
* selector.
*
* @param selector The selector for the builder
* @return The created text builder
* @see Text.Selector
* @see TextBuilder.Selector
*/
public static TextBuilder.Selector builder(Selector selector) {
return new TextBuilder.Selector(selector);
}
/**
* Creates a new {@link TextBuilder.Selector} with the formatting and
* actions of the specified {@link Text} and the given selector.
*
* @param text The text to apply the properties from
* @param selector The selector for the builder
* @return The created text builder
* @see Text.Selector
* @see TextBuilder.Selector
*/
public static TextBuilder.Selector builder(Text text, Selector selector) {
return new TextBuilder.Selector(text, selector);
}
/**
* Creates a new unformatted {@link TextBuilder.Score} with the given score.
*
* @param score The score for the text builder
* @return The created text builder
* @see Text.Score
* @see TextBuilder.Score
*/
public static TextBuilder.Score builder(Score score) {
return new TextBuilder.Score(score);
}
/**
* Creates a new {@link TextBuilder.Score} with the formatting and actions
* of the specified {@link Text} and the given score.
*
* @param text The text to apply the properties from
* @param score The score for the text builder
* @return The created text builder
* @see Text.Score
* @see TextBuilder.Score
*/
public static TextBuilder.Score builder(Text text, Score score) {
return new TextBuilder.Score(text, score);
}
/**
* Joins a sequence of text objects together.
*
* @param texts The texts to join
* @return A text object that joins the given text objects
*/
public static Text join(Text... texts) {
return builder().append(texts).build();
}
/**
* Joins a sequence of text objects together.
*
* @param texts The texts to join
* @return A text object that joins the given text objects
*/
public static Text join(Iterable<? extends Text> texts) {
return builder().append(texts).build();
}
/**
* Joins a sequence of text objects together along with a separator.
*
* @param separator The separator
* @param texts The text to join
* @return A text object that joins the given text objects
*/
public static Text join(Text separator, Text... texts) {
switch (texts.length) {
case 0:
return of();
case 1:
return texts[0];
default:
TextBuilder builder = builder();
boolean appendSeparator = false;
for (Text text : texts) {
if (appendSeparator) {
builder.append(separator);
} else {
appendSeparator = true;
}
builder.append(text);
}
return builder.build();
}
}
/**
* Parses the specified JSON text and returns the parsed result.
*
* @param json The valid JSON text
* @return The parsed text
* @throws IllegalArgumentException If the JSON is invalid
*/
public static Text parseJson(String json) throws IllegalArgumentException {
return factory.parseJson(json);
}
/**
* Parses the specified JSON text and returns the parsed result.
*
* <p>Unlike {@link #parseJson(String)} this will ignore some formatting
* errors and parse the JSON data more leniently.</p>
*
* @param json The JSON text
* @return The parsed text
* @throws IllegalArgumentException If the JSON couldn't be parsed
*/
public static Text parseJsonLenient(String json) throws IllegalArgumentException {
return factory.parseJsonLenient(json);
}
/**
* Returns a plain text representation of the {@link Text} without any
* formatting.
*
* @param text The text to convert
* @return The text converted to plain text
*/
public static String toPlain(Text text) {
return factory.toPlain(text);
}
/**
* Returns a JSON representation of the {@link Text} as used in commands.
*
* @param text The text to convert
* @return The text converted to JSON
*/
public static String toJson(Text text) {
return factory.toJson(text);
}
/**
* Returns a plain text representation of the {@link Text} without any
* formatting.
*
* @param text The text to convert
* @return The text converted to plain text
*/
public static String toPlain(Text text, Locale locale) {
return factory.toPlain(text, locale);
}
/**
* Returns a JSON representation of the {@link Text} as used in commands.
*
* @param text The text to convert
* @return The text converted to JSON
*/
public static String toJson(Text text, Locale locale) {
return factory.toJson(text, locale);
}
/**
* Returns the default legacy formatting character.
*
* @return The legacy formatting character
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static char getLegacyChar() {
return factory.getLegacyChar();
}
/**
* Creates a Message from a legacy string using the default legacy.
*
* @param text The text to be converted as a String
* @return The converted Message
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static Text.Literal fromLegacy(String text) {
return fromLegacy(text, getLegacyChar());
}
/**
* Creates a Message from a legacy string, given a color character.
*
* @param text The text to be converted as a String
* @param color The color character to be replaced
* @return The converted Message
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static Text.Literal fromLegacy(String text, char color) {
return factory.parseLegacyMessage(text, color);
}
/**
* Removes the legacy formatting character from a legacy string.
*
* @param text The legacy text as a String
* @return The stripped text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static String stripCodes(String text) {
return stripCodes(text, getLegacyChar());
}
/**
* Removes the legacy formatting character from a legacy string.
*
* @param text The legacy text as a String
* @param color The color character to be replaced
* @return The stripped text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String stripCodes(String text, char color) {
return factory.stripLegacyCodes(text, color);
}
/**
* Replaces the given formatting character with the default legacy
* formatting character from a legacy string.
*
* @param text The legacy text as a String
* @param from The color character to be replaced
* @return The replaced text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static String replaceCodes(String text, char from) {
return replaceCodes(text, from, getLegacyChar());
}
/**
* Replaces the given formatting character with another given formatting
* character from a legacy string.
*
* @param text The legacy text as a String
* @param from The color character to be replaced
* @param to The color character to replace with
* @return The replaced text
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String replaceCodes(String text, char from, char to) {
return factory.replaceLegacyCodes(text, from, to);
}
/**
* Returns a representation of the {@link Text} using the legacy color
* codes.
*
* @param text The text to convert
* @return The text converted to the old color codes
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
@SuppressWarnings("deprecation")
public static String toLegacy(Text text) {
return toLegacy(text, getLegacyChar());
}
/**
* Returns a representation of the {@link Text} using the legacy color
* codes.
*
* @param text The text to convert
* @param code The legacy char to use for the message
* @return The text converted to the old color codes
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String toLegacy(Text text, char code) {
return factory.toLegacy(text, code);
}
/**
* Returns a representation of the {@link Text} using the legacy color
* codes.
*
* @param text The text to convert
* @param code The legacy char to use for the message
* @param locale The language to return this representation in
* @return The text converted to the old color codes
* @deprecated Legacy formatting codes are being phased out of Minecraft
*/
@Deprecated
public static String toLegacy(Text text, char code, Locale locale) {
return factory.toLegacy(text, code, locale);
}
}
| mit |
future-architect/uroborosql | src/test/java/jp/co/future/uroborosql/parameter/mapper/BindParameterMapperManagerTest.java | 6049 | package jp.co.future.uroborosql.parameter.mapper;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Timestamp;
import java.text.ParseException;
import java.time.Clock;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.Date;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import jp.co.future.uroborosql.parameter.mapper.legacy.DateToStringParameterMapper;
public class BindParameterMapperManagerTest {
private Clock clock;
@BeforeEach
public void setUp() {
this.clock = Clock.systemDefaultZone();
}
@Test
public void test() throws ParseException {
var parameterMapperManager = new BindParameterMapperManager(this.clock);
assertThat(parameterMapperManager.toJdbc(null, null), is(nullValue()));
assertThat(parameterMapperManager.toJdbc(true, null), is(true));
assertThat(parameterMapperManager.toJdbc((byte) 1, null), is((byte) 1));
assertThat(parameterMapperManager.toJdbc((short) 1, null), is((short) 1));
assertThat(parameterMapperManager.toJdbc(1, null), is(1));
assertThat(parameterMapperManager.toJdbc(1L, null), is(1L));
assertThat(parameterMapperManager.toJdbc(1F, null), is(1F));
assertThat(parameterMapperManager.toJdbc(1D, null), is(1D));
assertThat(parameterMapperManager.toJdbc(BigDecimal.TEN, null), is(BigDecimal.TEN));
assertThat(parameterMapperManager.toJdbc("A", null), is("A"));
assertThat(parameterMapperManager.toJdbc(new byte[] { 1, 2 }, null), is(new byte[] { 1, 2 }));
assertThat(parameterMapperManager.toJdbc(new java.sql.Date(1), null), is(new java.sql.Date(1)));
assertThat(parameterMapperManager.toJdbc(new java.sql.Time(1), null), is(new java.sql.Time(1)));
assertThat(parameterMapperManager.toJdbc(new java.sql.Timestamp(1), null), is(new java.sql.Timestamp(1)));
var array = newProxy(java.sql.Array.class);
assertThat(parameterMapperManager.toJdbc(array, null), is(array));
var ref = newProxy(java.sql.Ref.class);
assertThat(parameterMapperManager.toJdbc(ref, null), is(ref));
var blob = newProxy(java.sql.Blob.class);
assertThat(parameterMapperManager.toJdbc(blob, null), is(blob));
var clob = newProxy(java.sql.Clob.class);
assertThat(parameterMapperManager.toJdbc(clob, null), is(clob));
var sqlxml = newProxy(java.sql.SQLXML.class);
assertThat(parameterMapperManager.toJdbc(sqlxml, null), is(sqlxml));
var struct = newProxy(java.sql.Struct.class);
assertThat(parameterMapperManager.toJdbc(struct, null), is(struct));
var object = new Object();
assertThat(parameterMapperManager.toJdbc(object, null), is(object));
var date = Date.from(LocalDate.parse("2000-01-01").atStartOfDay(ZoneId.systemDefault()).toInstant());
assertThat(parameterMapperManager.toJdbc(date, null), is(new java.sql.Timestamp(date.getTime())));
assertThat(parameterMapperManager.toJdbc(Month.APRIL, null), is(4));
}
@Test
public void testWithCustom() throws ParseException {
var original = new BindParameterMapperManager(this.clock);
original.addMapper(new EmptyStringToNullParameterMapper());
var mapper = new DateToStringParameterMapper();
original.addMapper(mapper);
var parameterMapperManager = new BindParameterMapperManager(original, this.clock);
var date = Date.from(LocalDate.parse("2000-01-01").atStartOfDay(this.clock.getZone()).toInstant());
assertThat(parameterMapperManager.toJdbc(date, null), is("20000101"));
assertThat(parameterMapperManager.canAcceptByStandard(date), is(true));
parameterMapperManager.removeMapper(mapper);
assertThat(parameterMapperManager.toJdbc(date, null), is(instanceOf(Timestamp.class)));
}
@Test
public void testCustom() {
var parameterMapperManager = new BindParameterMapperManager(this.clock);
parameterMapperManager.addMapper(new BindParameterMapper<String>() {
@Override
public Class<String> targetType() {
return String.class;
}
@Override
public Object toJdbc(final String original, final Connection connection,
final BindParameterMapperManager parameterMapperManager) {
return original.toLowerCase();
}
});
assertThat(parameterMapperManager.toJdbc("S", null), is("s"));
assertThat(parameterMapperManager.toJdbc(true, null), is(true));
}
@Test
public void testCustomWithClock() {
var parameterMapperManager = new BindParameterMapperManager(this.clock);
parameterMapperManager.addMapper(new BindParameterMapperWithClock<String>() {
private Clock clock;
@Override
public Class<String> targetType() {
return String.class;
}
@Override
public Object toJdbc(final String original, final Connection connection,
final BindParameterMapperManager parameterMapperManager) {
return original.toLowerCase();
}
@Override
public Clock getClock() {
return this.clock;
}
@Override
public void setClock(final Clock clock) {
this.clock = clock;
}
});
assertThat(parameterMapperManager.toJdbc("S", null), is("s"));
assertThat(parameterMapperManager.toJdbc(true, null), is(true));
}
interface ProxyContainer {
Object getOriginal();
}
@SuppressWarnings("unchecked")
private static <I> I newProxy(final Class<I> interfaceType) {
var o = new Object();
Method getOriginal;
try {
getOriginal = ProxyContainer.class.getMethod("getOriginal");
} catch (NoSuchMethodException | SecurityException e) {
throw new AssertionError(e);
}
var proxyInstance = (I) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] {
interfaceType, ProxyContainer.class }, (proxy, method, args) -> {
if (getOriginal.equals(method)) {
return o;
}
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof ProxyContainer) {
args[i] = ((ProxyContainer) args[i]).getOriginal();
}
}
return method.invoke(o, args);
});
return proxyInstance;
}
}
| mit |
mattwright324/youtube-comment-suite | src/main/java/io/mattw/youtube/commentsuite/util/ClipboardUtil.java | 1872 | package io.mattw.youtube.commentsuite.util;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
public class ClipboardUtil {
private Clipboard systemClipboard;
public ClipboardUtil() {
}
private void initSystemClipboard() {
if (systemClipboard == null) {
systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
}
private void setSystemClipboard(Clipboard clipboard) {
this.systemClipboard = clipboard;
}
public String getClipboard() throws UnsupportedFlavorException, IOException {
return (String) systemClipboard.getData(DataFlavor.stringFlavor);
}
/**
* Sets clipboard to string value.
*
* @param string text to set clipboard as
*/
public void setClipboard(String string) {
initSystemClipboard();
StringSelection selection = new StringSelection(string);
systemClipboard.setContents(selection, selection);
}
/**
* Converts list into a line.separator delimited string and sets to clipboard.
*
* @param list list of objects converted to line separated toString()
*/
public void setClipboard(List<?> list) {
List<String> strList = list.stream().map(Object::toString).collect(Collectors.toList());
setClipboard(strList.stream().collect(Collectors.joining(System.getProperty("line.separator"))));
}
/**
* Coverts object to string value and sets to clipboard.
*
* @param object uses toString() for clipboard
*/
public void setClipboard(Object object) {
setClipboard(object.toString());
}
}
| mit |
sjfloat/cyclops | cyclops-guava/src/main/java/com/aol/cyclops/guava/FromSimpleReact.java | 286 | package com.aol.cyclops.guava;
import com.aol.simple.react.stream.traits.FutureStream;
import com.google.common.collect.FluentIterable;
public class FromSimpleReact {
public static <T> FluentIterable<T> fromSimpleReact(
FutureStream<T> s) {
return FluentIterable.from(s);
}
}
| mit |
ByeongGi/Koata_Java | Jsp1012-13_struts2-04/src/dao/BoardDao2.java | 1753 | package dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import factory.FactoryService;
import vo.Bbs_CommmVo;
import vo.Board2Vo;
public class BoardDao2 {
private static BoardDao2 dao;
public static synchronized BoardDao2 getDao(){
if ( dao == null ) dao = new BoardDao2();
return dao;
}
public void insertDB(Board2Vo vo){
SqlSession ss= FactoryService.getFatory().openSession(true);
ss.insert("board2.in_board",vo);
ss.close();
}
public List<Board2Vo> getList(){
SqlSession ss= FactoryService.getFatory().openSession();
List<Board2Vo> list=ss.selectList("board2.gList");
ss.close();
return list;
}
public Board2Vo view(int no){
SqlSession ss= FactoryService.getFatory().openSession();
Board2Vo vo =ss.selectOne("board2.view_board",no);
ss.close();
return vo;
}
// 댓글에 해당 되는 메소드
public void commin(Bbs_CommmVo vo){
SqlSession ss= FactoryService.getFatory().openSession(true);
ss.insert("board2.bbscomin",vo);
ss.close();
}
public List<Bbs_CommmVo> bbs_view(int no){
SqlSession ss= FactoryService.getFatory().openSession();
List<Bbs_CommmVo> list=ss.selectList("board2.comL",no);
ss.close();
return list;
}
public void replayInsert(Board2Vo vo){
System.out.println("LOG replayInsert 메소드 시작 ");
SqlSession ss= FactoryService.getFatory().openSession();
try {
ss.update("board2.replay_Update",vo);
System.out.println("LOG replayUpdate");
ss.insert("board2.replay_Insert",vo);
System.out.println("LOG replayInsert");
ss.commit();
} catch (Exception e) {
e.printStackTrace();
ss.rollback();
} finally{
ss.close();
System.out.println("LOG replayInsert 메소드 끝 ");
}
}
} | mit |
5devs/web-project-m1 | FretePlanejado/src/java/com/freteplanejado/entity/Frete.java | 2066 | /*
* 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.freteplanejado.entity;
/**
*
* @author 43596980895
*/
public class Frete {
private int id;
private String origem;
private String destino;
private float altura;
private float largura;
private float profundidade;
private float peso;
private String observacoes;
public Frete() {
}
public Frete(String origem, String destino, float altura, float largura, float profundidade, float peso, String observacoes) {
this.origem = origem;
this.destino = destino;
this.altura = altura;
this.largura = largura;
this.profundidade = profundidade;
this.peso = peso;
this.observacoes = observacoes;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrigem() {
return origem;
}
public void setOrigem(String origem) {
this.origem = origem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public float getAltura() {
return altura;
}
public void setAltura(float altura) {
this.altura = altura;
}
public float getLargura() {
return largura;
}
public void setLargura(float largura) {
this.largura = largura;
}
public float getProfundidade() {
return profundidade;
}
public void setProfundidade(float profundidade) {
this.profundidade = profundidade;
}
public float getPeso() {
return peso;
}
public void setPeso(float peso) {
this.peso = peso;
}
public String getObservacoes() {
return observacoes;
}
public void setObservacoes(String observacoes) {
this.observacoes = observacoes;
}
}
| mit |
dashorst/project-euler | src/test/java/com/martijndashorst/euler/Euler12.java | 1853 | package com.martijndashorst.euler;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
* The sequence of triangle numbers is generated by adding the natural numbers.
* So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first
* ten terms would be:
*
* 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
*
* Let us list the factors of the first seven triangle numbers:
*
* <pre>
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
* </pre>
*
* We can see that 28 is the first triangle number to have over five divisors.
*
* What is the value of the first triangle number to have over five hundred
* divisors?
*/
public class Euler12 {
@Test
public void example() {
assertThat(firstTriangleNumberWithOverNDivisors(5), is(28L));
}
@Test
public void solution() {
assertThat(firstTriangleNumberWithOverNDivisors(500), is(76_576_500L));
}
private long firstTriangleNumberWithOverNDivisors(int n) {
int divisors = 0;
int counter = 1;
long triangle = 0;
do {
triangle = (counter * (counter + 1)) / 2;
divisors = numberOfDivisors(triangle);
counter++;
} while (divisors < n);
return triangle;
}
@Test
public void nrOfDivisors1() {
assertThat(numberOfDivisors(1), is(1));
assertThat(numberOfDivisors(2), is(2));
assertThat(numberOfDivisors(3), is(2));
assertThat(numberOfDivisors(4), is(3));
assertThat(numberOfDivisors(10), is(4));
assertThat(numberOfDivisors(28), is(6));
}
private int numberOfDivisors(long n) {
if (n == 1)
return 1;
if (n <= 3)
return 2;
long nr = (long) Math.sqrt(n);
int nrOfDivisors = 2;
for (int i = 2; i <= nr; i++) {
if (n % i == 0) {
nrOfDivisors += i == nr ? 1 : 2;
}
}
return nrOfDivisors;
}
}
| mit |
artem-gabbasov/otus_java_2017_04_L1 | L5.1/src/test/java/ru/otus/l51/tests/TestClass.java | 502 | package ru.otus.l51.tests;
/**
* Created by tully.
*/
@SuppressWarnings("unused")
public class TestClass {
private int a = 0;
private String s = "";
public TestClass() {
}
public TestClass(Integer a) {
this.a = a;
}
public TestClass(Integer a, String s) {
this.a = a;
this.s = s;
}
int getA() {
return a;
}
String getS() {
return s;
}
private void setDefault(){
a = 0;
s = "";
}
}
| mit |
rtashev/University-Projects | library/webapplibraryproject/src/main/java/com/project/library/utils/MyDateUtil.java | 667 | package com.project.library.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.springframework.stereotype.Component;
@Component
public class MyDateUtil {
public Date calculateDate(String currentDate, int daysToAdd) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = formatter.parse(currentDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, daysToAdd);
return c.getTime();
}
}
| mit |
calebmeyer/Better-Crafting-Tables | src/main/java/com/calebmeyer/bettercrafting/creativetab/CreativeTabBCT.java | 907 | package com.calebmeyer.bettercrafting.creativetab;
import com.calebmeyer.bettercrafting.constants.Project;
import com.calebmeyer.bettercrafting.initialization.ModItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class CreativeTabBCT {
public static final CreativeTabs BETTER_CRAFTING_TABLES_TAB = new CreativeTabs(Project.MOD_ID) {
/**
* This method returns an item, whose icon is used for this creative tab
*
* @return an item to use for the creative tab's icon
*/
@Override
public Item getTabIconItem() {
return ModItems.craftingPanel;
}
/**
* Gets the label for this creative tab.
*
* @return the label
*/
@Override
public String getTranslatedTabLabel() {
return Project.MOD_NAME;
}
};
}
| mit |
PA165-MushroomHunter/MushroomHunter | service/src/main/java/cz/muni/fi/pa165/mushrooms/service/exceptions/EntityOperationServiceException.java | 563 | package cz.muni.fi.pa165.mushrooms.service.exceptions;
/**
* @author bkompis
*/
public class EntityOperationServiceException extends MushroomHunterServiceDataAccessException {
public <T> EntityOperationServiceException(String what, String operation, T entity, Throwable e) {
super("Could not " + operation + " " + what + " (" + entity + ").", e);
}
public EntityOperationServiceException(String msg) {
super(msg);
}
public EntityOperationServiceException(String msg, Throwable cause) {
super(msg, cause);
}
}
| mit |
ktg/openFood | src/main/java/uk/ac/nott/mrl/gles/program/GraphProgram.java | 5077 | /*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.nott.mrl.gles.program;
import android.opengl.GLES20;
import android.util.Log;
import com.android.grafika.gles.GlUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public class GraphProgram
{
private static final int SIZEOF_FLOAT = 4;
private static final int VERTEX_STRIDE = SIZEOF_FLOAT * 2;
private static final String TAG = GlUtil.TAG;
private static final String VERTEX_SHADER =
"uniform mat4 uMVPMatrix;" +
"attribute vec4 aPosition;" +
"void main() {" +
" gl_Position = uMVPMatrix * aPosition;" +
"}";
private static final String FRAGMENT_SHADER =
"precision mediump float;" +
"uniform vec4 uColor;" +
"void main() {" +
" gl_FragColor = uColor;" +
"}";
private final int MAX_SIZE = 200;
// Handles to the GL program and various components of it.
private int programHandle = -1;
private int colorLocation = -1;
private int matrixLocation = -1;
private int positionLocation = -1;
private final float[] colour = {1f, 1f, 1f, 1f};
private final FloatBuffer points;
private final float[] values = new float[MAX_SIZE];
private int size = 0;
private int offset = 0;
private boolean bufferValid = false;
private float min = Float.MAX_VALUE;
private float max = Float.MIN_VALUE;
private static final float left = 1.8f;
private static final float right = 0.2f;
private static final float top = 0.8f;
private static final float bottom = -0.8f;
/**
* Prepares the program in the current EGL context.
*/
public GraphProgram()
{
programHandle = GlUtil.createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
if (programHandle == 0)
{
throw new RuntimeException("Unable to create program");
}
Log.d(TAG, "Created program " + programHandle);
// get locations of attributes and uniforms
ByteBuffer bb = ByteBuffer.allocateDirect(MAX_SIZE * VERTEX_STRIDE);
bb.order(ByteOrder.nativeOrder());
points = bb.asFloatBuffer();
positionLocation = GLES20.glGetAttribLocation(programHandle, "aPosition");
GlUtil.checkLocation(positionLocation, "aPosition");
matrixLocation = GLES20.glGetUniformLocation(programHandle, "uMVPMatrix");
GlUtil.checkLocation(matrixLocation, "uMVPMatrix");
colorLocation = GLES20.glGetUniformLocation(programHandle, "uColor");
GlUtil.checkLocation(colorLocation, "uColor");
}
/**
* Releases the program.
*/
public void release()
{
GLES20.glDeleteProgram(programHandle);
programHandle = -1;
}
public synchronized void add(float value)
{
values[offset] = value;
min = Math.min(value, min);
max = Math.max(value, max);
size = Math.min(size + 1, MAX_SIZE);
offset = (offset + 1) % MAX_SIZE;
bufferValid = false;
}
public void setColour(final float r, final float g, final float b)
{
colour[0] = r;
colour[1] = g;
colour[2] = b;
}
private synchronized FloatBuffer getValidBuffer()
{
if (!bufferValid)
{
points.position(0);
for(int index = 0; index < size; index++)
{
float value = values[(offset + index) % size];
float scaledValue = ((value - min) / (max - min) * (top - bottom)) + bottom;
//Log.i(TAG, "x=" + ((index * (right - left) / size) + left) + ", y=" + scaledValue);
points.put((index * (right - left) / (size - 1)) + left);
points.put(scaledValue);
}
points.position(0);
bufferValid = true;
}
return points;
}
public void draw(float[] matrix)
{
GlUtil.checkGlError("draw start");
// Select the program.
GLES20.glUseProgram(programHandle);
GlUtil.checkGlError("glUseProgram");
// Copy the model / view / projection matrix over.
GLES20.glUniformMatrix4fv(matrixLocation, 1, false, matrix, 0);
GlUtil.checkGlError("glUniformMatrix4fv");
// Copy the color vector in.
GLES20.glUniform4fv(colorLocation, 1, colour, 0);
GlUtil.checkGlError("glUniform4fv ");
// Enable the "aPosition" vertex attribute.
GLES20.glEnableVertexAttribArray(positionLocation);
GlUtil.checkGlError("glEnableVertexAttribArray");
// Connect vertexBuffer to "aPosition".
GLES20.glVertexAttribPointer(positionLocation, 2,
GLES20.GL_FLOAT, false, VERTEX_STRIDE, getValidBuffer());
GlUtil.checkGlError("glVertexAttribPointer");
// Draw the rect.
GLES20.glDrawArrays(GLES20.GL_LINE_STRIP, 0, size);
GlUtil.checkGlError("glDrawArrays");
// Done -- disable vertex array and program.
GLES20.glDisableVertexAttribArray(positionLocation);
GLES20.glUseProgram(0);
}
}
| mit |
tsdl2013/SimpleFlatMapper | sfm/src/main/java/org/sfm/tuples/Tuple20.java | 3155 | package org.sfm.tuples;
public class Tuple20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> extends Tuple19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> {
private final T20 element19;
public Tuple20(T1 element0, T2 element1, T3 element2, T4 element3, T5 element4, T6 element5, T7 element6, T8 element7, T9 element8, T10 element9, T11 element10, T12 element11, T13 element12, T14 element13, T15 element14, T16 element15, T17 element16, T18 element17, T19 element18, T20 element19) {
super(element0, element1, element2, element3, element4, element5, element6, element7, element8, element9, element10, element11, element12, element13, element14, element15, element16, element17, element18);
this.element19 = element19;
}
public final T20 getElement19() {
return element19;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Tuple20 tuple20 = (Tuple20) o;
if (element19 != null ? !element19.equals(tuple20.element19) : tuple20.element19 != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (element19 != null ? element19.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Tuple20{" +
"element0=" + getElement0() +
", element1=" + getElement1() +
", element2=" + getElement2() +
", element3=" + getElement3() +
", element4=" + getElement4() +
", element5=" + getElement5() +
", element6=" + getElement6() +
", element7=" + getElement7() +
", element8=" + getElement8() +
", element9=" + getElement9() +
", element10=" + getElement10() +
", element11=" + getElement11() +
", element12=" + getElement12() +
", element13=" + getElement13() +
", element14=" + getElement14() +
", element15=" + getElement15() +
", element16=" + getElement16() +
", element17=" + getElement17() +
", element18=" + getElement18() +
", element19=" + getElement19() +
'}';
}
public <T21> Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> tuple21(T21 element20) {
return new Tuple21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(getElement0(), getElement1(), getElement2(), getElement3(), getElement4(), getElement5(), getElement6(), getElement7(), getElement8(), getElement9(), getElement10(), getElement11(), getElement12(), getElement13(), getElement14(), getElement15(), getElement16(), getElement17(), getElement18(), getElement19(), element20);
}
}
| mit |
MylesIsCool/ViaVersion | common/src/main/java/com/viaversion/viaversion/protocols/protocol1_12_2to1_12_1/Protocol1_12_2To1_12_1.java | 2084 | /*
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2016-2021 ViaVersion and contributors
*
* 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.viaversion.viaversion.protocols.protocol1_12_2to1_12_1;
import com.viaversion.viaversion.api.protocol.AbstractProtocol;
import com.viaversion.viaversion.api.protocol.remapper.PacketRemapper;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ClientboundPackets1_12_1;
import com.viaversion.viaversion.protocols.protocol1_12_1to1_12.ServerboundPackets1_12_1;
public class Protocol1_12_2To1_12_1 extends AbstractProtocol<ClientboundPackets1_12_1, ClientboundPackets1_12_1, ServerboundPackets1_12_1, ServerboundPackets1_12_1> {
public Protocol1_12_2To1_12_1() {
super(ClientboundPackets1_12_1.class, ClientboundPackets1_12_1.class, ServerboundPackets1_12_1.class, ServerboundPackets1_12_1.class);
}
@Override
protected void registerPackets() {
registerClientbound(ClientboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT, Type.LONG);
}
});
registerServerbound(ServerboundPackets1_12_1.KEEP_ALIVE, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.LONG, Type.VAR_INT);
}
});
}
}
| mit |
lionelcollidor/dta-formation | apps/pizzeria-console-objet/pizzeria-dao/src/main/java/fr/pizzeria/exception/StockageException.java | 353 | package fr.pizzeria.exception;
public class StockageException extends Exception {
public StockageException() {
super();
}
public StockageException(String message, Throwable cause) {
super(message, cause);
}
public StockageException(String message) {
super(message);
}
public StockageException(Throwable cause) {
super(cause);
}
}
| mit |
Vexatos/ForecastersBackpacks | src/main/java/vexatos/backpacks/backpack/package-info.java | 225 | /**
* @author Vexatos
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package vexatos.backpacks.backpack;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
| mit |
McJty/DeepResonance | src/main/java/mcjty/deepresonance/jei/smelter/SmelterRecipeHandler.java | 834 | package mcjty.deepresonance.jei.smelter;
import mezz.jei.api.recipe.IRecipeWrapper;
import javax.annotation.Nonnull;
public class SmelterRecipeHandler implements mezz.jei.api.recipe.IRecipeHandler<SmelterRecipeWrapper> {
private final String id;
public SmelterRecipeHandler() {
this.id = SmelterRecipeCategory.ID;
}
@Nonnull
@Override
public Class<SmelterRecipeWrapper> getRecipeClass() {
return SmelterRecipeWrapper.class;
}
@Nonnull
@Override
public IRecipeWrapper getRecipeWrapper(@Nonnull SmelterRecipeWrapper recipe) {
return recipe;
}
@Override
public String getRecipeCategoryUid(SmelterRecipeWrapper recipe) {
return id;
}
@Override
public boolean isRecipeValid(SmelterRecipeWrapper recipe) {
return true;
}
}
| mit |
stephenlienharrell/WeatherPipe | WeatherPipe/src/main/java/edu/purdue/eaps/weatherpipe/AWSInterface.java | 19505 | package edu.purdue.eaps.weatherpipe;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.lang.System;
import java.lang.Runtime;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.PropertyConfigurator;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduce;
import com.amazonaws.services.elasticmapreduce.AmazonElasticMapReduceClient;
import com.amazonaws.services.elasticmapreduce.model.Cluster;
import com.amazonaws.services.elasticmapreduce.model.DescribeClusterRequest;
import com.amazonaws.services.elasticmapreduce.model.DescribeClusterResult;
import com.amazonaws.services.elasticmapreduce.model.HadoopJarStepConfig;
import com.amazonaws.services.elasticmapreduce.model.JobFlowInstancesConfig;
import com.amazonaws.services.elasticmapreduce.model.RunJobFlowRequest;
import com.amazonaws.services.elasticmapreduce.model.RunJobFlowResult;
import com.amazonaws.services.elasticmapreduce.model.StepConfig;
import com.amazonaws.services.elasticmapreduce.model.TerminateJobFlowsRequest;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.HeadBucketRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.Download;
import com.amazonaws.services.s3.transfer.MultipleFileDownload;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
public class AWSInterface extends MapReduceInterface {
private String jobBucketNamePrefix = "weatherpipe";
private AmazonElasticMapReduce emrClient;
private AmazonS3 s3client;
private TransferManager transMan;
private Region region;
private String jobSetupDirName;
private String jobLogDirName;
//private String defaultInstance = "c3.xlarge";
private String jobBucketName;
private String jobID;
private int bytesTransfered = 0;
public AWSInterface(String job, String bucket){
String weatherPipeBinaryPath = WeatherPipe.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String log4jConfPath = weatherPipeBinaryPath.substring(0, weatherPipeBinaryPath.lastIndexOf("/")) + "/log4j.properties";
PropertyConfigurator.configure(log4jConfPath);
jobBucketName = bucket;
AwsBootstrap(job);
}
private void AwsBootstrap(String job) {
AWSCredentials credentials;
ClientConfiguration conf;
String userID;
MessageDigest md = null;
byte[] shaHash;
StringBuffer hexSha;
DateFormat df;
TimeZone tz;
String isoDate;
File jobDir;
File jobSetupDir;
File jobLogDir;
int i;
conf = new ClientConfiguration();
// 2 minute timeout
conf.setConnectionTimeout(120000);
credentials = new ProfileCredentialsProvider("default").getCredentials();
// TODO: add better credential searching later
region = Region.getRegion(Regions.US_EAST_1);
s3client = new AmazonS3Client(credentials, conf);
s3client.setRegion(region);
transMan = new TransferManager(s3client);
emrClient = new AmazonElasticMapReduceClient(credentials, conf);
emrClient.setRegion(region);
if(jobBucketName == null) {
userID = new AmazonIdentityManagementClient(credentials).getUser().getUser().getUserId();
try {
md = MessageDigest.getInstance("SHA-256");
md.update(userID.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shaHash = md.digest();
hexSha = new StringBuffer();
for(byte b : shaHash) {
hexSha.append(String.format("%02X", b));
}
jobBucketName = jobBucketNamePrefix + "." + hexSha;
if(jobBucketName.length() > 63) {
jobBucketName = jobBucketName.substring(0,62);
}
}
jobBucketName = jobBucketName.toLowerCase();
if(job == null) {
tz = TimeZone.getTimeZone("UTC");
df = new SimpleDateFormat("yyyy-MM-dd'T'HH.mm");
df.setTimeZone(tz);
isoDate = df.format(new Date());
jobID = isoDate + "." + Calendar.getInstance().get(Calendar.MILLISECOND);
// UUID Code if date isn't good
// jobID = UUID.randomUUID().toString();
} else {
jobID = job;
}
jobDirName = "WeatherPipeJob" + jobID;
jobDir = new File(jobDirName);
i = 0;
while(jobDir.exists()) {
i++;
jobDirName = jobDirName + "-" + i;
jobDir = new File(jobDirName);
}
jobDir.mkdir();
jobSetupDirName = jobDirName + "/" + "job_setup";
jobSetupDir = new File(jobSetupDirName);
jobSetupDir.mkdir();
jobLogDirName = jobDirName + "/" + "logs";
jobLogDir = new File(jobLogDirName);
jobLogDir.mkdir();
}
private void UploadFileToS3(String jobBucketName, String key, File file) {
Upload upload;
PutObjectRequest request;
request = new PutObjectRequest(
jobBucketName, key, file);
bytesTransfered = 0;
// Subscribe to the event and provide event handler.
request.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
bytesTransfered += progressEvent.getBytesTransferred();
}
});
System.out.println();
upload = transMan.upload(request);
while(!upload.isDone()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
continue;
}
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + file.length()/1024 + "K");
}
// If we got an error the count could be off
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K");
System.out.println();
System.out.println("Transfer Complete");
}
public String FindOrCreateWeatherPipeJobDirectory() {
String bucketLocation = null;
try {
if(!(s3client.doesBucketExist(jobBucketName))) {
// Note that CreateBucketRequest does not specify region. So bucket is
// created in the region specified in the client.
s3client.createBucket(new CreateBucketRequest(
jobBucketName));
} else {
s3client.headBucket(new HeadBucketRequest(jobBucketName));
}
bucketLocation = "s3n://" + jobBucketName + "/";
} catch (AmazonServiceException ase) {
if(ase.getStatusCode() == 403) {
System.out.println("You do not have propper permissions to access " + jobBucketName +
". S3 uses a global name space, please make sure you are using a unique bucket name.");
System.exit(1);
} else {
System.out.println("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response" +
" for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
}
System.exit(1);
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
System.exit(1);
}
return bucketLocation;
}
public String UploadInputFileList(ArrayList<String> fileList, String dataDirName) {
String key = jobID + "_input";
String uploadFileString = "";
PrintWriter inputFile = null;
File file = new File(jobSetupDirName + "/" + key);
for (String s : fileList) uploadFileString += dataDirName + " " + s + "\n";
try {
inputFile = new PrintWriter(file);
inputFile.print(uploadFileString);
inputFile.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
UploadFileToS3(jobBucketName, key, file);
return "s3n://" + jobBucketName + "/" + key;
}
public String UploadMPJarFile(String fileLocation) {
String key = jobID + "WeatherPipeMapreduce.jar";
File jarFile = new File(fileLocation);
UploadFileToS3(jobBucketName, key, jarFile);
try {
FileUtils.copyFile(new File(fileLocation), new File(jobSetupDirName + "/" + key));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
return "s3n://" + jobBucketName + "/" + key;
}
public void CreateMRJob(String jobInputLocation, String jobJarLocation, int numInstances, String instanceType) {
// Modified from https://mpouttuclarke.wordpress.com/2011/06/24/how-to-run-an-elastic-mapreduce-job-using-the-java-sdk/
// first run aws emr create-default-roles
String hadoopVersion = "2.4.0";
String flowName = "WeatherPipe_" + jobID;
String logS3Location = "s3n://" + jobBucketName + "/" + jobID + ".log";
String outS3Location = "s3n://" + jobBucketName + "/" + jobID + "_output";
String[] arguments = new String[] {jobInputLocation, outS3Location};
List<String> jobArguments = Arrays.asList(arguments);
DescribeClusterRequest describeClusterRequest = new DescribeClusterRequest();
DescribeClusterResult describeClusterResult;
File rawOutputFile = new File(jobDirName + "/" + jobID + "_raw_map_reduce_output");
File localLogDir = new File(jobLogDirName);
int normalized_hours;
double cost;
long startTimeOfProgram, endTimeOfProgram, elapsedTime;
final String resultId;
String line, lastStateMsg;
StringBuilder jobOutputBuild;
int i;
Download download;
int fileLength;
BufferedReader lineRead;
MultipleFileDownload logDirDownload;
startTimeOfProgram = System.currentTimeMillis();
if(instanceType == null) {
instanceType = "c3.xlarge";
System.out.println("Instance type is set to default: " + instanceType);
System.out.println();
}
try {
// Configure instances to use
JobFlowInstancesConfig instances = new JobFlowInstancesConfig();
System.out.println("Using EMR Hadoop v" + hadoopVersion);
instances.setHadoopVersion(hadoopVersion);
System.out.println("Using instance count: " + numInstances);
instances.setInstanceCount(numInstances);
System.out.println("Using master instance type: " + instanceType);
instances.setMasterInstanceType("c3.xlarge");
// do these need to be different??
System.out.println("Using slave instance type: " + instanceType);
instances.setSlaveInstanceType(instanceType);
// Configure the job flow
System.out.println("Configuring flow: " + flowName);
RunJobFlowRequest request = new RunJobFlowRequest(flowName, instances);
System.out.println("\tusing log URI: " + logS3Location);
request.setLogUri(logS3Location);
request.setServiceRole("EMR_DefaultRole");
request.setAmiVersion("3.1.0");
// this may change for some people
request.setJobFlowRole("EMR_EC2_DefaultRole");
System.out.println("\tusing jar URI: " + jobJarLocation);
HadoopJarStepConfig jarConfig = new HadoopJarStepConfig(jobJarLocation);
System.out.println("\tusing args: " + jobArguments);
jarConfig.setArgs(jobArguments);
StepConfig stepConfig =
new StepConfig(jobJarLocation.substring(jobJarLocation.indexOf('/') + 1),
jarConfig);
request.setSteps(Arrays.asList(new StepConfig[] { stepConfig }));
System.out.println("Configured hadoop jar succesfully!\n");
//Run the job flow
RunJobFlowResult result = emrClient.runJobFlow(request);
System.out.println("Trying to run job flow!\n");
describeClusterRequest.setClusterId(result.getJobFlowId());
resultId = result.getJobFlowId();
//Check the status of the running job
String lastState = "";
Runtime.getRuntime().addShutdownHook(new Thread() {public void run()
{ List<String> jobIds = new ArrayList<String>();
jobIds.add(resultId);
TerminateJobFlowsRequest tjfr = new TerminateJobFlowsRequest(jobIds);
emrClient.terminateJobFlows(tjfr);
System.out.println();
System.out.println("Amazon EMR job shutdown");
}});
while (true)
{
describeClusterResult = emrClient.describeCluster(describeClusterRequest);
Cluster cluster = describeClusterResult.getCluster();
lastState = cluster.getStatus().getState();
lastStateMsg = "\rCurrent State of Cluster: " + lastState;
System.out.print(lastStateMsg + " ");
if(!lastState.startsWith("TERMINATED")) {
lastStateMsg = lastStateMsg + " ";
for(i = 0; i < 10; i++) {
lastStateMsg = lastStateMsg + ".";
System.out.print(lastStateMsg);
Thread.sleep(1000);
}
continue;
} else {
lastStateMsg = lastStateMsg + " ";
System.out.print(lastStateMsg);
}
// it reaches here when the emr has "terminated"
normalized_hours = cluster.getNormalizedInstanceHours();
cost = normalized_hours * 0.011;
endTimeOfProgram = System.currentTimeMillis(); // returns milliseconds
elapsedTime = (endTimeOfProgram - startTimeOfProgram)/(1000);
logDirDownload = transMan.downloadDirectory(jobBucketName, jobID + ".log", localLogDir);
while(!logDirDownload.isDone()) {
Thread.sleep(1000);
}
System.out.println();
if(!lastState.endsWith("ERRORS")) {
bytesTransfered = 0;
fileLength = (int)s3client.getObjectMetadata(jobBucketName, jobID + "_output" + "/part-r-00000").getContentLength();
GetObjectRequest fileRequest = new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000");
fileRequest.setGeneralProgressListener(new ProgressListener() {
@Override
public void progressChanged(ProgressEvent progressEvent) {
bytesTransfered += progressEvent.getBytesTransferred();
}
});
download = transMan.download(new GetObjectRequest(jobBucketName, jobID + "_output" + "/part-r-00000"), rawOutputFile);
System.out.println("Downloading Output");
while(!download.isDone()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
continue;
}
// System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + fileLength/1024 + "K ");
}
/* Printing this stuff isn't working
// If we got an error the count could be off
System.out.print("\rTransfered: " + bytesTransfered/1024 + "K / " + bytesTransfered/1024 + "K ");
System.out.println();
*/
System.out.println("Transfer Complete");
System.out.println("The job has ended and output has been downloaded to " + jobDirName);
System.out.printf("Normalized instance hours: %d\n", normalized_hours);
System.out.printf("Approximate cost of this run: $%2.02f\n", cost);
System.out.println("The job took " + elapsedTime + " seconds to finish" );
lineRead = new BufferedReader(new FileReader(rawOutputFile));
jobOutputBuild = new StringBuilder("");
while((line = lineRead.readLine()) != null) {
if(line.startsWith("Run#")) {
jobOutputBuild = new StringBuilder("");
jobOutputBuild.append(line.split("\t")[1]);
} else {
jobOutputBuild.append("\n");
jobOutputBuild.append(line);
}
}
jobOutput = jobOutputBuild.toString();
break;
}
jobOutput = "FAILED";
System.out.println("The job has ended with errors, please check the log in " + localLogDir);
System.out.printf("Normalized instance hours: %d\n", normalized_hours);
System.out.printf("Approximate cost of this run = $%2.02f\n", cost);
System.out.println("The job took " + elapsedTime + " seconds to finish" );
break;
}
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addJobBucketName (String jobBucketName){
this.jobBucketName = jobBucketName;
}
protected void close() {
transMan.shutdownNow();
}
}
| mit |
marcossilva/IFAdventure | EnsaioRetentivo/src/framework/org/json/JSONArray.java | 32203 | package framework.org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a
* string wrapped in square brackets with commas separating the values. The
* internal form is an object having <code>get</code> and <code>opt</code>
* methods for accessing the values by index, and <code>put</code> methods for
* adding or replacing values. The values can be any of these types:
* <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
* <code>Number</code>, <code>String</code>, or the
* <code>JSONObject.NULL object</code>.
* <p>
* The constructor can convert a JSON text into a Java object. The
* <code>toString</code> method converts to JSON text.
* <p>
* A <code>get</code> method returns a value if one can be found, and throws an
* exception if one cannot be found. An <code>opt</code> method returns a
* default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an
* object which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you.
* <p>
* The texts produced by the <code>toString</code> methods strictly conform to
* JSON syntax rules. The constructors are more forgiving in the texts they will
* accept:
* <ul>
* <li>An extra <code>,</code> <small>(comma)</small> may appear just
* before the closing bracket.</li>
* <li>The <code>null</code> value will be inserted when there is <code>,</code>
* <small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code> <small>(single
* quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a quote
* or single quote, and if they do not contain leading or trailing spaces, and
* if they do not contain any of these characters:
* <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and
* if they are not the reserved words <code>true</code>, <code>false</code>, or
* <code>null</code>.</li>
* </ul>
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONArray {
/**
* The arrayList where the JSONArray's properties are kept.
*/
private final ArrayList<Object> myArrayList;
/**
* Construct an empty JSONArray.
*/
public JSONArray() {
this.myArrayList = new ArrayList<Object>();
}
/**
* Construct a JSONArray from a JSONTokener.
*
* @param x
* A JSONTokener
* @throws JSONException
* If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
this();
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
if (x.nextClean() != ']') {
x.back();
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ',':
if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
}
}
}
}
/**
* Construct a JSONArray from a source JSON text.
*
* @param source
* A string that begins with <code>[</code> <small>(left
* bracket)</small> and ends with <code>]</code>
* <small>(right bracket)</small>.
* @throws JSONException
* If there is a syntax error.
*/
public JSONArray(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONArray from a Collection.
*
* @param collection
* A Collection.
*/
public JSONArray(Collection<Object> collection) {
this.myArrayList = new ArrayList<Object>();
if (collection != null) {
Iterator<Object> iter = collection.iterator();
while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next()));
}
}
}
/**
* Construct a JSONArray from an array
*
* @throws JSONException
* If not an array.
*/
public JSONArray(Object array) throws JSONException {
this();
if (array.getClass().isArray()) {
int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i)));
}
} else {
throw new JSONException(
"JSONArray initial value should be a string or collection or array.");
}
}
/**
* Get the object value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return An object value.
* @throws JSONException
* If there is no value for the index.
*/
public Object get(int index) throws JSONException {
Object object = this.opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
}
/**
* Get the boolean value associated with an index. The string values "true"
* and "false" are converted to boolean.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The truth.
* @throws JSONException
* If there is no value for the index or if the value is not
* convertible to boolean.
*/
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
/**
* Get the double value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value cannot be converted
* to a number.
*/
public double getDouble(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the int value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value is not a number.
*/
public int getInt(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the JSONArray associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A JSONArray value.
* @throws JSONException
* If there is no value for the index. or if the value is not a
* JSONArray
*/
public JSONArray getJSONArray(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
}
/**
* Get the JSONObject associated with an index.
*
* @param index
* subscript
* @return A JSONObject value.
* @throws JSONException
* If there is no value for the index or if the value is not a
* JSONObject
*/
public JSONObject getJSONObject(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
}
/**
* Get the long value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException
* If the key is not found or if the value cannot be converted
* to a number.
*/
public long getLong(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
/**
* Get the string associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A string value.
* @throws JSONException
* If there is no string value for the index.
*/
public String getString(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof String) {
return (String) object;
}
throw new JSONException("JSONArray[" + index + "] not a string.");
}
/**
* Determine if the value is null.
*
* @param index
* The index must be between 0 and length() - 1.
* @return true if the value at the index is null, or if there is no value.
*/
public boolean isNull(int index) {
return JSONObject.NULL.equals(this.opt(index));
}
/**
* Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element. Warning:
* This method assumes that the data structure is acyclical.
*
* @param separator
* A string that will be inserted between the elements.
* @return a string.
* @throws JSONException
* If the array contains an invalid number.
*/
public String join(String separator) throws JSONException {
int len = this.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
public int length() {
return this.myArrayList.size();
}
/**
* Get the optional object value associated with an index.
*
* @param index
* The index must be between 0 and length() - 1.
* @return An object value, or null if there is no object at that index.
*/
public Object opt(int index) {
return (index < 0 || index >= this.length()) ? null : this.myArrayList
.get(index);
}
/**
* Get the optional boolean value associated with an index. It returns false
* if there is no value at that index, or if the value is not Boolean.TRUE
* or the String "true".
*
* @param index
* The index must be between 0 and length() - 1.
* @return The truth.
*/
public boolean optBoolean(int index) {
return this.optBoolean(index, false);
}
/**
* Get the optional boolean value associated with an index. It returns the
* defaultValue if there is no value at that index or if it is not a Boolean
* or the String "true" or "false" (case insensitive).
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* A boolean default.
* @return The truth.
*/
public boolean optBoolean(int index, boolean defaultValue) {
try {
return this.getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional double value associated with an index. NaN is returned
* if there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public double optDouble(int index) {
return this.optDouble(index, Double.NaN);
}
/**
* Get the optional double value associated with an index. The defaultValue
* is returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* subscript
* @param defaultValue
* The default value.
* @return The value.
*/
public double optDouble(int index, double defaultValue) {
try {
return this.getDouble(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional int value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public int optInt(int index) {
return this.optInt(index, 0);
}
/**
* Get the optional int value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return The value.
*/
public int optInt(int index, int defaultValue) {
try {
return this.getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional JSONArray associated with an index.
*
* @param index
* subscript
* @return A JSONArray value, or null if the index has no value, or if the
* value is not a JSONArray.
*/
public JSONArray optJSONArray(int index) {
Object o = this.opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
}
/**
* Get the optional JSONObject associated with an index. Null is returned if
* the key is not found, or null if the index has no value, or if the value
* is not a JSONObject.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A JSONObject value.
*/
public JSONObject optJSONObject(int index) {
Object o = this.opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
}
/**
* Get the optional long value associated with an index. Zero is returned if
* there is no value for the index, or if the value is not a number and
* cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @return The value.
*/
public long optLong(int index) {
return this.optLong(index, 0);
}
/**
* Get the optional long value associated with an index. The defaultValue is
* returned if there is no value for the index, or if the value is not a
* number and cannot be converted to a number.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return The value.
*/
public long optLong(int index, long defaultValue) {
try {
return this.getLong(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value is not a
* string and is not null, then it is coverted to a string.
*
* @param index
* The index must be between 0 and length() - 1.
* @return A String value.
*/
public String optString(int index) {
return this.optString(index, "");
}
/**
* Get the optional string associated with an index. The defaultValue is
* returned if the key is not found.
*
* @param index
* The index must be between 0 and length() - 1.
* @param defaultValue
* The default value.
* @return A String value.
*/
public String optString(int index, String defaultValue) {
Object object = this.opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object
.toString();
}
/**
* Append a boolean value. This increases the array's length by one.
*
* @param value
* A boolean value.
* @return this.
*/
public JSONArray put(boolean value) {
this.put(value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param value
* A Collection value.
* @return this.
*/
public JSONArray put(Collection<Object> value) {
this.put(new JSONArray(value));
return this;
}
/**
* Append a double value. This increases the array's length by one.
*
* @param value
* A double value.
* @throws JSONException
* if the value is not finite.
* @return this.
*/
public JSONArray put(double value) throws JSONException {
Double d = new Double(value);
JSONObject.testValidity(d);
this.put(d);
return this;
}
/**
* Append an int value. This increases the array's length by one.
*
* @param value
* An int value.
* @return this.
*/
public JSONArray put(int value) {
this.put(new Integer(value));
return this;
}
/**
* Append an long value. This increases the array's length by one.
*
* @param value
* A long value.
* @return this.
*/
public JSONArray put(long value) {
this.put(new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject which
* is produced from a Map.
*
* @param value
* A Map value.
* @return this.
*/
public JSONArray put(Map<String, Object> value) {
this.put(new JSONObject(value));
return this;
}
/**
* Append an object value. This increases the array's length by one.
*
* @param value
* An object value. The value should be a Boolean, Double,
* Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
*/
public JSONArray put(Object value) {
this.myArrayList.add(value);
return this;
}
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index
* The subscript.
* @param value
* A boolean value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, boolean value) throws JSONException {
this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONArray which
* is produced from a Collection.
*
* @param index
* The subscript.
* @param value
* A Collection value.
* @return this.
* @throws JSONException
* If the index is negative or if the value is not finite.
*/
public JSONArray put(int index, Collection<Object> value) throws JSONException {
this.put(index, new JSONArray(value));
return this;
}
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* A double value.
* @return this.
* @throws JSONException
* If the index is negative or if the value is not finite.
*/
public JSONArray put(int index, double value) throws JSONException {
this.put(index, new Double(value));
return this;
}
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* An int value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, int value) throws JSONException {
this.put(index, new Integer(value));
return this;
}
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad it
* out.
*
* @param index
* The subscript.
* @param value
* A long value.
* @return this.
* @throws JSONException
* If the index is negative.
*/
public JSONArray put(int index, long value) throws JSONException {
this.put(index, new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a JSONObject that
* is produced from a Map.
*
* @param index
* The subscript.
* @param value
* The Map value.
* @return this.
* @throws JSONException
* If the index is negative or if the the value is an invalid
* number.
*/
public JSONArray put(int index, Map<String, Object> value) throws JSONException {
this.put(index, new JSONObject(value));
return this;
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
*
* @param index
* The subscript.
* @param value
* The value to put into the array. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or
* String, or the JSONObject.NULL object.
* @return this.
* @throws JSONException
* If the index is negative or if the the value is an invalid
* number.
*/
public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < this.length()) {
this.myArrayList.set(index, value);
} else {
while (index != this.length()) {
this.put(JSONObject.NULL);
}
this.put(value);
}
return this;
}
/**
* Remove an index and close the hole.
*
* @param index
* The index of the element to be removed.
* @return The value that was associated with the index, or null if there
* was no value.
*/
public Object remove(int index) {
return index >= 0 && index < this.length()
? this.myArrayList.remove(index)
: null;
}
/**
* Determine if two JSONArrays are similar.
* They must contain similar sequences.
*
* @param other The other JSONArray
* @return true if they are equal
*/
public boolean similar(Object other) {
if (!(other instanceof JSONArray)) {
return false;
}
int len = this.length();
if (len != ((JSONArray)other).length()) {
return false;
}
for (int i = 0; i < len; i += 1) {
Object valueThis = this.get(i);
Object valueOther = ((JSONArray)other).get(i);
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
} else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
} else if (!valueThis.equals(valueOther)) {
return false;
}
}
return true;
}
/**
* Produce a JSONObject by combining a JSONArray of names with the values of
* this JSONArray.
*
* @param names
* A JSONArray containing a list of key strings. These will be
* paired with the values.
* @return A JSONObject, or null if there are no names or if this JSONArray
* has no values.
* @throws JSONException
* If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || this.length() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
return jo;
}
/**
* Make a JSON text of this JSONArray. For compactness, no unnecessary
* whitespace is added. If it is not possible to produce a syntactically
* correct JSON text then null will be returned instead. This could occur if
* the array contains an invalid number.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, transmittable representation of the
* array.
*/
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method
* assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @return a printable, displayable, transmittable representation of the
* object, beginning with <code>[</code> <small>(left
* bracket)</small> and ending with <code>]</code>
* <small>(right bracket)</small>.
* @throws JSONException
*/
public String toString(int indentFactor) throws JSONException {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString();
}
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
/**
* Write the contents of the JSONArray as JSON text to a writer. For
* compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indention of the top level.
* @return The writer.
* @throws JSONException
*/
Writer write(Writer writer, int indentFactor, int indent)
throws JSONException {
try {
boolean commanate = false;
int length = this.length();
writer.write('[');
if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0),
indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i),
indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
}
| mit |
vundyalaavinash/Algorithms | BasicSorting/SelectionSort.java | 2176 | /**
* Created by avinashvundyala on 09/07/16.
*/
public class SelectionSort {
public int[] iterativeSelectionSort(int[] arr) {
int temp, smallIdx;
for(int i = 0; i < arr.length; i++) {
smallIdx = i;
for(int j = i; j < arr.length; j++) {
if(arr[smallIdx] > arr[j]) {
smallIdx = j;
}
}
temp = arr[i];
arr[i] = arr[smallIdx];
arr[smallIdx] = temp;
}
return arr;
}
public int[] recursiveSelectionSort(int[] arr, int startIdx) {
if(startIdx == arr.length) {
return arr;
}
int temp, smallIdx;
smallIdx = startIdx;
for(int j = startIdx; j < arr.length; j++) {
if(arr[smallIdx] > arr[j]) {
smallIdx = j;
}
}
temp = arr[startIdx];
arr[startIdx] = arr[smallIdx];
arr[smallIdx] = temp;
return recursiveSelectionSort(arr, startIdx + 1);
}
public void printArray(int[] array) {
for(int number: array) {
System.out.print(String.valueOf(number) + " ");
}
}
public static void main(String args[]) {
SelectionSort ss = new SelectionSort();
int[] unsortedArray1 = {6,4,2,1,9,0};
System.out.print("Unsoreted Array Sorting: ");
ss.printArray(ss.iterativeSelectionSort(unsortedArray1));
int[] unsortedArray2 = {1,2,3,4,5,6};
System.out.print("\nAlready Soreted Array Sorting: ");
ss.printArray(ss.iterativeSelectionSort(unsortedArray2));
int[] unsortedArray3 = {6,5,4,3,2,1};
System.out.print("\nUnsoreted Array Sorting: ");
ss.printArray(ss.iterativeSelectionSort(unsortedArray3));
int[] unsortedArray4 = {6,4,2,1,9,0};
System.out.print("\nUnsoreted Array Sorting: ");
ss.printArray(ss.recursiveSelectionSort(unsortedArray4, 0));
int[] unsortedArray5 = {1,2,3,4,5,6};
System.out.print("\nAlready Soreted Array Sorting: ");
ss.printArray(ss.recursiveSelectionSort(unsortedArray5, 0));
int[] unsortedArray6 = {6,5,4,3,2,1};
System.out.print("\nUnsoreted Array Sorting: ");
ss.printArray(ss.recursiveSelectionSort(unsortedArray6, 0));
}
}
| mit |
brunyuriy/adasim | src/adasim/algorithm/routing/QLearningRoutingAlgorithm.java | 9693 | package adasim.algorithm.routing;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Stack;
import org.apache.log4j.Logger;
import org.jdom.Element;
import adasim.model.AdasimMap;
import adasim.model.ConfigurationException;
import adasim.model.RoadSegment;
import adasim.model.TrafficSimulator;
import adasim.model.internal.FilterMap;
import adasim.model.internal.SimulationXMLReader;
import adasim.model.internal.VehicleManager;
public class QLearningRoutingAlgorithm extends AbstractRoutingAlgorithm {
private boolean finished = false;
private final double alpha = 0.1; // Learning rate
private final double gamma = 0.9; // Eagerness - 0 looks in the near future, 1 looks in the distant future
private int statesCount ;
private final int reward = 100;
private final int penalty = -10;
private int[][] R; // Reward lookup
private double[][] Q; // Q learning
private final int lookahead;
private final int recompute;
private int steps;
private List<RoadSegment> path;
RoadSegment currentSource =null;
private final static Logger logger = Logger.getLogger(LookaheadShortestPathRoutingAlgorithm.class);
public QLearningRoutingAlgorithm() {
this(2,2);
}
public QLearningRoutingAlgorithm( int lookahead, int recomp ){
this.lookahead = lookahead;
this.recompute = recomp;
this.steps = 0;
logger.info( "QLearningRoutingAlgorithm(" + lookahead + "," + recompute +")" );
}
/*
* Map Road segment to 2d array for q learninig to work on
*
*
*/
public void mapSegmentToArray(List<RoadSegment> listOfRoadSegment ) {
Collections.sort(listOfRoadSegment); // Make sure we alwasy loading sorted Map
//int dim = listOfRoadSegment.size() +1; // dimention of 2d array
R = new int[statesCount][statesCount];
Q = new double[statesCount][statesCount];
// set all cells with -1 for the impossible transitions
for(int i=0;i<statesCount ;i++) {
for(int j=0;j<statesCount ;j++) {
R[i][j]= -1;
}
}
// set cells with 0 where agent could move
for (RoadSegment roadSegment : listOfRoadSegment) {
for (RoadSegment roadSegmentNeighbors : roadSegment.getNeighbors()) {
R[roadSegment.getID()][roadSegmentNeighbors.getID()]= 0; // forword drive
// R[roadSegmentNeighbors.getID()][roadSegment.getID()]= 0; //backword drive
// set reword for reaching the target
if(roadSegmentNeighbors.getID() == target.getID() ) {
R[roadSegment.getID()][roadSegmentNeighbors.getID()]= reward;
}
// if(roadSegment.getID() == target ) {
// R[roadSegmentNeighbors.getID()][roadSegment.getID()]= reward;
// }
}
}
// set reword for reaching goal
//R[target][target]= reward;
initializeQ();
}
//Set Q values to R values
void initializeQ()
{
for (int i = 0; i < statesCount; i++){
for(int j = 0; j < statesCount; j++){
Q[i][j] = (double)R[i][j];
}
}
}
// Used for debug
void printR() {
System.out.printf("%25s", "States: ");
for (int i = 0; i < statesCount; i++) {
System.out.printf("%4s", i);
}
System.out.println();
for (int i = 0; i < statesCount; i++) {
System.out.print("Possible states from " + i + " :[");
for (int j = 0; j < statesCount; j++) {
System.out.printf("%4s", R[i][j]);
}
System.out.println("]");
}
}
void calculateQ() {
Random rand = new Random();
for (int i = 0; i < 1000; i++) { // Train cycles
// Select random initial state
int crtState = currentSource.getID();// set source base on input rand.nextInt(statesCount);
while (!isFinalState(crtState)) {
int[] actionsFromCurrentState = possibleActionsFromState(crtState);
// Pick a random action from the ones possible
int index = rand.nextInt(actionsFromCurrentState.length);
int nextState = actionsFromCurrentState[index];
// Q(state,action)= Q(state,action) + alpha * (R(state,action) + gamma * Max(next state, all actions) - Q(state,action))
double q = Q[crtState][nextState];
double maxQ = maxQ(nextState);
int r = R[crtState][nextState];
double value = q + alpha * (r + gamma * maxQ - q);
Q[crtState][nextState] = value;
crtState = nextState;
}
}
}
boolean isFinalState(int state) {
return state == target.getID();
}
int[] possibleActionsFromState(int state) {
ArrayList<Integer> result = new ArrayList<>();
for (int i = 0; i < statesCount; i++) {
if (R[state][i] != -1) {
result.add(i);
}
}
return result.stream().mapToInt(i -> i).toArray();
}
double maxQ(int nextState) {
int[] actionsFromState = possibleActionsFromState(nextState);
//the learning rate and eagerness will keep the W value above the lowest reward
double maxValue = -10;
for (int nextAction : actionsFromState) {
double value = Q[nextState][nextAction];
if (value > maxValue)
maxValue = value;
}
return maxValue;
}
void printPolicy() {
System.out.println("\nPrint policy");
for (int i = 0; i < statesCount; i++) {
System.out.println("From state " + i + " goto state " + getPolicyFromState(i));
}
}
int getPolicyFromState(int state) {
int[] actionsFromState = possibleActionsFromState(state);
double maxValue = Double.MIN_VALUE;
int policyGotoState = state;
// Pick to move to the state that has the maximum Q value
for (int nextState : actionsFromState) {
double value = Q[state][nextState];
if (value > maxValue) {
maxValue = value;
policyGotoState = nextState;
}
}
return policyGotoState;
}
void printQ() {
System.out.println("\nQ matrix");
for (int i = 0; i < Q.length; i++) {
System.out.print("From state " + i + ": ");
for (int j = 0; j < Q[i].length; j++) {
System.out.printf("%6.2f ", (Q[i][j]));
}
System.out.println();
}
}
@Override
public List<RoadSegment> getPath(RoadSegment from, RoadSegment to) {
currentSource = from;
// get path
List<RoadSegment> nodes = graph.getRoadSegments();
statesCount = nodes.size();
mapSegmentToArray(nodes); // convert segments to 2d array
calculateQ(); // calculate q-learninig
System.out.println("========================Source: " + currentSource.getID() +", Target: "+ target.getID() + "===============================");
printR();
printQ();
printPolicy();
List<RoadSegment> newListOfNodes = new ArrayList<RoadSegment>( );
// get path using stack
Stack<Integer> st= new Stack<Integer>();
st.add(getPolicyFromState(from.getID()));
while( !st.isEmpty()){
int currentState= st.pop();
newListOfNodes.add(nodes.get(currentState));
if(currentState == to.getID()) {
break;
}
int nextSate = getPolicyFromState(currentState);
st.add(nextSate);
}
System.out.println("\nRoadSegments: ");
for (RoadSegment roadSegment : newListOfNodes) {
System.out.println("\tSegment ID:"+roadSegment.getID());
System.out.println("\t \tNeighbors: "+ roadSegment.getNeighbors());
}
System.out.println("=======================================================");
if ( newListOfNodes == null ) {
finished = true;
}
return newListOfNodes;
}
@Override
public RoadSegment getNextNode() {
if ( finished ) return null;
if ( path == null ) {
path = getPath(source);
logger.info( pathLogMessage() );
}
assert path != null || finished;
if ( path == null || path.size() == 0 ) {
finished = true;
return null;
}
if ( ++steps == recompute ) {
RoadSegment next = path.remove(0);
path = getPath(next);
logger.info( "UPDATE: " + pathLogMessage() );
steps = 0;
return next;
} else {
return path.remove(0);
}
}
/**
* Computes a path to the configured target node starting from
* the passed <code>start</code> node.
* @param start
*/
private List<RoadSegment> getPath(RoadSegment start) {
List<RoadSegment> p = getPath( start, target );
if ( p == null ) {
finished = true;
}
return p;
}
private String pathLogMessage() {
StringBuffer buf = new StringBuffer( "PATH: Vehicle: " );
buf.append( vehicle.getID() );
buf.append( " From: " );
buf.append( source.getID() );
buf.append( " To: " );
buf.append( target.getID() );
buf.append( " Path: " );
buf.append( path == null ? "[]" : path );
return buf.toString();
}
} | mit |
ke00n/alabno | infrastructure/infrastructure/src/main/java/jobmanager/tests/MicroServiceInfoTest.java | 657 | package jobmanager.tests;
import static alabno.testsuite.TestUtils.*;
import alabno.testsuite.TestModule;
import alabno.testsuite.TestStatistics;
import jobmanager.MicroServiceInfo;
public class MicroServiceInfoTest implements TestModule {
@Override
public void run(TestStatistics statistics) {
constructor_test(statistics);
}
private void constructor_test(TestStatistics statistics) {
MicroServiceInfo the_info = new MicroServiceInfo("haskell", "java -jar proj/../haskellanalyzer/Main");
assertEqualsObjects(the_info.getName(), "haskell");
assertEqualsObjects(the_info.getLocation(), "java -jar proj/../haskellanalyzer/Main");
}
}
| mit |
augustomarinho/springboot-docker | src/main/java/com/am/docker/study/controller/RestDockerExample.java | 299 | package com.am.docker.study.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestDockerExample {
@RequestMapping("/")
public String home() {
return "Hello Docker World";
}
} | mit |
elBukkit/MagicPlugin | MagicAPI/src/main/java/com/elmakers/mine/bukkit/api/event/PreCastEvent.java | 1149 | package com.elmakers.mine.bukkit.api.event;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
/**
* A custom event that the Magic plugin will fire any time a
* Mage casts a Spell.
*/
public class PreCastEvent extends Event implements Cancellable {
private boolean cancelled;
private final Mage mage;
private final Spell spell;
private static final HandlerList handlers = new HandlerList();
public PreCastEvent(Mage mage, Spell spell) {
this.mage = mage;
this.spell = spell;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public Mage getMage() {
return mage;
}
public Spell getSpell() {
return spell;
}
}
| mit |
naosim/rtmjava | src/main/java/com/naosim/rtm/lib/MD5.java | 538 | package com.naosim.rtm.lib;
import java.math.BigInteger;
import java.security.MessageDigest;
public class MD5 {
public static String md5(String str) {
try {
byte[] str_bytes = str.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5_bytes = md.digest(str_bytes);
BigInteger big_int = new BigInteger(1, md5_bytes);
return big_int.toString(16);
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
| mit |
TechReborn/RebornCore | src/main/java/reborncore/client/gui/slots/SlotFake.java | 2200 | /*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package reborncore.client.gui.slots;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
public class SlotFake extends BaseSlot {
public boolean mCanInsertItem;
public boolean mCanStackItem;
public int mMaxStacksize = 127;
public SlotFake(Inventory itemHandler, int par2, int par3, int par4, boolean aCanInsertItem,
boolean aCanStackItem, int aMaxStacksize) {
super(itemHandler, par2, par3, par4);
this.mCanInsertItem = aCanInsertItem;
this.mCanStackItem = aCanStackItem;
this.mMaxStacksize = aMaxStacksize;
}
@Override
public boolean canInsert(ItemStack par1ItemStack) {
return this.mCanInsertItem;
}
@Override
public int getMaxStackAmount() {
return this.mMaxStacksize;
}
@Override
public boolean hasStack() {
return false;
}
@Override
public ItemStack takeStack(int par1) {
return !this.mCanStackItem ? ItemStack.EMPTY : super.takeStack(par1);
}
@Override
public boolean canWorldBlockRemove() {
return false;
}
}
| mit |
lobobrowser/Cobra | src/main/java/org/cobraparser/html/renderer/RListItem.java | 6450 | /*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
package org.cobraparser.html.renderer;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import org.cobraparser.html.HtmlRendererContext;
import org.cobraparser.html.domimpl.NodeImpl;
import org.cobraparser.html.style.ListStyle;
import org.cobraparser.html.style.RenderState;
import org.cobraparser.ua.UserAgentContext;
import org.w3c.dom.html.HTMLElement;
class RListItem extends BaseRListElement {
private static final int BULLET_WIDTH = 5;
private static final int BULLET_HEIGHT = 5;
private static final int BULLET_RMARGIN = 5;
private static final int BULLET_SPACE_WIDTH = 36;
public RListItem(final NodeImpl modelNode, final int listNesting, final UserAgentContext pcontext, final HtmlRendererContext rcontext,
final FrameContext frameContext,
final RenderableContainer parentContainer, final RCollection parent) {
super(modelNode, listNesting, pcontext, rcontext, frameContext, parentContainer);
// this.defaultMarginInsets = new java.awt.Insets(0, BULLET_SPACE_WIDTH, 0,
// 0);
}
@Override
public int getViewportListNesting(final int blockNesting) {
return blockNesting + 1;
}
@Override
public void invalidateLayoutLocal() {
super.invalidateLayoutLocal();
this.value = null;
}
private static final Integer UNSET = new Integer(Integer.MIN_VALUE);
private Integer value = null;
private Integer getValue() {
Integer value = this.value;
if (value == null) {
final HTMLElement node = (HTMLElement) this.modelNode;
final String valueText = node == null ? null : node.getAttribute("value");
if (valueText == null) {
value = UNSET;
} else {
try {
value = Integer.valueOf(valueText);
} catch (final NumberFormatException nfe) {
value = UNSET;
}
}
this.value = value;
}
return value;
}
private int count;
@Override
public void doLayout(final int availWidth, final int availHeight, final boolean expandWidth, final boolean expandHeight,
final FloatingBoundsSource floatBoundsSource,
final int defaultOverflowX, final int defaultOverflowY, final boolean sizeOnly) {
super.doLayout(availWidth, availHeight, expandWidth, expandHeight, floatBoundsSource, defaultOverflowX, defaultOverflowY, sizeOnly);
// Note: Count must be calculated even if layout is valid.
final RenderState renderState = this.modelNode.getRenderState();
final Integer value = this.getValue();
if (value == UNSET) {
this.count = renderState.incrementCount(DEFAULT_COUNTER_NAME, this.listNesting);
} else {
final int newCount = value.intValue();
this.count = newCount;
renderState.resetCount(DEFAULT_COUNTER_NAME, this.listNesting, newCount + 1);
}
}
@Override
public void paintShifted(final Graphics g) {
super.paintShifted(g);
final RenderState rs = this.modelNode.getRenderState();
final Insets marginInsets = this.marginInsets;
final RBlockViewport layout = this.bodyLayout;
final ListStyle listStyle = this.listStyle;
int bulletType = listStyle == null ? ListStyle.TYPE_UNSET : listStyle.type;
if (bulletType != ListStyle.TYPE_NONE) {
if (bulletType == ListStyle.TYPE_UNSET) {
RCollection parent = this.getOriginalOrCurrentParent();
if (!(parent instanceof RList)) {
parent = parent.getOriginalOrCurrentParent();
}
if (parent instanceof RList) {
final ListStyle parentListStyle = ((RList) parent).listStyle;
bulletType = parentListStyle == null ? ListStyle.TYPE_DISC : parentListStyle.type;
} else {
bulletType = ListStyle.TYPE_DISC;
}
}
// Paint bullets
final Color prevColor = g.getColor();
g.setColor(rs.getColor());
try {
final Insets insets = this.getInsets(this.hasHScrollBar, this.hasVScrollBar);
final Insets paddingInsets = this.paddingInsets;
final int baselineOffset = layout.getFirstBaselineOffset();
final int bulletRight = (marginInsets == null ? 0 : marginInsets.left) - BULLET_RMARGIN;
final int bulletBottom = insets.top + baselineOffset + (paddingInsets == null ? 0 : paddingInsets.top);
final int bulletTop = bulletBottom - BULLET_HEIGHT;
final int bulletLeft = bulletRight - BULLET_WIDTH;
final int bulletNumber = this.count;
String numberText = null;
switch (bulletType) {
case ListStyle.TYPE_DECIMAL:
numberText = bulletNumber + ".";
break;
case ListStyle.TYPE_LOWER_ALPHA:
numberText = ((char) ('a' + bulletNumber)) + ".";
break;
case ListStyle.TYPE_UPPER_ALPHA:
numberText = ((char) ('A' + bulletNumber)) + ".";
break;
case ListStyle.TYPE_DISC:
g.fillOval(bulletLeft, bulletTop, BULLET_WIDTH, BULLET_HEIGHT);
break;
case ListStyle.TYPE_CIRCLE:
g.drawOval(bulletLeft, bulletTop, BULLET_WIDTH, BULLET_HEIGHT);
break;
case ListStyle.TYPE_SQUARE:
g.fillRect(bulletLeft, bulletTop, BULLET_WIDTH, BULLET_HEIGHT);
break;
}
if (numberText != null) {
final FontMetrics fm = g.getFontMetrics();
final int numberLeft = bulletRight - fm.stringWidth(numberText);
final int numberY = bulletBottom;
g.drawString(numberText, numberLeft, numberY);
}
} finally {
g.setColor(prevColor);
}
}
}
}
| mit |
vadadler/java | planmart/src/com/planmart/Order.java | 2316 | package com.planmart;
import java.util.ArrayList;
import java.util.Date;
public class Order {
private Customer customer;
private String shippingRegion;
private PaymentMethod paymentMethod;
private Date placed;
private ArrayList<ProductOrder> items = new ArrayList<>();
private ArrayList<LineItem> lineItems = new ArrayList<>();
public Order(Customer customer, String shippingRegion, PaymentMethod paymentMethod, Date placed) {
this.customer = customer;
this.shippingRegion = shippingRegion;
this.paymentMethod = paymentMethod;
this.placed = placed;
}
/**
* Gets the customer who placed the order.
*/
public Customer getCustomer() {
return customer;
}
/**
* Sets the customer who placed the order.
*/
public void setCustomer(Customer customer) {
this.customer = customer;
}
/**
* Gets two-letter region where the order should be shipped to.
*/
public String getShippingRegion() {
return shippingRegion;
}
/**
* Sets two-letter region where the order should be shipped to.
*/
public void setShippingRegion(String shippingRegion) {
this.shippingRegion = shippingRegion;
}
/**
* Gets an enum describing the method of payment for the order.
*/
public PaymentMethod getPaymentMethod() {
return paymentMethod;
}
/**
* Sets an enum describing the method of payment for the order.
*/
public void setPaymentMethod(PaymentMethod paymentMethod) {
this.paymentMethod = paymentMethod;
}
/**
* Gets the date and time in UTC when the order was placed.
*/
public Date getPlaced() {
return placed;
}
/**
* Sets the date and time in UTC when the order was placed.
*/
public void setPlaced(Date placed) {
this.placed = placed;
}
/**
* Gets a list of items representing one or more products and the quantity of each.
*/
public ArrayList<ProductOrder> getItems() {
return items;
}
/**
* Gets a list of line items that represent adjustments to the order by the processor (tax, shipping, etc.)
*/
public ArrayList<LineItem> getLineItems() {
return lineItems;
}
}
| mit |
wblut/Render2016_RenderingTheObvious | src/wblut/Render2016/MultiTextNoTitle.java | 1180 | package wblut.Render2016;
import java.util.Arrays;
import processing.core.PConstants;
public class MultiTextNoTitle extends Slide {
String[] lines = null;
int offset;
public MultiTextNoTitle(final RTO home, final String... lines) {
super(home, "");
this.lines = Arrays.copyOf(lines, lines.length);
offset = 80;
};
public MultiTextNoTitle(final RTO home, final int offset, final String... lines) {
super(home, "");
this.lines = Arrays.copyOf(lines, lines.length);
this.offset = offset;
};
@Override
void setup() {
home.fill(0);
}
@Override
public void updatePre() {
}
@Override
void backgroundDraw() {
home.background(20);
}
@Override
void transformAndLights() {
}
@Override
void normalDraw() {
}
@Override
void glowDraw() {
}
@Override
public void hudDraw() {
home.textFont(home.fontsans, 1.8f * home.smallfont);
home.textAlign(PConstants.CENTER);
home.fill(200);
float m = 0;
for (int i = 0; i < lines.length; i++) {
home.text(lines[i], home.width / 2, ((home.height / 2) - offset) + m);
m += 2.6f * home.smallfont;
}
}
@Override
public void updatePost() {
}
@Override
void shutdown() {
}
}
| cc0-1.0 |
KryptonCaptain/ThaumicBases | src/main/java/tb/common/block/BlockNodeManipulator.java | 2456 | package tb.common.block;
import tb.common.item.ItemNodeFoci;
import tb.common.tile.TileNodeManipulator;
import tb.init.TBItems;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public class BlockNodeManipulator extends BlockContainer{
public BlockNodeManipulator()
{
super(Material.rock);
}
@Override
public TileEntity createNewTileEntity(World w, int meta) {
return new TileNodeManipulator();
}
public boolean isOpaqueCube()
{
return false;
}
public boolean renderAsNormalBlock()
{
return false;
}
public int getRenderType()
{
return 0x421922;
}
public boolean onBlockActivated(World w, int x, int y, int z, EntityPlayer p, int side, float vecX, float vecY, float vecZ)
{
if(p.getCurrentEquippedItem() != null)
{
ItemStack current = p.getCurrentEquippedItem();
if(current.getItem() instanceof ItemNodeFoci)
{
if(w.getBlockMetadata(x, y, z) != 0)
{
int meta = w.getBlockMetadata(x, y, z);
ItemStack stk = new ItemStack(TBItems.nodeFoci,1,meta-1);
EntityItem itm = new EntityItem(w,x+0.5D,y,z+0.5D,stk);
if(!w.isRemote)
w.spawnEntityInWorld(itm);
}
w.setBlockMetadataWithNotify(x, y, z, current.getItemDamage()+1, 3);
p.destroyCurrentEquippedItem();
return true;
}
}else
{
if(w.getBlockMetadata(x, y, z) != 0)
{
int meta = w.getBlockMetadata(x, y, z);
ItemStack stk = new ItemStack(TBItems.nodeFoci,1,meta-1);
EntityItem itm = new EntityItem(w,x+0.5D,y,z+0.5D,stk);
if(!w.isRemote)
w.spawnEntityInWorld(itm);
}
w.setBlockMetadataWithNotify(x, y, z, 0, 3);
}
return true;
}
@Override
public void breakBlock(World w, int x, int y, int z, Block b, int meta)
{
if(meta > 0) //Fix for the manipulator not dropping the foci.
{
ItemStack foci = new ItemStack(TBItems.nodeFoci,1,meta-1);
EntityItem itm = new EntityItem(w,x+0.5D,y+0.5D,z+0.5D,foci);
if(!w.isRemote)
w.spawnEntityInWorld(itm);
}
super.breakBlock(w, x, y, z, b, meta);
}
}
| cc0-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.jpa.tests.spec10.entity_jpa_3.0_fat/fat/src/com/ibm/ws/jpa/tests/spec10/entity/FATSuite.java | 1362 | /*******************************************************************************
* Copyright (c) 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jpa.tests.spec10.entity;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.ibm.ws.jpa.tests.spec10.entity.tests.AbstractFATSuite;
import com.ibm.ws.jpa.tests.spec10.entity.tests.Entity_EJB;
import com.ibm.ws.jpa.tests.spec10.entity.tests.Entity_Web;
import componenttest.rules.repeater.FeatureReplacementAction;
import componenttest.rules.repeater.RepeatTests;
@RunWith(Suite.class)
@SuiteClasses({
Entity_EJB.class,
Entity_Web.class,
componenttest.custom.junit.runner.AlwaysPassesTest.class
})
public class FATSuite extends AbstractFATSuite {
@ClassRule
public static RepeatTests r = RepeatTests.with(FeatureReplacementAction.EE9_FEATURES());
}
| epl-1.0 |
xiaohanz/softcontroller | opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/testingservices/parallelapsp/TestingParallelAPSPConfigMXBean.java | 972 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.config.manager.testingservices.parallelapsp;
import javax.management.ObjectName;
import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
@ServiceInterfaceAnnotation(value = TestingParallelAPSPConfigMXBean.NAME, osgiRegistrationType = TestingAPSP.class)
public interface TestingParallelAPSPConfigMXBean {
static final String NAME = "apsp";
ObjectName getThreadPool();
void setThreadPool(ObjectName threadPoolName);
String getSomeParam();
void setSomeParam(String s);
// for reporting. this should be moved to runtime jmx bean
Integer getMaxNumberOfThreads();
}
| epl-1.0 |
Netcentric/accesscontroltool | accesscontroltool-bundle/src/test/java/biz/netcentric/cq/tools/actool/configreader/TestYamlConfigReader.java | 2450 | /*
* (C) Copyright 2017 Netcentric AG.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package biz.netcentric.cq.tools.actool.configreader;
import java.util.Map;
import biz.netcentric.cq.tools.actool.configmodel.AceBean;
import biz.netcentric.cq.tools.actool.configmodel.AuthorizableConfigBean;
import biz.netcentric.cq.tools.actool.validators.exceptions.AcConfigBeanValidationException;
/** Subclass of YamlConfigReader only used for unit tests. Overrides bean setup-methods from YamlConfigReader to set up TestAceBean and
* TestAuthorizableConfigBean in order to set the assertedExceptionString set in test yaml files for later evaluation in unit tests. Also
* overrides getNewAceBean() and getNewAuthorizableConfigBean() to return the correct testing type in order to make the downcast in
* overridden setup-methods possible.
*
* @author jochenkoschorke */
public class TestYamlConfigReader extends YamlConfigReader {
protected final String ASSERTED_EXCEPTION = "assertedException";
@Override
protected void setupAceBean(final String principal,
final Map<String, ?> currentAceDefinition, final AceBean tmpAclBean, String sourceFile) {
super.setupAceBean(principal, currentAceDefinition, tmpAclBean, sourceFile);
((TestAceBean) tmpAclBean).setAssertedExceptionString(getMapValueAsString(
currentAceDefinition, ASSERTED_EXCEPTION));
}
@Override
protected void setupAuthorizableBean(
final AuthorizableConfigBean authorizableConfigBean,
final Map<String, Object> currentPrincipalDataMap,
final String authorizableId,
boolean isGroupSection) throws AcConfigBeanValidationException {
super.setupAuthorizableBean(authorizableConfigBean, currentPrincipalDataMap, authorizableId, isGroupSection);
((TestAuthorizableConfigBean) authorizableConfigBean).setAssertedExceptionString(getMapValueAsString(
currentPrincipalDataMap, ASSERTED_EXCEPTION));
}
@Override
protected AceBean getNewAceBean() {
return new TestAceBean();
}
@Override
protected AuthorizableConfigBean getNewAuthorizableConfigBean() {
return new TestAuthorizableConfigBean();
}
}
| epl-1.0 |
BIRT-eXperts/IBM-Maximo-BIRT-Code-Generator | src/com/mmkarton/mx7/reportgenerator/sqledit/SQLUtility.java | 7663 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
* Ing. Gerd Stockner (Mayr-Melnhof Karton Gesellschaft m.b.H.) - modifications
* Christian Voller (Mayr-Melnhof Karton Gesellschaft m.b.H.) - modifications
* CoSMIT GmbH - publishing, maintenance
*******************************************************************************/
package com.mmkarton.mx7.reportgenerator.sqledit;
import java.sql.Types;
import java.text.Bidi;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.datatools.connectivity.oda.IParameterMetaData;
import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
import org.eclipse.datatools.connectivity.oda.OdaException;
import org.eclipse.datatools.connectivity.oda.design.DataSetParameters;
import org.eclipse.datatools.connectivity.oda.design.DesignFactory;
import org.eclipse.datatools.connectivity.oda.design.ParameterDefinition;
import org.eclipse.datatools.connectivity.oda.design.ParameterMode;
import org.eclipse.datatools.connectivity.oda.design.ResultSetColumns;
import org.eclipse.datatools.connectivity.oda.design.ResultSetDefinition;
import org.eclipse.datatools.connectivity.oda.design.ui.designsession.DesignSessionUtil;
import com.mmkarton.mx7.reportgenerator.engine.SQLQuery;
import com.mmkarton.mx7.reportgenerator.jdbc.ResultSetMetaData;
import com.mmkarton.mx7.reportgenerator.wizards.BIRTReportWizard;
/**
* The utility class for SQLDataSetEditorPage
*
*/
public class SQLUtility
{
/**
* save the dataset design's metadata info
*
* @param design
*/
public static SQLQuery getBIRTSQLFields(String sqlQueryText) {
MetaDataRetriever retriever = new MetaDataRetriever( addDummyWhere(sqlQueryText));
IResultSetMetaData resultsetMeta = retriever.getResultSetMetaData( );
IParameterMetaData paramMeta = retriever.getParameterMetaData( );
return saveDataSetDesign( resultsetMeta, paramMeta ,sqlQueryText);
}
public static SQLQuery saveDataSetDesign( IResultSetMetaData meta, IParameterMetaData paramMeta, String sqlQueryText )
{
try
{
setParameterMetaData( paramMeta );
// set resultset metadata
return setResultSetMetaData(meta, sqlQueryText );
}
catch ( OdaException e )
{
return null;
}
}
/**
* Set parameter metadata in dataset design
*
* @param design
* @param query
*/
private static void setParameterMetaData(IParameterMetaData paramMeta )
{
try
{
// set parameter metadata
mergeParameterMetaData( paramMeta );
}
catch ( OdaException e )
{
// do nothing, to keep the parameter definition in dataset design
// dataSetDesign.setParameters( null );
}
}
/**
* solve the BIDI line problem
* @param lineText
* @return
*/
public static int[] getBidiLineSegments( String lineText )
{
int[] seg = null;
if ( lineText != null
&& lineText.length( ) > 0
&& !new Bidi( lineText, Bidi.DIRECTION_LEFT_TO_RIGHT ).isLeftToRight( ) )
{
List list = new ArrayList( );
// Punctuations will be regarded as delimiter so that different
// splits could be rendered separately.
Object[] splits = lineText.split( "\\p{Punct}" );
// !=, <> etc. leading to "" will be filtered to meet the rule that
// segments must not have duplicates.
for ( int i = 0; i < splits.length; i++ )
{
if ( !splits[i].equals( "" ) )
list.add( splits[i] );
}
splits = list.toArray( );
// first segment must be 0
// last segment does not necessarily equal to line length
seg = new int[splits.length + 1];
for ( int i = 0; i < splits.length; i++ )
{
seg[i + 1] = lineText.indexOf( (String) splits[i], seg[i] )
+ ( (String) splits[i] ).length( );
}
}
return seg;
}
/**
* Return pre-defined query text pattern with every element in a cell.
*
* @return pre-defined query text
*/
public static String getQueryPresetTextString( String extensionId )
{
String[] lines = getQueryPresetTextArray( extensionId );
String result = "";
if ( lines != null && lines.length > 0 )
{
for ( int i = 0; i < lines.length; i++ )
{
result = result
+ lines[i] + ( i == lines.length - 1 ? " " : " \n" );
}
}
return result;
}
/**
* Return pre-defined query text pattern with every element in a cell in an
* Array
*
* @return pre-defined query text in an Array
*/
public static String[] getQueryPresetTextArray( String extensionId )
{
final String[] lines;
if ( extensionId.equals( "org.eclipse.birt.report.data.oda.jdbc.SPSelectDataSet" ) )
lines = new String[]{
"{call procedure-name(arg1,arg2, ...)}"
};
else
lines = new String[]{
"select", "from"
};
return lines;
}
/**
* merge paramter meta data between dataParameter and datasetDesign's
* parameter.
*
* @param dataSetDesign
* @param md
* @throws OdaException
*/
private static void mergeParameterMetaData( IParameterMetaData md ) throws OdaException
{
if ( md == null)
return;
DataSetParameters dataSetParameter = DesignSessionUtil.toDataSetParametersDesign( md,
ParameterMode.IN_LITERAL );
if ( dataSetParameter != null )
{
Iterator iter = dataSetParameter.getParameterDefinitions( )
.iterator( );
while ( iter.hasNext( ) )
{
ParameterDefinition defn = (ParameterDefinition) iter.next( );
proccessParamDefn( defn, dataSetParameter );
}
}
//dataSetDesign.setParameters( dataSetParameter );
}
/**
* Process the parameter definition for some special case
*
* @param defn
* @param parameters
*/
private static void proccessParamDefn( ParameterDefinition defn,
DataSetParameters parameters )
{
if ( defn.getAttributes( ).getNativeDataTypeCode( ) == Types.NULL )
{
defn.getAttributes( ).setNativeDataTypeCode( Types.CHAR );
}
}
/**
* Set the resultset metadata in dataset design
*
* @param dataSetDesign
* @param md
* @throws OdaException
*/
private static SQLQuery setResultSetMetaData(IResultSetMetaData md, String sqlQueryText ) throws OdaException
{
SQLQuery query=null;
ResultSetColumns columns = DesignSessionUtil.toResultSetColumnsDesign( md );
if ( columns != null )
{
query=new SQLQuery();
ResultSetDefinition resultSetDefn = DesignFactory.eINSTANCE.createResultSetDefinition( );
resultSetDefn.setResultSetColumns( columns );
int count=resultSetDefn.getResultSetColumns().getResultColumnDefinitions().size();
query.setSqlQueryString(sqlQueryText);
for (int i = 0; i < count; i++)
{
int columntype=-1;
String columname="";
try {
ResultSetMetaData dataset=(ResultSetMetaData)md;
columname=dataset.getColumnName(i+1);
columntype=dataset.getColumnType(i+1);
} catch (Exception e)
{
return null;
}
query.setFields(columname, columntype);
}
}
return query;
}
private static String addDummyWhere(String sqlQueryText)
{
if (sqlQueryText==null) {
return null;
}
String tempsql = sqlQueryText.toUpperCase();
String sql_query="";
int where_pos = tempsql.toUpperCase().indexOf("WHERE");
if (where_pos > 0)
{
sql_query = tempsql.substring(0,where_pos );
}
else
{
sql_query = tempsql;
}
return sql_query+" Where 1=2";
}
}
| epl-1.0 |
ELTE-Soft/xUML-RT-Executor | plugins/hu.eltesoft.modelexecution.m2t.smap.emf/src/hu/eltesoft/modelexecution/m2t/smap/emf/ReferenceToLineMapping.java | 1442 | package hu.eltesoft.modelexecution.m2t.smap.emf;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/**
* Maps qualified EMF object references to virtual line numbers. Line numbering
* starts from one, and incremented by one when a new reference inserted.
*/
class ReferenceToLineMapping implements Serializable {
private static final long serialVersionUID = 303577619348585564L;
private final Vector<QualifiedReference> lineNumberToReference = new Vector<>();
private final Map<QualifiedReference, Integer> referenceToLineNumber = new HashMap<>();
public int addLineNumber(QualifiedReference reference) {
Integer result = toLineNumber(reference);
if (null != result) {
return result;
}
lineNumberToReference.add(reference);
int lineNumber = lineNumberToReference.size();
referenceToLineNumber.put(reference, lineNumber);
return lineNumber;
}
public Integer toLineNumber(QualifiedReference reference) {
return referenceToLineNumber.get(reference);
}
public QualifiedReference fromLineNumber(int lineNumber) {
// Vectors are indexed from zero, while lines from one
int index = lineNumber - 1;
if (index < 0 || lineNumberToReference.size() <= index) {
return null;
}
return lineNumberToReference.get(index);
}
@Override
public String toString() {
return referenceToLineNumber.toString() + ";" + lineNumberToReference.toString();
}
}
| epl-1.0 |
Yoshi-xtaze/ACL2015_Jafaden | pacman/carte/Labyrinthe.java | 3356 | package pacman.carte;
import java.util.ArrayList;
import pacman.personnages.Pacman;
import pacman.personnages.Personnage;
public class Labyrinthe {
public static final int NB_COLONNE = 20;
public static final int NB_LIGNE = 20;
protected int[][] grille;
protected int largeur;
protected int hauteur;
public static int LARGEUR_CASE = 25;
public static int HAUTEUR_CASE = 25;
protected ArrayList<CaseTrappe> trappes;
protected ArrayList<CaseColle> colles;
protected Case[][] tabCases;
protected int largeurTresor;
protected int hauteurTresor;
//protected Pacman pacman;
/**
*
* @param largeur la largeur du labyrinthe
* @param hauteur la hauteur du labyrinthe
*/
public Labyrinthe(int largeur, int hauteur){
grille = new int[largeur][hauteur];
tabCases = new Case[largeur][hauteur];
this.largeur = largeur;
this.trappes = new ArrayList<CaseTrappe>();
this.hauteur = hauteur;
}
public int[][] getGrille() {
return grille;
}
public void setGrille(int[][] grille) {
this.grille = grille;
}
public void setGrilleCases(Case[][] grille){
this.tabCases = grille;
}
public int getLargeur() {
return largeur;
}
/**
* Teste si une position dans le labyrinthe est disponible, pour pouvoir s'y deplacer
* @param largeur
* @param hauteur
* @return
*/
public boolean estLibre(int largeur, int hauteur){
boolean rep = true;
/* Tests bords de map */
if(largeur < 0)
rep = false;
else if((largeur >= (this.largeur))){
rep = false;
}else if((hauteur < 0)){
rep = false;
}else if((hauteur >= (this.hauteur))){
rep = false;
}
/* Test Murs */
if(rep){
Case c = getCase(largeur, hauteur);
rep = c.isAteignable();
}
return rep;
}
public int getHauteur() {
return hauteur;
}
/**
*
* @param largeur
* @param hauteur
* @return une case du labyrinthe
*/
public Case getCase(int largeur, int hauteur){
return tabCases[largeur][hauteur];
}
public int getLargeurTabCase(){
return tabCases.length;
}
public int getHauteurTabCase(){
return tabCases[0].length;
}
public void setPosTresor(int largeur, int hauteur){
this.largeurTresor=largeur;
this.hauteurTresor=hauteur;
}
public int getLargeurTresor(){
return this.largeurTresor;
}
public int getHauteurTresor(){
return this.hauteurTresor;
}
public void addCaseTrappe(Case c){
trappes.add((CaseTrappe) c);
}
public void addCaseColle(Case c){
colles.add((CaseColle) c);
}
public CaseTrappe getDestination(Pacman p){
CaseTrappe res = null;
boolean trouv = false;
int i = 0;
while(!trouv && i < trappes.size()){
CaseTrappe c = trappes.get(i);
if(c.hit(p)){
trouv = true;
res = c.getDestination();
}
i++;
}
return res;
}
public void linkTrappes(){
for(CaseTrappe c : trappes){
makeAssociation(c);
}
}
private void makeAssociation(CaseTrappe t){
CaseTrappe res = null;
boolean trouv = false;
int i = 0;
while(!trouv && i< trappes.size()){
CaseTrappe c = trappes.get(i);
if(!c.equals(t)){//si la case en cours n'est pas celle de depart
if(c.isAssociation(t)){
t.setDestination(c);
}
}
i++;
}
}
public boolean isColle(Personnage p){
for(int i=0;i<colles.size();i++){
CaseColle c = colles.get(i);
if(c.hit(p))return true;
}
return false;
}
}
| epl-1.0 |
mareknovotny/windup | reporting/api/src/main/java/org/jboss/windup/reporting/rules/CreateApplicationListReportRuleProvider.java | 3507 | package org.jboss.windup.reporting.rules;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.jboss.forge.furnace.Furnace;
import org.jboss.windup.config.AbstractRuleProvider;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.config.metadata.RuleMetadata;
import org.jboss.windup.config.operation.GraphOperation;
import org.jboss.windup.config.phase.PostReportGenerationPhase;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.model.WindupVertexFrame;
import org.jboss.windup.graph.service.GraphService;
import org.jboss.windup.reporting.model.ApplicationReportModel;
import org.jboss.windup.reporting.model.TemplateType;
import org.jboss.windup.reporting.model.WindupVertexListModel;
import org.jboss.windup.reporting.rules.AttachApplicationReportsToIndexRuleProvider;
import org.jboss.windup.reporting.service.ApplicationReportService;
import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.ConfigurationBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;
/**
* This renders an application index page listing all applications analyzed by the current execution of windup.
*
* @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a>
*/
@RuleMetadata(phase = PostReportGenerationPhase.class, before = AttachApplicationReportsToIndexRuleProvider.class)
public class CreateApplicationListReportRuleProvider extends AbstractRuleProvider
{
public static final String APPLICATION_LIST_REPORT = "Application List";
private static final String OUTPUT_FILENAME = "../index.html";
public static final String TEMPLATE_PATH = "/reports/templates/application_list.ftl";
@Inject
private Furnace furnace;
// @formatter:off
@Override
public Configuration getConfiguration(GraphContext context)
{
return ConfigurationBuilder.begin()
.addRule()
.perform(new GraphOperation() {
@Override
public void perform(GraphRewrite event, EvaluationContext context) {
createIndexReport(event.getGraphContext());
}
});
}
// @formatter:on
private void createIndexReport(GraphContext context)
{
ApplicationReportService applicationReportService = new ApplicationReportService(context);
ApplicationReportModel report = applicationReportService.create();
report.setReportPriority(1);
report.setReportIconClass("glyphicon glyphicon-home");
report.setReportName(APPLICATION_LIST_REPORT);
report.setTemplatePath(TEMPLATE_PATH);
report.setTemplateType(TemplateType.FREEMARKER);
report.setDisplayInApplicationReportIndex(false);
report.setReportFilename(OUTPUT_FILENAME);
GraphService<WindupVertexListModel> listService = new GraphService<>(context, WindupVertexListModel.class);
WindupVertexListModel<ApplicationReportModel> applications = listService.create();
for (ApplicationReportModel applicationReportModel : applicationReportService.findAll())
{
if (applicationReportModel.isMainApplicationReport() != null && applicationReportModel.isMainApplicationReport())
applications.addItem(applicationReportModel);
}
Map<String, WindupVertexFrame> relatedData = new HashMap<>();
relatedData.put("applications", applications);
report.setRelatedResource(relatedData);
}
}
| epl-1.0 |
Obeo/Game-Designer | plugins/fr.obeo.dsl.game.edit/src-gen/fr/obeo/dsl/game/provider/UIItemProvider.java | 6992 | /**
*/
package fr.obeo.dsl.game.provider;
import fr.obeo.dsl.game.GameFactory;
import fr.obeo.dsl.game.GamePackage;
import fr.obeo.dsl.game.UI;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link fr.obeo.dsl.game.UI} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class UIItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public UIItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addNamePropertyDescriptor(object);
addFollowPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Name feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addNamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Scene_name_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Scene_name_feature", "_UI_Scene_type"),
GamePackage.Literals.SCENE__NAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Follow feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addFollowPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Scene_follow_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Scene_follow_feature", "_UI_Scene_type"),
GamePackage.Literals.SCENE__FOLLOW,
true,
false,
true,
null,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(GamePackage.Literals.UI__WIDGETS);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns UI.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/UI"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((UI)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_UI_type") :
getString("_UI_UI_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(UI.class)) {
case GamePackage.UI__NAME:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case GamePackage.UI__WIDGETS:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(GamePackage.Literals.UI__WIDGETS,
GameFactory.eINSTANCE.createContainer()));
newChildDescriptors.add
(createChildParameter
(GamePackage.Literals.UI__WIDGETS,
GameFactory.eINSTANCE.createText()));
newChildDescriptors.add
(createChildParameter
(GamePackage.Literals.UI__WIDGETS,
GameFactory.eINSTANCE.createButton()));
newChildDescriptors.add
(createChildParameter
(GamePackage.Literals.UI__WIDGETS,
GameFactory.eINSTANCE.createIFrame()));
newChildDescriptors.add
(createChildParameter
(GamePackage.Literals.UI__WIDGETS,
GameFactory.eINSTANCE.createHTMLElement()));
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return GameEditPlugin.INSTANCE;
}
}
| epl-1.0 |
sudaraka94/che | wsagent/che-datasource-ide/src/main/java/org/eclipse/che/datasource/ide/newDatasource/connector/DefaultNewDatasourceConnectorViewImpl.java | 8136 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.datasource.ide.newDatasource.connector;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import org.eclipse.che.datasource.ide.DatasourceUiResources;
import javax.annotation.Nullable;
public class DefaultNewDatasourceConnectorViewImpl extends Composite implements DefaultNewDatasourceConnectorView {
interface NewDatasourceViewImplUiBinder extends UiBinder<Widget, DefaultNewDatasourceConnectorViewImpl> {
}
@UiField
Label configureTitleCaption;
@UiField
TextBox hostField;
@UiField
TextBox portField;
@UiField
TextBox dbName;
@UiField
TextBox usernameField;
@UiField
TextBox passwordField;
@UiField
Button testConnectionButton;
@UiField
Label testConnectionErrorMessage;
@UiField
RadioButton radioUserPref;
@UiField
RadioButton radioProject;
@UiField
ListBox projectsList;
@UiField
CheckBox useSSL;
@UiField
CheckBox verifyServerCertificate;
@UiField
DatasourceUiResources datasourceUiResources;
@UiField
Label testConnectionText;
private ActionDelegate delegate;
protected String encryptedPassword;
protected boolean passwordFieldIsDirty = false;
private Long runnerProcessId;
@Inject
public DefaultNewDatasourceConnectorViewImpl(NewDatasourceViewImplUiBinder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
hostField.setText("localhost");
radioUserPref.setValue(true);
radioProject.setEnabled(false);
projectsList.setEnabled(false);
projectsList.setWidth("100px");
configureTitleCaption.setText("Settings");
}
@Override
public void setDelegate(DefaultNewDatasourceConnectorView.ActionDelegate delegate) {
this.delegate = delegate;
}
@Override
public void setImage(@Nullable ImageResource image) {
}
@Override
public void setDatasourceName(@Nullable String dsName) {
}
@Override
public String getDatabaseName() {
return dbName.getText();
}
@UiHandler("dbName")
public void onDatabaseNameFieldChanged(KeyUpEvent event) {
delegate.databaseNameChanged(dbName.getText());
}
@Override
public String getHostname() {
return hostField.getText();
}
@UiHandler("hostField")
public void onHostNameFieldChanged(KeyUpEvent event) {
delegate.hostNameChanged(hostField.getText());
}
@Override
public int getPort() {
return Integer.parseInt(portField.getText());
}
@Override
public String getUsername() {
return usernameField.getText();
}
@UiHandler("usernameField")
public void onUserNameFieldChanged(KeyUpEvent event) {
delegate.userNameChanged(usernameField.getText());
}
@Override
public String getPassword() {
return passwordField.getText();
}
@UiHandler("passwordField")
public void onPasswordNameFieldChanged(KeyUpEvent event) {
delegate.passwordChanged(passwordField.getText());
delegate.onClickTestConnectionButton();
}
@Override
public String getEncryptedPassword() {
return encryptedPassword;
}
@Override
public void setPort(int port) {
portField.setText(Integer.toString(port));
}
@UiHandler("portField")
public void onPortFieldChanged(KeyPressEvent event) {
if (!Character.isDigit(event.getCharCode())) {
portField.cancelKey();
}
delegate.portChanged(Integer.parseInt(portField.getText()));
}
@Override
public boolean getUseSSL() {
if (useSSL.getValue() != null) {
return useSSL.getValue();
} else {
return false;
}
}
@Override
public boolean getVerifyServerCertificate() {
if (verifyServerCertificate.getValue() != null) {
return verifyServerCertificate.getValue();
} else {
return false;
}
}
@Override
public void setDatabaseName(final String databaseName) {
dbName.setValue(databaseName);
}
@Override
public void setHostName(final String hostName) {
hostField.setValue(hostName);
}
@Override
public void setUseSSL(final boolean useSSL) {
this.useSSL.setValue(useSSL);
}
@UiHandler({"useSSL"})
void onUseSSLChanged(ValueChangeEvent<Boolean> event) {
delegate.useSSLChanged(event.getValue());
}
@Override
public void setVerifyServerCertificate(final boolean verifyServerCertificate) {
this.verifyServerCertificate.setValue(verifyServerCertificate);
}
@UiHandler({"verifyServerCertificate"})
void onVerifyServerCertificateChanged(ValueChangeEvent<Boolean> event) {
delegate.verifyServerCertificateChanged(event.getValue());
}
@Override
public void setUsername(final String username) {
usernameField.setValue(username);
}
@Override
public void setPassword(final String password) {
passwordField.setValue(password);
}
@UiHandler("testConnectionButton")
void handleClick(ClickEvent e) {
delegate.onClickTestConnectionButton();
}
@UiHandler("testConnectionText")
void handleTextClick(ClickEvent e) {
delegate.onClickTestConnectionButton();
}
@Override
public void onTestConnectionSuccess() {
// turn button green
testConnectionButton.setStyleName(datasourceUiResources.datasourceUiCSS().datasourceWizardTestConnectionOK());
// clear error messages
testConnectionErrorMessage.setText("Connection Established Successfully!");
}
@Override
public void onTestConnectionFailure(String errorMessage) {
// turn test button red
testConnectionButton.setStyleName(datasourceUiResources.datasourceUiCSS().datasourceWizardTestConnectionKO());
// set message
testConnectionErrorMessage.setText(errorMessage);
}
@Override
public void setEncryptedPassword(String encryptedPassword, boolean resetPasswordField) {
this.encryptedPassword = encryptedPassword;
passwordFieldIsDirty = false;
if (resetPasswordField) {
passwordField.setText("");
}
}
@UiHandler("passwordField")
public void handlePasswordFieldChanges(ChangeEvent event) {
passwordFieldIsDirty = true;
}
@Override
public boolean isPasswordFieldDirty() {
return passwordFieldIsDirty;
}
@Override
public Long getRunnerProcessId() {
return runnerProcessId;
}
@Override
public void setRunnerProcessId(Long runnerProcessId) {
this.runnerProcessId = runnerProcessId;
}
}
| epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext/emf-gen/org/eclipse/xtext/impl/UntilTokenImpl.java | 706 | /**
*/
package org.eclipse.xtext.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.xtext.UntilToken;
import org.eclipse.xtext.XtextPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Until Token</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class UntilTokenImpl extends AbstractNegatedTokenImpl implements UntilToken {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected UntilTokenImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return XtextPackage.Literals.UNTIL_TOKEN;
}
} //UntilTokenImpl
| epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext.testlanguages/src/org/eclipse/xtext/testlanguages/fileAware/scoping/FileAwareTestLanguageScopeProvider.java | 944 | /*
* generated by Xtext
*/
package org.eclipse.xtext.testlanguages.fileAware.scoping;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.xtext.scoping.IGlobalScopeProvider;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.testlanguages.fileAware.fileAware.FileAwarePackage;
import com.google.inject.Inject;
/**
* This class contains custom scoping description.
*
* See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#scoping
* on how and when to use it.
*/
public class FileAwareTestLanguageScopeProvider extends AbstractFileAwareTestLanguageScopeProvider {
@Inject IGlobalScopeProvider global;
public IScope getScope(EObject context, EReference reference) {
if (reference == FileAwarePackage.Literals.IMPORT__ELEMENT) {
return global.getScope(context.eResource(), reference, null);
}
return super.getScope(context, reference);
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/readonly/OneDirectMappingProject.java | 1579 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.oxm.readonly;
import org.eclipse.persistence.sessions.Project;
import org.eclipse.persistence.oxm.*;
import org.eclipse.persistence.oxm.mappings.XMLDirectMapping;
public class OneDirectMappingProject extends Project
{
public OneDirectMappingProject()
{
super();
addEmployeeDescriptor();
}
public void addEmployeeDescriptor()
{
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setDefaultRootElement("employee");
descriptor.setJavaClass(Employee.class);
XMLDirectMapping firstNameMapping = new XMLDirectMapping();
firstNameMapping.setAttributeName("firstName");
firstNameMapping.setXPath("first-name/text()");
firstNameMapping.readOnly();
descriptor.addMapping(firstNameMapping);
this.addDescriptor(descriptor);
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/page/ui/com.odcgroup.page.transformmodel.ui/src/main/java/com/odcgroup/page/transformmodel/ui/builder/WidgetBuilderContext.java | 2613 | package com.odcgroup.page.transformmodel.ui.builder;
import org.eclipse.core.runtime.Assert;
import com.odcgroup.mdf.ecore.util.DomainRepository;
import com.odcgroup.page.metamodel.MetaModel;
import com.odcgroup.page.metamodel.util.MetaModelRegistry;
import com.odcgroup.page.model.corporate.CorporateDesign;
import com.odcgroup.page.model.corporate.CorporateDesignUtils;
import com.odcgroup.page.model.util.WidgetFactory;
import com.odcgroup.workbench.core.IOfsProject;
/**
* The WidgetBuilderContext is used to provide information to all the different
* WidgetBuilder's used when building a Widget.
*
* @author Gary Hayes
*/
public class WidgetBuilderContext {
/** The OFS project for which we are building Widgets. */
private IOfsProject ofsProject;
/** This is the corporate design to use when building template. */
private CorporateDesign corporateDesign;
/** The WidgetBuilderFactory used to build Widgets. */
private WidgetBuilderFactory widgetBuilderFactory;
/**
* Creates a new WidgetBuilderContext.
*
* @param ofsProject The OFS project for which we are building Widgets
* @param widgetBuilderFactory The WidgetBuilderFactory used to build Widgets
*/
public WidgetBuilderContext(IOfsProject ofsProject, WidgetBuilderFactory widgetBuilderFactory) {
Assert.isNotNull(ofsProject);
Assert.isNotNull(widgetBuilderFactory);
this.ofsProject = ofsProject;
this.widgetBuilderFactory = widgetBuilderFactory;
corporateDesign = CorporateDesignUtils.getCorporateDesign(ofsProject);
}
/**
* Gets the path containing the model definitions.
*
* @return path
*/
public final DomainRepository getDomainRepository() {
return DomainRepository.getInstance(ofsProject);
}
/**
* Gets the Corporate Design.
*
* @return CorporateDesign The corporate design attached to this builder
*/
public final CorporateDesign getCorporateDesign() {
return corporateDesign;
}
/**
* Gets the metamodel.
*
* @return MetaModel The metamodel.
*/
public final MetaModel getMetaModel() {
return MetaModelRegistry.getMetaModel();
}
/**
* Gets the project for which we are building Widgets.
*
* @return IProject
*/
public final IOfsProject getOfsProject() {
return ofsProject;
}
/**
* Gets the Factory used to build Widgets.
*
* @return WidgetBuilderFactory
*/
public final WidgetBuilderFactory getBuilderFactory() {
return widgetBuilderFactory;
}
/**
* Gets the WidgetFactory.
*
* @return WidgetFactory The WidgetFactory
*/
public WidgetFactory getWidgetFactory() {
return new WidgetFactory();
}
} | epl-1.0 |
jmchilton/TINT | projects/TropixStorageClient/src/test/edu/umn/msi/tropix/storage/client/impl/ModelStorageDataFactoryImplTest.java | 3201 | /*******************************************************************************
* Copyright 2009 Regents of the University of Minnesota. All rights
* reserved.
* Copyright 2009 Mayo Foundation for Medical Education and Research.
* All rights reserved.
*
* This program is made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* 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 INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS
* OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
* PARTICULAR PURPOSE. See the License for the specific language
* governing permissions and limitations under the License.
*
* Contributors:
* Minnesota Supercomputing Institute - initial API and implementation
******************************************************************************/
package edu.umn.msi.tropix.storage.client.impl;
import java.util.HashMap;
import java.util.Map;
import org.easymock.EasyMock;
import org.testng.annotations.Test;
import edu.umn.msi.tropix.common.test.EasyMockUtils;
import edu.umn.msi.tropix.grid.credentials.Credential;
import edu.umn.msi.tropix.models.TropixFile;
import edu.umn.msi.tropix.storage.client.ModelStorageData;
public class ModelStorageDataFactoryImplTest {
@Test(groups = "unit")
public void get() {
final ModelStorageDataFactoryImpl factory = new ModelStorageDataFactoryImpl();
final TropixFileFactory tfFactory = EasyMock.createMock(TropixFileFactory.class);
factory.setTropixFileFactory(tfFactory);
final Credential proxy = EasyMock.createMock(Credential.class);
TropixFile tropixFile = new TropixFile();
ModelStorageData mds = EasyMock.createMock(ModelStorageData.class);
final String serviceUrl = "http://storage";
final Map<String, Object> map = new HashMap<String, Object>();
map.put("storageServiceUrl", serviceUrl);
tfFactory.getStorageData(EasyMockUtils.<TropixFile>isBeanWithProperties(map), EasyMock.same(proxy));
EasyMock.expectLastCall().andReturn(mds);
EasyMock.replay(tfFactory);
assert mds == factory.getStorageData(serviceUrl, proxy);
EasyMockUtils.verifyAndReset(tfFactory);
tropixFile = new TropixFile();
mds = EasyMock.createMock(ModelStorageData.class);
map.put("fileId", "12345");
tfFactory.getStorageData(EasyMockUtils.<TropixFile>isBeanWithProperties(map), EasyMock.same(proxy));
EasyMock.expectLastCall().andReturn(mds);
EasyMock.replay(tfFactory);
assert mds == factory.getStorageData("12345", serviceUrl, proxy);
EasyMockUtils.verifyAndReset(tfFactory);
tropixFile = new TropixFile();
mds = EasyMock.createMock(ModelStorageData.class);
tfFactory.getStorageData(EasyMock.same(tropixFile), EasyMock.same(proxy));
EasyMock.expectLastCall().andReturn(mds);
EasyMock.replay(tfFactory);
assert mds == factory.getStorageData(tropixFile, proxy);
EasyMockUtils.verifyAndReset(tfFactory);
}
}
| epl-1.0 |
ttimbul/eclipse.wst | bundles/org.eclipse.wst.dtd.ui/src/org/eclipse/wst/dtd/ui/internal/wizard/NewDTDTemplatesWizardPage.java | 17558 | /*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*
*******************************************************************************/
package org.eclipse.wst.dtd.ui.internal.wizard;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.text.templates.DocumentTemplateContext;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateBuffer;
import org.eclipse.jface.text.templates.TemplateContext;
import org.eclipse.jface.text.templates.TemplateContextType;
import org.eclipse.jface.text.templates.persistence.TemplateStore;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.wst.dtd.core.internal.provisional.contenttype.ContentTypeIdForDTD;
import org.eclipse.wst.dtd.ui.StructuredTextViewerConfigurationDTD;
import org.eclipse.wst.dtd.ui.internal.DTDUIMessages;
import org.eclipse.wst.dtd.ui.internal.DTDUIPlugin;
import org.eclipse.wst.dtd.ui.internal.Logger;
import org.eclipse.wst.dtd.ui.internal.editor.IHelpContextIds;
import org.eclipse.wst.dtd.ui.internal.preferences.DTDUIPreferenceNames;
import org.eclipse.wst.dtd.ui.internal.templates.TemplateContextTypeIdsDTD;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.ui.StructuredTextViewerConfiguration;
import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
import org.eclipse.wst.sse.ui.internal.provisional.style.LineStyleProvider;
/**
* Templates page in new file wizard. Allows users to select a new file
* template to be applied in new file.
*
*/
public class NewDTDTemplatesWizardPage extends WizardPage {
/**
* Content provider for templates
*/
private class TemplateContentProvider implements IStructuredContentProvider {
/** The template store. */
private TemplateStore fStore;
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
fStore = null;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object input) {
return fStore.getTemplates(TemplateContextTypeIdsDTD.NEW);
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
fStore = (TemplateStore) newInput;
}
}
/**
* Label provider for templates.
*/
private class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider {
/*
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object,
* int)
*/
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
/*
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object,
* int)
*/
public String getColumnText(Object element, int columnIndex) {
Template template = (Template) element;
switch (columnIndex) {
case 0 :
return template.getName();
case 1 :
return template.getDescription();
default :
return ""; //$NON-NLS-1$
}
}
}
/** Last selected template name */
private String fLastSelectedTemplateName;
/** The viewer displays the pattern of selected template. */
private SourceViewer fPatternViewer;
/** The table presenting the templates. */
private TableViewer fTableViewer;
/** Template store used by this wizard page */
private TemplateStore fTemplateStore;
/** Checkbox for using templates. */
private Button fUseTemplateButton;
public NewDTDTemplatesWizardPage() {
super("NewDTDTemplatesWizardPage", DTDUIMessages.NewDTDTemplatesWizardPage_0, null); //$NON-NLS-1$
setDescription(DTDUIMessages.NewDTDTemplatesWizardPage_1);
}
/**
* Correctly resizes the table so no phantom columns appear
*
* @param parent
* the parent control
* @param buttons
* the buttons
* @param table
* the table
* @param column1
* the first column
* @param column2
* the second column
* @param column3
* the third column
*/
private void configureTableResizing(final Composite parent, final Table table, final TableColumn column1, final TableColumn column2) {
parent.addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Rectangle area = parent.getClientArea();
Point preferredSize = table.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int width = area.width - 2 * table.getBorderWidth();
if (preferredSize.y > area.height) {
// Subtract the scrollbar width from the total column
// width
// if a vertical scrollbar will be required
Point vBarSize = table.getVerticalBar().getSize();
width -= vBarSize.x;
}
Point oldSize = table.getSize();
if (oldSize.x > width) {
// table is getting smaller so make the columns
// smaller first and then resize the table to
// match the client area width
column1.setWidth(width / 2);
column2.setWidth(width / 2);
table.setSize(width, area.height);
}
else {
// table is getting bigger so make the table
// bigger first and then make the columns wider
// to match the client area width
table.setSize(width, area.height);
column1.setWidth(width / 2);
column2.setWidth(width / 2);
}
}
});
}
public void createControl(Composite ancestor) {
Composite parent = new Composite(ancestor, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
parent.setLayout(layout);
// create checkbox for user to use DTD Template
fUseTemplateButton = new Button(parent, SWT.CHECK);
fUseTemplateButton.setText(DTDUIMessages.NewDTDTemplatesWizardPage_4);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
fUseTemplateButton.setLayoutData(data);
fUseTemplateButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
enableTemplates();
}
});
// create composite for Templates table
Composite innerParent = new Composite(parent, SWT.NONE);
GridLayout innerLayout = new GridLayout();
innerLayout.numColumns = 2;
innerLayout.marginHeight = 0;
innerLayout.marginWidth = 0;
innerParent.setLayout(innerLayout);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
innerParent.setLayoutData(gd);
Label label = new Label(innerParent, SWT.NONE);
label.setText(DTDUIMessages.NewDTDTemplatesWizardPage_7);
data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
label.setLayoutData(data);
// create table that displays templates
Table table = new Table(innerParent, SWT.BORDER | SWT.FULL_SELECTION);
data = new GridData(GridData.FILL_BOTH);
data.widthHint = convertWidthInCharsToPixels(2);
data.heightHint = convertHeightInCharsToPixels(10);
data.horizontalSpan = 2;
table.setLayoutData(data);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableLayout tableLayout = new TableLayout();
table.setLayout(tableLayout);
TableColumn column1 = new TableColumn(table, SWT.NONE);
column1.setText(DTDUIMessages.NewDTDTemplatesWizardPage_2);
TableColumn column2 = new TableColumn(table, SWT.NONE);
column2.setText(DTDUIMessages.NewDTDTemplatesWizardPage_3);
fTableViewer = new TableViewer(table);
fTableViewer.setLabelProvider(new TemplateLabelProvider());
fTableViewer.setContentProvider(new TemplateContentProvider());
fTableViewer.setSorter(new ViewerSorter() {
public int compare(Viewer viewer, Object object1, Object object2) {
if ((object1 instanceof Template) && (object2 instanceof Template)) {
Template left = (Template) object1;
Template right = (Template) object2;
int result = left.getName().compareToIgnoreCase(right.getName());
if (result != 0)
return result;
return left.getDescription().compareToIgnoreCase(right.getDescription());
}
return super.compare(viewer, object1, object2);
}
public boolean isSorterProperty(Object element, String property) {
return true;
}
});
fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent e) {
updateViewerInput();
}
});
// create viewer that displays currently selected template's contents
fPatternViewer = doCreateViewer(parent);
fTemplateStore = DTDUIPlugin.getDefault().getTemplateStore();
fTableViewer.setInput(fTemplateStore);
// Create linked text to just to templates preference page
Link link = new Link(parent, SWT.NONE);
link.setText(DTDUIMessages.NewDTDTemplatesWizardPage_6);
data = new GridData(SWT.END, SWT.FILL, true, false, 2, 1);
link.setLayoutData(data);
link.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
linkClicked();
}
});
configureTableResizing(innerParent, table, column1, column2);
loadLastSavedPreferences();
PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, IHelpContextIds.DTD_NEWWIZARD_TEMPLATE_HELPID);
Dialog.applyDialogFont(parent);
setControl(parent);
}
/**
* Creates, configures and returns a source viewer to present the template
* pattern on the preference page. Clients may override to provide a
* custom source viewer featuring e.g. syntax coloring.
*
* @param parent
* the parent control
* @return a configured source viewer
*/
private SourceViewer createViewer(Composite parent) {
SourceViewerConfiguration sourceViewerConfiguration = new StructuredTextViewerConfiguration() {
StructuredTextViewerConfiguration baseConfiguration = new StructuredTextViewerConfigurationDTD();
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return baseConfiguration.getConfiguredContentTypes(sourceViewer);
}
public LineStyleProvider[] getLineStyleProviders(ISourceViewer sourceViewer, String partitionType) {
return baseConfiguration.getLineStyleProviders(sourceViewer, partitionType);
}
};
SourceViewer viewer = new StructuredTextViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
viewer.getTextWidget().setFont(JFaceResources.getFont("org.eclipse.wst.sse.ui.textfont")); //$NON-NLS-1$
IStructuredModel scratchModel = StructuredModelManager.getModelManager().createUnManagedStructuredModelFor(ContentTypeIdForDTD.ContentTypeID_DTD);
IDocument document = scratchModel.getStructuredDocument();
viewer.configure(sourceViewerConfiguration);
viewer.setDocument(document);
return viewer;
}
private SourceViewer doCreateViewer(Composite parent) {
Label label = new Label(parent, SWT.NONE);
label.setText(DTDUIMessages.NewDTDTemplatesWizardPage_5);
GridData data = new GridData();
data.horizontalSpan = 2;
label.setLayoutData(data);
SourceViewer viewer = createViewer(parent);
viewer.setEditable(false);
Control control = viewer.getControl();
data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = 2;
data.heightHint = convertHeightInCharsToPixels(5);
// [261274] - source viewer was growing to fit the max line width of the template
data.widthHint = convertWidthInCharsToPixels(2);
control.setLayoutData(data);
return viewer;
}
/**
* Enable/disable controls in page based on fUseTemplateButton's current
* state.
*/
void enableTemplates() {
boolean enabled = fUseTemplateButton.getSelection();
if (!enabled) {
// save last selected template
Template template = getSelectedTemplate();
if (template != null)
fLastSelectedTemplateName = template.getName();
else
fLastSelectedTemplateName = ""; //$NON-NLS-1$
fTableViewer.setSelection(null);
}
else {
setSelectedTemplate(fLastSelectedTemplateName);
}
fTableViewer.getControl().setEnabled(enabled);
fPatternViewer.getControl().setEnabled(enabled);
}
/**
* Return the template preference page id
*
* @return
*/
private String getPreferencePageId() {
return "org.eclipse.wst.sse.ui.preferences.dtd.templates"; //$NON-NLS-1$
}
/**
* Get the currently selected template.
*
* @return
*/
private Template getSelectedTemplate() {
Template template = null;
IStructuredSelection selection = (IStructuredSelection) fTableViewer.getSelection();
if (selection.size() == 1) {
template = (Template) selection.getFirstElement();
}
return template;
}
/**
* Returns template string to insert.
*
* @return String to insert or null if none is to be inserted
*/
String getTemplateString() {
String templateString = null;
Template template = getSelectedTemplate();
if (template != null) {
TemplateContextType contextType = DTDUIPlugin.getDefault().getTemplateContextRegistry().getContextType(TemplateContextTypeIdsDTD.NEW);
IDocument document = new Document();
TemplateContext context = new DocumentTemplateContext(contextType, document, 0, 0);
try {
TemplateBuffer buffer = context.evaluate(template);
templateString = buffer.getString();
}
catch (Exception e) {
Logger.log(Logger.WARNING_DEBUG, "Could not create template for new dtd", e); //$NON-NLS-1$
}
}
return templateString;
}
void linkClicked() {
String pageId = getPreferencePageId();
PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getShell(), pageId, new String[]{pageId}, null);
dialog.open();
fTableViewer.refresh();
}
/**
* Load the last template name used in New DTD File wizard.
*/
private void loadLastSavedPreferences() {
String templateName = DTDUIPlugin.getDefault().getPreferenceStore().getString(DTDUIPreferenceNames.NEW_FILE_TEMPLATE_NAME);
if (templateName == null || templateName.length() == 0) {
fLastSelectedTemplateName = ""; //$NON-NLS-1$
fUseTemplateButton.setSelection(false);
}
else {
fLastSelectedTemplateName = templateName;
fUseTemplateButton.setSelection(true);
}
enableTemplates();
}
/**
* Save template name used for next call to New DTD File wizard.
*/
void saveLastSavedPreferences() {
String templateName = ""; //$NON-NLS-1$
Template template = getSelectedTemplate();
if (template != null) {
templateName = template.getName();
}
DTDUIPlugin.getDefault().getPreferenceStore().setValue(DTDUIPreferenceNames.NEW_FILE_TEMPLATE_NAME, templateName);
DTDUIPlugin.getDefault().savePluginPreferences();
}
/**
* Select a template in the table viewer given the template name. If
* template name cannot be found or templateName is null, just select
* first item in table. If no items in table select nothing.
*
* @param templateName
*/
private void setSelectedTemplate(String templateName) {
Object template = null;
if (templateName != null && templateName.length() > 0) {
// pick the last used template
template = fTemplateStore.findTemplate(templateName, TemplateContextTypeIdsDTD.NEW);
}
// no record of last used template so just pick first element
if (template == null) {
// just pick first element
template = fTableViewer.getElementAt(0);
}
if (template != null) {
IStructuredSelection selection = new StructuredSelection(template);
fTableViewer.setSelection(selection, true);
}
}
/**
* Updates the pattern viewer.
*/
void updateViewerInput() {
Template template = getSelectedTemplate();
if (template != null) {
fPatternViewer.getDocument().set(template.getPattern());
}
else {
fPatternViewer.getDocument().set(""); //$NON-NLS-1$
}
}
}
| epl-1.0 |
Subsets and Splits