repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
totopoloco/yascheduler | app_yascheduler/app_yascheduler-ejb/src/test/java/at/mavila/yascheduler/app/test/MemberRegistrationTest.java | 2538 | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.mavila.yascheduler.app.test;
/*
import static org.junit.Assert.assertNotNull;
import java.util.logging.Logger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import at.mavila.yascheduler.app.model.Member;
import at.mavila.yascheduler.app.service.MemberRegistration;
import at.mavila.yascheduler.app.util.Resources;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
*/
//@RunWith(Arquillian.class)
public class MemberRegistrationTest {
/*@Deployment
public static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(Member.class, MemberRegistration.class, Resources.class)
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
// Deploy our test datasource
.addAsWebInfResource("test-ds.xml", "test-ds.xml");
}
@Inject
MemberRegistration memberRegistration;
@Inject
Logger log;
@Test
public void testRegister() throws Exception {
Member newMember = new Member();
newMember.setName("Jane Doe");
newMember.setEmail("jane@mailinator.com");
newMember.setPhoneNumber("2125551234");
memberRegistration.register(newMember);
assertNotNull(newMember.getId());
log.info(newMember.getName() + " was persisted with id " + newMember.getId());
}*/
}
| mit |
Afcepf-GroupeM/ProjetCesium | WebServiceBanque/src/main/java/fr/afcepf/al29/groupem/dao/CustomerDaoApi.java | 79 | package fr.afcepf.al29.groupem.dao;
public interface CustomerDaoApi {
}
| mit |
tripu/validator | src/nu/validator/xml/PrudentHttpEntityResolver.java | 22746 | /*
* Copyright (c) 2005 Henri Sivonen
* Copyright (c) 2007-2017 Mozilla Foundation
*
* 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 nu.validator.xml;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import org.relaxng.datatype.DatatypeException;
import nu.validator.datatype.ContentSecurityPolicy;
import nu.validator.datatype.Html5DatatypeException;
import nu.validator.io.BoundedInputStream;
import nu.validator.io.ObservableInputStream;
import nu.validator.io.StreamBoundException;
import nu.validator.io.StreamObserver;
import nu.validator.io.SystemIdIOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import io.mola.galimatias.URL;
import io.mola.galimatias.GalimatiasParseException;
/**
* @version $Id: PrudentHttpEntityResolver.java,v 1.1 2005/01/08 08:11:26
* hsivonen Exp $
* @author hsivonen
*/
@SuppressWarnings("deprecation") public class PrudentHttpEntityResolver
implements EntityResolver {
private static final Logger log4j = Logger.getLogger(PrudentHttpEntityResolver.class);
private static HttpClient client;
private static int maxRequests;
private long sizeLimit;
private final ErrorHandler errorHandler;
private int requestsLeft;
private boolean allowRnc = false;
private boolean allowHtml = false;
private boolean allowXhtml = false;
private boolean acceptAllKnownXmlTypes = false;
private boolean allowGenericXml = true;
private final ContentTypeParser contentTypeParser;
private String userAgent;
private HttpServletRequest request;
/**
* Sets the timeouts of the HTTP client.
*
* @param connectionTimeout
* timeout until connection established in milliseconds. Zero
* means no timeout.
* @param socketTimeout
* timeout for waiting for data in milliseconds. Zero means no
* timeout.
* @param maxRequests
* maximum number of connections to a particular host
*/
public static void setParams(int connectionTimeout, int socketTimeout,
int maxRequests) {
PrudentHttpEntityResolver.maxRequests = maxRequests;
PoolingHttpClientConnectionManager phcConnMgr;
Registry<ConnectionSocketFactory> registry = //
RegistryBuilder.<ConnectionSocketFactory> create() //
.register("http", PlainConnectionSocketFactory.getSocketFactory()) //
.register("https", SSLConnectionSocketFactory.getSocketFactory()) //
.build();
HttpClientBuilder builder = HttpClients.custom();
builder.setRedirectStrategy(new LaxRedirectStrategy());
builder.setMaxConnPerRoute(maxRequests);
builder.setMaxConnTotal(
Integer.parseInt(System.getProperty("nu.validator.servlet.max-total-connections","200")));
if ("true".equals(System.getProperty(
"nu.validator.xml.promiscuous-ssl", "true"))) { //
try {
SSLContext promiscuousSSLContext = new SSLContextBuilder() //
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
}).build();
builder.setSslcontext(promiscuousSSLContext);
HostnameVerifier verifier = //
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SSLConnectionSocketFactory promiscuousSSLConnSocketFactory = //
new SSLConnectionSocketFactory(promiscuousSSLContext, verifier);
registry = RegistryBuilder.<ConnectionSocketFactory> create() //
.register("https", promiscuousSSLConnSocketFactory) //
.register("http",
PlainConnectionSocketFactory.getSocketFactory()) //
.build();
} catch (KeyManagementException | KeyStoreException
| NoSuchAlgorithmException | NumberFormatException e) {
e.printStackTrace();
}
}
phcConnMgr = new PoolingHttpClientConnectionManager(registry);
phcConnMgr.setDefaultMaxPerRoute(maxRequests);
phcConnMgr.setMaxTotal(200);
builder.setConnectionManager(phcConnMgr);
RequestConfig.Builder config = RequestConfig.custom();
config.setCircularRedirectsAllowed(true);
config.setMaxRedirects(
Integer.parseInt(System.getProperty("nu.validator.servlet.max-redirects","20")));
config.setConnectTimeout(connectionTimeout);
config.setCookieSpec(CookieSpecs.BEST_MATCH);
config.setSocketTimeout(socketTimeout);
config.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
client = builder.setDefaultRequestConfig(config.build()).build();
}
public void setUserAgent(String ua) {
userAgent = ua;
}
public PrudentHttpEntityResolver(long sizeLimit, boolean laxContentType,
ErrorHandler errorHandler, HttpServletRequest request) {
this.request = request;
this.sizeLimit = sizeLimit;
this.requestsLeft = maxRequests;
this.errorHandler = errorHandler;
this.contentTypeParser = new ContentTypeParser(errorHandler,
laxContentType, this.allowRnc, this.allowHtml, this.allowXhtml,
this.acceptAllKnownXmlTypes, this.allowGenericXml);
}
public PrudentHttpEntityResolver(long sizeLimit, boolean laxContentType,
ErrorHandler errorHandler) {
this(sizeLimit, laxContentType, errorHandler, null);
}
/**
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,
* java.lang.String)
*/
@Override
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException {
if (requestsLeft > -1) {
if (requestsLeft == 0) {
throw new IOException(
"Number of permitted HTTP requests exceeded.");
} else {
requestsLeft--;
}
}
HttpGet m = null;
try {
URL url = null;
try {
url = URL.parse(systemId);
} catch (GalimatiasParseException e) {
IOException ioe = (IOException) new IOException(e.getMessage()).initCause(e);
SAXParseException spe = new SAXParseException(e.getMessage(),
publicId, systemId, -1, -1, ioe);
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw ioe;
}
String scheme = url.scheme();
if (!("http".equals(scheme) || "https".equals(scheme))) {
String msg = "Unsupported URI scheme: \u201C" + scheme
+ "\u201D.";
SAXParseException spe = new SAXParseException(msg, publicId,
systemId, -1, -1, new IOException(msg));
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
systemId = url.toString();
try {
m = new HttpGet(systemId);
} catch (IllegalArgumentException e) {
SAXParseException spe = new SAXParseException(
e.getMessage(),
publicId,
systemId,
-1,
-1,
(IOException) new IOException(e.getMessage()).initCause(e));
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
m.setHeader("User-Agent", userAgent);
m.setHeader("Accept", buildAccept());
m.setHeader("Accept-Encoding", "gzip");
if (request != null && request.getAttribute(
"http://validator.nu/properties/accept-language") != null) {
m.setHeader("Accept-Language", (String) request.getAttribute(
"http://validator.nu/properties/accept-language"));
}
log4j.info(systemId);
try {
if (url.port() > 65535) {
throw new IOException(
"Port number must be less than 65536.");
}
} catch (NumberFormatException e) {
throw new IOException(
"Port number must be less than 65536.");
}
HttpResponse response = client.execute(m);
boolean ignoreResponseStatus = false;
if (request != null && request.getAttribute(
"http://validator.nu/properties/ignore-response-status") != null) {
ignoreResponseStatus = (boolean) request.getAttribute(
"http://validator.nu/properties/ignore-response-status");
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200 && !ignoreResponseStatus) {
String msg = "HTTP resource not retrievable."
+ " The HTTP status from the remote server was: "
+ statusCode + ".";
SAXParseException spe = new SAXParseException(msg, publicId,
m.getURI().toString(), -1, -1,
new SystemIdIOException(m.getURI().toString(), msg));
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw new ResourceNotRetrievableException(
String.format("%s: %s", m.getURI().toString(), msg));
}
HttpEntity entity = response.getEntity();
long len = entity.getContentLength();
if (sizeLimit > -1 && len > sizeLimit) {
SAXParseException spe = new SAXParseException(
"Resource size exceeds limit.",
publicId,
m.getURI().toString(),
-1,
-1,
new StreamBoundException("Resource size exceeds limit."));
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
TypedInputSource is;
org.apache.http.Header ct = response.getFirstHeader("Content-Type");
String contentType = null;
final String baseUri = m.getURI().toString();
if (ct != null) {
contentType = ct.getValue();
}
is = contentTypeParser.buildTypedInputSource(baseUri, publicId,
contentType);
Header cl = response.getFirstHeader("Content-Language");
if (cl != null) {
is.setLanguage(cl.getValue().trim());
}
Header xuac = response.getFirstHeader("X-UA-Compatible");
if (xuac != null) {
String val = xuac.getValue().trim();
if (!"ie=edge".equalsIgnoreCase(val)) {
SAXParseException spe = new SAXParseException(
"X-UA-Compatible HTTP header must have the value \u201CIE=edge\u201D,"
+ " was \u201C" + val + "\u201D.",
publicId, systemId, -1, -1);
errorHandler.error(spe);
}
}
Header csp = response.getFirstHeader("Content-Security-Policy");
if (csp != null) {
try {
ContentSecurityPolicy.THE_INSTANCE.checkValid(csp.getValue().trim());
} catch (DatatypeException e) {
SAXParseException spe = new SAXParseException(
"Content-Security-Policy HTTP header: "
+ e.getMessage(), publicId, systemId, -1,
-1);
Html5DatatypeException ex5 = (Html5DatatypeException) e;
if (ex5.isWarning()) {
errorHandler.warning(spe);
} else {
errorHandler.error(spe);
}
}
}
final HttpGet meth = m;
InputStream stream = entity.getContent();
if (sizeLimit > -1) {
stream = new BoundedInputStream(stream, sizeLimit, baseUri);
}
Header ce = response.getFirstHeader("Content-Encoding");
if (ce != null) {
String val = ce.getValue().trim();
if ("gzip".equalsIgnoreCase(val)
|| "x-gzip".equalsIgnoreCase(val)) {
stream = new GZIPInputStream(stream);
if (sizeLimit > -1) {
stream = new BoundedInputStream(stream, sizeLimit,
baseUri);
}
}
}
is.setByteStream(new ObservableInputStream(stream,
new StreamObserver() {
private final Logger log4j = Logger.getLogger("nu.validator.xml.PrudentEntityResolver.StreamObserver");
private boolean released = false;
@Override
public void closeCalled() {
log4j.debug("closeCalled");
if (!released) {
log4j.debug("closeCalled, not yet released");
released = true;
try {
meth.releaseConnection();
} catch (Exception e) {
log4j.debug(
"closeCalled, releaseConnection", e);
}
}
}
@Override
public void exceptionOccurred(Exception ex)
throws IOException {
if (!released) {
released = true;
try {
meth.abort();
} catch (Exception e) {
log4j.debug("exceptionOccurred, abort", e);
} finally {
try {
meth.releaseConnection();
} catch (Exception e) {
log4j.debug(
"exceptionOccurred, releaseConnection",
e);
}
}
}
if (ex instanceof SystemIdIOException) {
throw (SystemIdIOException) ex;
} else if (ex instanceof IOException) {
IOException ioe = (IOException) ex;
throw new SystemIdIOException(baseUri,
ioe.getMessage(), ioe);
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new RuntimeException(
"API contract violation. Wrong exception type.",
ex);
}
}
@Override
public void finalizerCalled() {
if (!released) {
released = true;
try {
meth.abort();
} catch (Exception e) {
log4j.debug("finalizerCalled, abort", e);
} finally {
try {
meth.releaseConnection();
} catch (Exception e) {
log4j.debug(
"finalizerCalled, releaseConnection",
e);
}
}
}
}
}));
return is;
} catch (IOException | RuntimeException | SAXException e) {
if (m != null) {
try {
m.abort();
} catch (Exception ex) {
log4j.debug("abort", ex);
} finally {
try {
m.releaseConnection();
} catch (Exception ex) {
log4j.debug("releaseConnection", ex);
}
}
}
throw e;
}
}
/**
* @return Returns the allowRnc.
*/
public boolean isAllowRnc() {
return allowRnc;
}
/**
* @param allowRnc
* The allowRnc to set.
*/
public void setAllowRnc(boolean allowRnc) {
this.allowRnc = allowRnc;
this.contentTypeParser.setAllowRnc(allowRnc);
}
/**
* @param allowHtml
*/
public void setAllowHtml(boolean allowHtml) {
this.allowHtml = allowHtml;
this.contentTypeParser.setAllowHtml(allowHtml);
}
/**
* Returns the acceptAllKnownXmlTypes.
*
* @return the acceptAllKnownXmlTypes
*/
public boolean isAcceptAllKnownXmlTypes() {
return acceptAllKnownXmlTypes;
}
/**
* Sets the acceptAllKnownXmlTypes.
*
* @param acceptAllKnownXmlTypes
* the acceptAllKnownXmlTypes to set
*/
public void setAcceptAllKnownXmlTypes(boolean acceptAllKnownXmlTypes) {
this.acceptAllKnownXmlTypes = acceptAllKnownXmlTypes;
this.contentTypeParser.setAcceptAllKnownXmlTypes(acceptAllKnownXmlTypes);
}
/**
* Returns the allowGenericXml.
*
* @return the allowGenericXml
*/
public boolean isAllowGenericXml() {
return allowGenericXml;
}
/**
* Sets the allowGenericXml.
*
* @param allowGenericXml
* the allowGenericXml to set
*/
public void setAllowGenericXml(boolean allowGenericXml) {
this.allowGenericXml = allowGenericXml;
this.contentTypeParser.setAllowGenericXml(allowGenericXml);
}
/**
* Returns the allowXhtml.
*
* @return the allowXhtml
*/
public boolean isAllowXhtml() {
return allowXhtml;
}
/**
* Sets the allowXhtml.
*
* @param allowXhtml
* the allowXhtml to set
*/
public void setAllowXhtml(boolean allowXhtml) {
this.allowXhtml = allowXhtml;
this.contentTypeParser.setAllowXhtml(allowXhtml);
}
private String buildAccept() {
return "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
}
/**
* Returns the allowHtml.
*
* @return the allowHtml
*/
public boolean isAllowHtml() {
return allowHtml;
}
public boolean isOnlyHtmlAllowed() {
return !isAllowGenericXml() && !isAllowRnc() && !isAllowXhtml();
}
public class ResourceNotRetrievableException extends SAXException {
public ResourceNotRetrievableException(String message) {
super(message);
}
}
}
| mit |
SonechkaGodovykh/FiniteAutomaton | src/com/sonechka/graph/Automaton.java | 2723 | package com.sonechka.graph;
import java.util.List;
import java.util.Random;
/**
* Created by Sonechka on 5/15/15.
*/
public class Automaton {
private Graph graph;
public Automaton(){
graph = new Graph();
graph.addVertex(true, false);
}
public boolean addSymbol(int sourceVertex, int sinkVertex, String symbols, boolean isAnysymbol){
if(sourceVertex >= graph.vertexCount() || sourceVertex < 0 || sinkVertex < 0){
return false;
}
if(sinkVertex >= graph.vertexCount()){
graph.addVertex(false, false);
sinkVertex = graph.vertexCount() - 1;
}
return graph.addEdge(isAnysymbol, symbols, sourceVertex, sinkVertex);
}
public boolean addDisjunction(int sourceVertex, int sinkVertex, List<String> symbols, int numberOfAnySymbol){
if(sourceVertex < 0 || sinkVertex < 0) {
return false;
}
if(sinkVertex > graph.vertexCount()){
graph.addVertex(false, false);
sinkVertex = graph.vertexCount() - 1;
}
boolean result = true;
for(int i = 0; i < symbols.size(); i++){
result = result && addSymbol(sourceVertex, sinkVertex, symbols.get(i), i == numberOfAnySymbol);
}
return result;
}
public boolean addCleeneStar(int sourceVertex, int sinkVertex){
if(sourceVertex < 0 && sinkVertex < 0)
return false;
if(sourceVertex > graph.vertexCount() || sinkVertex > graph.vertexCount()){
return false;
}
return graph.addEdge(false, "", sourceVertex, sinkVertex);
}
public boolean setFinalState(int state){
return graph.setStateAsFinal(state);
}
public void drawAutomaton(){
graph.drawGraph();
}
public String generateWord(){
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
int i = 0;
while(true){
if(this.graph.graphStructure.get(i).getKey().getFinalState()){ //if we reached the final state, we return
// appended string with chance 1/(count of source edges + 1)
int count = random.nextInt(this.graph.graphStructure.get(i).getValue().size() + 1);
if(count == this.graph.graphStructure.get(i).getValue().size()) {
return stringBuilder.toString();
}
}
int next = random.nextInt(this.graph.graphStructure.get(i).getValue().size());
stringBuilder.append(this.graph.graphStructure.get(i).getValue().get(next).toString());
i = this.graph.graphStructure.get(i).getValue().get(next).getSink();
}
}
}
| mit |
eXsio/congregation-assistant | src/main/java/pl/exsio/ca/app/report/terraincard/view/TerrainCardsView.java | 6587 | /*
* The MIT License
*
* Copyright 2015 exsio.
*
* 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 pl.exsio.ca.app.report.terraincard.view;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import pl.exsio.ca.app.report.terraincard.model.TerrainCardCell;
import pl.exsio.ca.app.report.terraincard.model.TerrainCardColumn;
import pl.exsio.ca.app.report.terraincard.model.TerrainCardPage;
import pl.exsio.ca.app.report.terraincard.viewmodel.TerrainCardViewModel;
import pl.exsio.ca.model.ServiceGroup;
import pl.exsio.ca.model.TerrainType;
import pl.exsio.jin.annotation.TranslationPrefix;
import static pl.exsio.jin.translationcontext.TranslationContext.t;
/**
*
* @author exsio
*/
@TranslationPrefix("ca.report.terrain_card")
public class TerrainCardsView extends AbstractPdfView {
private TerrainCardViewModel viewModel;
private static final int START_COL = 0;
private static final int START_ROW = 3;
private static final String BACKGROUND_PATH = "/img/back.png";
private static final Color BACK_COLOR = new Color(244, 206, 138);
@Override
protected void buildPdfDocument(Map<String, Object> map, Document dcmnt, PdfWriter writer, HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
PdfContentByte canvas = writer.getDirectContentUnder();
Image back = Image.getInstance(getClass().getClassLoader().getResource(BACKGROUND_PATH));
back.scaleAbsolute(PageSize.A4.getWidth(),PageSize.A4.getHeight());
back.setAbsolutePosition(0, 0);
canvas.addImage(back);
LinkedList<TerrainCardPage> pages = this.viewModel.getPages(map);
int pagesCount = pages.size();
for (int i = 0; i < pagesCount; i++) {
dcmnt.add(this.buildTable(pages.get(i)));
if (i < pages.size() - 1) {
dcmnt.newPage();
canvas.addImage(back);
}
}
}
private Element buildTable(TerrainCardPage page) throws Exception {
Table table = new Table(this.viewModel.getTableColumnsNo() * 2);
table.setBorderWidth(0);
table.setPadding(0.565f);
table.setSpacing(0.7f);
table.setWidth(100);
table.setAlignment(Element.ALIGN_RIGHT);
int currentCol = START_COL;
int currentRow = START_ROW;
for (int i = 0; i < page.getColumns().size(); i++) {
TerrainCardColumn column = page.getColumns().get(i);
table.addCell(this.getColumnSpacingCell(4), 0, currentCol);
table.addCell(this.getColumnTitleCell(column.getTerrainName()), 1, currentCol);
table.addCell(this.getColumnSpacingCell(3), 2, currentCol);
for (int j = 0; j < column.getCells().size(); j++) {
TerrainCardCell cell = column.getCells().get(j);
table.addCell(this.getNotificationCell(" "+cell.getGroup(), 2, 6), currentRow, currentCol);
table.addCell(this.getNotificationCell(cell.getFrom(), 1, 7), currentRow + 1, currentCol);
table.addCell(this.getNotificationCell(cell.getTo(), 1, 7), currentRow + 1, currentCol + 1);
currentRow += 2;
}
currentCol += 2;
currentRow = START_ROW;
}
return table;
}
private Cell getNotificationCell(String groupName, int colSpan, int size) throws Exception {
Paragraph p = new Paragraph(groupName, this.getFont());
if (groupName.trim().equalsIgnoreCase(TerrainCardViewModel.EMPTY_CELL_VALUE)) {
p.getFont().setColor(BACK_COLOR);
}
p.getFont().setSize(size);
Cell cell = new Cell(p);
cell.setBorder(0);
cell.setColspan(colSpan);
return cell;
}
private Cell getColumnSpacingCell(int size) throws Exception {
Paragraph p = new Paragraph(TerrainCardViewModel.EMPTY_CELL_VALUE, this.getFont());
p.getFont().setColor(BACK_COLOR);
p.getFont().setSize(size);
Cell cell = new Cell(p);
cell.setBorder(0);
return cell;
}
private Cell getColumnTitleCell(String title) throws Exception {
Paragraph p = new Paragraph(" "+title, this.getFont());
int size = 8;
if(title.length() > 18) {
size = 6;
}
p.getFont().setSize(size);
p.getFont().setStyle(Font.ITALIC);
p.setSpacingAfter(2);
p.setSpacingBefore(2);
Cell cell = new Cell(p);
cell.setColspan(2);
cell.setBorder(0);
return cell;
}
private Font getFont() throws Exception {
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
Font f = new Font(bf, 10, Font.NORMAL);
return f;
}
public void setViewModel(TerrainCardViewModel viewModel) {
this.viewModel = viewModel;
}
}
| mit |
Azure/azure-sdk-for-java | sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/src/main/java/com/azure/resourcemanager/vmwarecloudsimple/fluent/models/ResourcePoolInner.java | 3345 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.vmwarecloudsimple.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Resource pool model. */
@JsonFlatten
@Fluent
public class ResourcePoolInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ResourcePoolInner.class);
/*
* resource pool id (privateCloudId:vsphereId)
*/
@JsonProperty(value = "id", required = true)
private String id;
/*
* Azure region
*/
@JsonProperty(value = "location", access = JsonProperty.Access.WRITE_ONLY)
private String location;
/*
* {ResourcePoolName}
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private String name;
/*
* The Private Cloud Id
*/
@JsonProperty(value = "privateCloudId", access = JsonProperty.Access.WRITE_ONLY)
private String privateCloudId;
/*
* {resourceProviderNamespace}/{resourceType}
*/
@JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
private String type;
/*
* Hierarchical resource pool name
*/
@JsonProperty(value = "properties.fullName", access = JsonProperty.Access.WRITE_ONLY)
private String fullName;
/**
* Get the id property: resource pool id (privateCloudId:vsphereId).
*
* @return the id value.
*/
public String id() {
return this.id;
}
/**
* Set the id property: resource pool id (privateCloudId:vsphereId).
*
* @param id the id value to set.
* @return the ResourcePoolInner object itself.
*/
public ResourcePoolInner withId(String id) {
this.id = id;
return this;
}
/**
* Get the location property: Azure region.
*
* @return the location value.
*/
public String location() {
return this.location;
}
/**
* Get the name property: {ResourcePoolName}.
*
* @return the name value.
*/
public String name() {
return this.name;
}
/**
* Get the privateCloudId property: The Private Cloud Id.
*
* @return the privateCloudId value.
*/
public String privateCloudId() {
return this.privateCloudId;
}
/**
* Get the type property: {resourceProviderNamespace}/{resourceType}.
*
* @return the type value.
*/
public String type() {
return this.type;
}
/**
* Get the fullName property: Hierarchical resource pool name.
*
* @return the fullName value.
*/
public String fullName() {
return this.fullName;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (id() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property id in model ResourcePoolInner"));
}
}
}
| mit |
alexwang3322/bs-android | src/main/java/com/bugsnag/android/Exceptions.java | 2649 | package com.bugsnag.android;
import android.support.annotation.NonNull;
import java.io.IOException;
/**
* Unwrap and serialize exception information and any "cause" exceptions.
*/
class Exceptions implements JsonStream.Streamable {
private final Configuration config;
private Throwable exception;
private String name;
private String message;
private StackTraceElement[] frames;
Exceptions(Configuration config, Throwable exception) {
this.config = config;
this.exception = exception;
}
Exceptions(Configuration config, String name, String message, StackTraceElement[] frames) {
this.config = config;
this.name = name;
this.message = message;
this.frames = frames;
}
@Override
public void toStream(@NonNull JsonStream writer) throws IOException {
writer.beginArray();
if(exception != null) {
// Unwrap any "cause" exceptions
Throwable currentEx = exception;
while(currentEx != null) {
if(config.isStandardExceptionFormat) {
exceptionToStreamStandard(writer, currentEx.getClass().getName(), currentEx.getLocalizedMessage(), currentEx);
} else {
exceptionToStream(writer, currentEx.getClass().getName(), currentEx.getLocalizedMessage(), currentEx.getStackTrace());
}
currentEx = currentEx.getCause();
}
} else {
exceptionToStream(writer, name, message, frames);
}
writer.endArray();
}
private void exceptionToStreamStandard(JsonStream writer, String name, String message, Throwable throwable ) throws IOException {
StackTraceElement[] elements = throwable.getStackTrace();
StringBuffer err = new StringBuffer();
for (int i = 0; i < elements.length; i++) {
err.append("\tat ");
err.append(elements[i].toString());
err.append("\n");
}
writer.beginObject();
writer.name("errorClass").value(name);
writer.name("message").value(message);
writer.name("stacktrace").value(err.toString());
writer.endObject();
}
private void exceptionToStream(JsonStream writer, String name, String message, StackTraceElement[] frames) throws IOException {
Stacktrace stacktrace = new Stacktrace(config, frames);
writer.beginObject();
writer.name("errorClass").value(name);
writer.name("message").value(message);
writer.name("stacktrace").value(stacktrace);
writer.endObject();
}
}
| mit |
alanmtz1503/InCense | src/edu/incense/android/ui/SensingNotification.java | 3433 | /**
*
*/
package edu.incense.android.ui;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import edu.incense.android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
/**
* @author mxpxgx
*
*/
public class SensingNotification {
private Context context;
private NotificationManager manager;
private List<String> activeSensors;
private final static String CONTENT_TITLE = "InCense is active";
private final static String CONTENT_HEADER = "Sensors: ";
private final static int NOTIFICATION_ID = 1524;
public SensingNotification(Context context) {
this.context = context;
manager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
activeSensors = new ArrayList<String>();
}
private String createNotificationContent() {
StringBuilder sb = new StringBuilder(CONTENT_HEADER);
String div = ", ", end = ".";
for (String sensor : activeSensors) {
sb.append(sensor.toLowerCase() + div);
}
sb.replace(sb.length() - div.length(), sb.length(), end);
return sb.toString();
}
private Notification createNotification() {
int icon = R.drawable.bullseye;
CharSequence tickerText = CONTENT_TITLE;
long when = System.currentTimeMillis();
return new Notification(icon, tickerText, when);
}
private PendingIntent createNotificationIntent() {
// TODO CHANGE THIS ACTIVITy
Intent intent = new Intent(context, RecordActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
return pendingIntent;
}
public void add(String sensor) {
if(!activeSensors.contains(sensor)){
activeSensors.add(sensor);
}
}
public void remove(String sensor) {
activeSensors.remove(sensor);
}
public void updateNotificationWith(String sensor) {
add(sensor);
updateNotification();
}
public void updateNotificationWithout(String sensor) {
remove(sensor);
updateNotification();
}
public void updateNotification() {
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(notificationUpdater);
}
private Runnable notificationUpdater = new Runnable() {
public void run() {
if (activeSensors.isEmpty()) {
manager.cancel(NOTIFICATION_ID);
} else {
// Title for the expanded status
String contentTitle = CONTENT_TITLE;
// Text to display in the extended status window
String contentText = createNotificationContent();
// Intent to launch an activity when the extended text is
// clicked
PendingIntent pendingIntent = createNotificationIntent();
Notification notification = createNotification();
notification.setLatestEventInfo(context, contentTitle,
contentText, pendingIntent);
manager.notify(NOTIFICATION_ID, notification);
}
}
};
}
| mit |
mikerandrup/MabLidsAndroid | app/src/main/java/com/mikerandrup/essaycomposable/components/dynamicwords/DynamicWordComponent.java | 640 | package com.mikerandrup.essaycomposable.components.dynamicwords;
import com.mikerandrup.essaycomposable.components.BaseComponent;
public class DynamicWordComponent extends BaseComponent {
public DynamicWordComponent() {
value = null;
}
public DynamicWordComponent(String hint) {
hintText = hint;
value = null;
}
protected String hintText = "";
public String getWordType() {
return this.getClass().getSimpleName().toString();
}
public String getWordTypeAndHint() {
return getWordType() + ((hintText=="") ? "" : (" ("+hintText+")"));
}
} | mit |
Skuzzzy/Catal | src/jdbaird/Main.java | 880 | package jdbaird;
import jdbaird.tokens.Token;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
//3.2+32*(45.12+5)+5/14.7 = 1607.38013605
TokenMaker test = new TokenMaker("3+32*(45+5)+5/14");
for(int i = 0; i<test.getTokenList().size();i++){
System.out.print(test.getTokenList().get(i).getContents()+" ");
}
System.out.println("");
ShuntingYard railroad = new ShuntingYard(test.getTokenList());
railroad.algorithm();
ArrayList<Token> out = railroad.getOutputList();
for(int i = 0; i<out.size();i++){
System.out.print(out.get(i).getContents()+" ");
}
PostfixEvaluation check = new PostfixEvaluation(railroad.getOutputList());
System.out.println("");
System.out.println(check.getResult());
}
}
| mit |
highlanderkev/StockExVirtuoso | src/driver/MainAutomatedTest.java | 6067 | package driver;
import book.ProductService;
import client.User;
import client.UserImpl;
import client.UserSim;
import client.UserSimSettings;
import constants.MarketState;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class MainAutomatedTest {
public static CountDownLatch countDownLatch;
public static void main(String[] args) throws Exception {
setupTradingSystem();
automatedTestMode();
}
public synchronized static void simDone() {
countDownLatch.countDown();
}
private static void setupTradingSystem() {
try {
ProductService.getInstance().createProduct("IBM");
ProductService.getInstance().createProduct("CBOE");
ProductService.getInstance().createProduct("GOOG");
ProductService.getInstance().createProduct("AAPL");
ProductService.getInstance().createProduct("GE");
ProductService.getInstance().createProduct("T");
} catch (Exception ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void automatedTestMode() throws Exception {
String name = "REX";
boolean goodName = false;
String error = "";
int errorCount = 0;
do {
name = JOptionPane.showInputDialog(null, error + "Enter your First name", "Name", JOptionPane.INFORMATION_MESSAGE);
if (name == null) {
System.out.println("No Name provided - Defaulting to 'REX'");
name = "REX";
goodName = true;
JOptionPane.showMessageDialog(null, "You have been assigned the default user name of 'REX'", "Default Name", JOptionPane.INFORMATION_MESSAGE);
} else if (name.matches("^[a-zA-Z]+$")) {
goodName = true;
} else {
errorCount++;
if (errorCount >= 3) {
System.out.println("Too many tried - Defaulting to 'REX'");
name = "REX";
goodName = true;
JOptionPane.showMessageDialog(null, "You have been assigned the default user name of 'REX'", "Default Name", JOptionPane.INFORMATION_MESSAGE);
} else {
error = "Names must consist of letters only - please try again.\n\n";
}
}
} while (!goodName);
User user1 = new UserImpl(name.toUpperCase());
try {
user1.connect();
user1.showMarketDisplay();
} catch (Exception ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
String results = JOptionPane.showInputDialog(null,
"Enter simulation duration in seconds\nand click 'OK' to open the market.", 180);
if (results == null) {
System.out.println("Simulation Cancelled");
System.exit(0);
}
int duration = Integer.parseInt(results);
JOptionPane.showMessageDialog(null, "Please add all available Stock Symbols to your Market Display.\n" + ""
+ "Simulation will begin 15 seconds after clicking 'Ok'.",
"Add Products", JOptionPane.INFORMATION_MESSAGE);
///
System.out.println("Simulation starting in 15 seconds...");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
try {
ProductService.getInstance().setMarketState(MarketState.PREOPEN); // Replace PREOPEN with your preresenation of PREOPEN
} catch (Exception ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
///
System.out.println("Simulation starting in 10 seconds...");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
try {
ProductService.getInstance().setMarketState(MarketState.OPEN); // Replace OPEN with your preresenation of OPEN
} catch (Exception ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Simulation starting in 5 seconds...");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
UserSimSettings.addProductData("IBM", 189.40, 189.60, 200);
UserSimSettings.addProductData("CBOE", 28.00, 28.15, 300);
UserSimSettings.addProductData("GOOG", 608.00, 608.75, 500);
UserSimSettings.addProductData("AAPL", 600.00, 601.00, 350);
UserSimSettings.addProductData("GE", 19.55, 19.95, 100);
UserSimSettings.addProductData("T", 34.25, 34.65, 250);
System.out.println("Simulation starting: " + duration + " seconds remain.");
int numSimUsers = 5;
countDownLatch = new CountDownLatch(numSimUsers);
for (int i = 0; i < numSimUsers; i++) {
User u = new UserImpl("SIM" + (i + 1));
UserSim us = new UserSim((duration * 1000), u, false);
new Thread(us).start();
}
try {
countDownLatch.await();
System.out.println("Done Waiting");
ProductService.getInstance().setMarketState(MarketState.CLOSED); // Replace CLOSED with your preresenation of CLOSED
JOptionPane.showMessageDialog(null, "The simulation has completed.",
"Completed", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
Logger.getLogger(MainAutomatedTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| mit |
travis-repos/java-api-wrapper | src/test/java/com/soundcloud/api/ApiWrapperTest.java | 17167 | package com.soundcloud.api;
import static junit.framework.Assert.fail;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.soundcloud.api.fakehttp.FakeHttpLayer;
import com.soundcloud.api.fakehttp.RequestMatcher;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.AuthenticationHandler;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.RequestDirector;
import org.apache.http.client.UserTokenHandler;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URI;
public class ApiWrapperTest {
private ApiWrapper api;
final FakeHttpLayer layer = new FakeHttpLayer();
@Before
public void setup() {
api = new ApiWrapper("invalid", "invalid", URI.create("redirect://me"), null, Env.SANDBOX) {
private static final long serialVersionUID = 12345; // silence warnings
@Override
protected RequestDirector getRequestDirector(HttpRequestExecutor requestExec,
ClientConnectionManager conman,
ConnectionReuseStrategy reustrat,
ConnectionKeepAliveStrategy kastrat,
HttpRoutePlanner rouplan,
HttpProcessor httpProcessor,
HttpRequestRetryHandler retryHandler,
RedirectHandler redirectHandler,
AuthenticationHandler targetAuthHandler,
AuthenticationHandler proxyAuthHandler,
UserTokenHandler stateHandler,
HttpParams params) {
return new RequestDirector() {
@Override
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
throws HttpException, IOException {
return layer.emulateRequest(target, request, context, this);
}
};
}
};
layer.clearHttpResponseRules();
}
@Test(expected = IllegalArgumentException.class)
public void loginShouldThrowIllegalArgumentException() throws Exception {
api.login(null, null);
}
@Test
public void clientCredentialsShouldDefaultToSignupScope() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"04u7h-4cc355-70k3n\",\n" +
" \"expires_in\": 3600,\n" +
" \"scope\": \"signup\",\n" +
" \"refresh_token\": \"04u7h-r3fr35h-70k3n\"\n" +
"}");
Token t = api.clientCredentials();
assertThat(t.access, equalTo("04u7h-4cc355-70k3n"));
assertThat(t.refresh, equalTo("04u7h-r3fr35h-70k3n"));
assertThat(t.scope, equalTo("signup"));
assertTrue(t.signupScoped());
assertNotNull(t.getExpiresIn());
}
@Test(expected = CloudAPI.InvalidTokenException.class)
public void clientCredentialsShouldThrowIfScopeCanNotBeObtained() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"04u7h-4cc355-70k3n\",\n" +
" \"expires_in\": 3600,\n" +
" \"scope\": \"loser\",\n" +
" \"refresh_token\": \"04u7h-r3fr35h-70k3n\"\n" +
"}");
api.clientCredentials("unlimitedammo");
}
@Test
public void exchangeOAuth1Token() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"04u7h-4cc355-70k3n\",\n" +
" \"expires_in\": 3600,\n" +
" \"scope\": \"*\",\n" +
" \"refresh_token\": \"04u7h-r3fr35h-70k3n\"\n" +
"}");
api.exchangeOAuth1Token("oldtoken");
}
@Test(expected = IllegalArgumentException.class)
public void exchangeOAuth1TokenWithEmptyTokenShouldThrow() throws Exception {
api.exchangeOAuth1Token(null);
}
@Test
public void shouldGetTokensWhenLoggingIn() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"04u7h-4cc355-70k3n\",\n" +
" \"expires_in\": 3600,\n" +
" \"scope\": \"*\",\n" +
" \"refresh_token\": \"04u7h-r3fr35h-70k3n\"\n" +
"}");
Token t = api.login("foo", "bar");
assertThat(t.access, equalTo("04u7h-4cc355-70k3n"));
assertThat(t.refresh, equalTo("04u7h-r3fr35h-70k3n"));
assertThat(t.scope, equalTo("*"));
assertNotNull(t.getExpiresIn());
}
@Test
public void shouldGetTokensWhenLoggingInWithNonExpiringScope() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"04u7h-4cc355-70k3n\",\n" +
" \"scope\": \"* non-expiring\"\n" +
"}");
Token t = api.login("foo", "bar", Token.SCOPE_NON_EXPIRING);
assertThat(t.access, equalTo("04u7h-4cc355-70k3n"));
assertThat(t.refresh, is(nullValue()));
assertThat(t.getExpiresIn(), is(nullValue()));
assertThat(t.scoped(Token.SCOPE_NON_EXPIRING), is(true));
assertThat(t.scoped(Token.SCOPE_DEFAULT), is(true));
}
@Test
public void shouldGetTokensWhenLoggingInViaAuthorizationCode() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"04u7h-4cc355-70k3n\",\n" +
" \"expires_in\": 3600,\n" +
" \"scope\": \"*\",\n" +
" \"refresh_token\": \"04u7h-r3fr35h-70k3n\"\n" +
"}");
Token t = api.authorizationCode("code");
assertThat(t.access, equalTo("04u7h-4cc355-70k3n"));
assertThat(t.refresh, equalTo("04u7h-r3fr35h-70k3n"));
assertThat(t.scope, equalTo("*"));
assertNotNull(t.getExpiresIn());
}
@Test
public void shouldGetTokensWhenLoggingInViaAuthorizationCodeAndScope() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"04u7h-4cc355-70k3n\",\n" +
" \"scope\": \"* non-expiring\"\n" +
"}");
Token t = api.authorizationCode("code", Token.SCOPE_NON_EXPIRING);
assertThat(t.access, equalTo("04u7h-4cc355-70k3n"));
assertThat(t.refresh, is(nullValue()));
assertThat(t.scoped(Token.SCOPE_DEFAULT), is(true));
assertThat(t.scoped(Token.SCOPE_NON_EXPIRING), is(true));
assertNull(t.getExpiresIn());
}
@Test(expected = IOException.class)
public void shouldThrowIOExceptionWhenLoginFailed() throws Exception {
layer.addPendingHttpResponse(401, "{\n" +
" \"error\": \"Error!\"\n" +
"}");
api.login("foo", "bar");
}
@Test(expected = IOException.class)
public void shouldThrowIOExceptionWhenInvalidJSONReturned() throws Exception {
layer.addPendingHttpResponse(200, "I'm invalid JSON!");
api.login("foo", "bar");
}
@Test
public void shouldContainInvalidJSONInExceptionMessage() throws Exception {
layer.addPendingHttpResponse(200, "I'm invalid JSON!");
try {
api.login("foo", "bar");
fail("expected IOException");
} catch (IOException e) {
assertThat(e.getMessage(), containsString("I'm invalid JSON!"));
}
}
@Test
public void shouldRefreshToken() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"fr3sh\",\n" +
" \"expires_in\": 3600,\n" +
" \"scope\": null,\n" +
" \"refresh_token\": \"refresh\"\n" +
"}");
api.setToken(new Token("access", "refresh"));
assertThat(api
.refreshToken()
.access,
equalTo("fr3sh"));
}
@Test(expected = IllegalStateException.class)
public void shouldThrowIllegalStateExceptionWhenNoRefreshToken() throws Exception {
api.refreshToken();
}
@Test
public void shouldResolveUris() throws Exception {
HttpResponse r = mock(HttpResponse.class);
StatusLine line = mock(StatusLine.class);
when(line.getStatusCode()).thenReturn(302);
when(r.getStatusLine()).thenReturn(line);
Header location = mock(Header.class);
when(location.getValue()).thenReturn("http://api.soundcloud.com/users/1000");
when(r.getFirstHeader(anyString())).thenReturn(location);
layer.addHttpResponseRule(new RequestMatcher() {
@Override
public boolean matches(HttpRequest request) {
return true;
}
}, r);
assertThat(api.resolve("http://soundcloud.com/crazybob"), is(1000L));
}
@Test(expected = CloudAPI.ResolverException.class)
public void resolveShouldReturnNegativeOneWhenInvalid() throws Exception {
layer.addPendingHttpResponse(404, "Not found");
api.resolve("http://soundcloud.com/nonexisto");
}
@Test
public void shouldGetContent() throws Exception {
layer.addHttpResponseRule("/some/resource?a=1", "response");
assertThat(Http.getString(api.get(Request.to("/some/resource").with("a", "1"))),
equalTo("response"));
}
@Test
public void shouldPostContent() throws Exception {
HttpResponse resp = mock(HttpResponse.class);
layer.addHttpResponseRule("POST", "/foo/something", resp);
assertThat(api.post(Request.to("/foo/something").with("a", 1)),
equalTo(resp));
}
@Test
public void shouldPutContent() throws Exception {
HttpResponse resp = mock(HttpResponse.class);
layer.addHttpResponseRule("PUT", "/foo/something", resp);
assertThat(api.put(Request.to("/foo/something").with("a", 1)),
equalTo(resp));
}
@Test
public void shouldDeleteContent() throws Exception {
HttpResponse resp = mock(HttpResponse.class);
layer.addHttpResponseRule("DELETE", "/foo/something", resp);
assertThat(api.delete(new Request("/foo/something")), equalTo(resp));
}
@Test
public void testGetOAuthHeader() throws Exception {
Header h = ApiWrapper.createOAuthHeader(new Token("foo", "refresh"));
assertThat(h.getName(), equalTo("Authorization"));
assertThat(h.getValue(), equalTo("OAuth foo"));
}
@Test
public void testGetOAuthHeaderNullToken() throws Exception {
Header h = ApiWrapper.createOAuthHeader(null);
assertThat(h.getName(), equalTo("Authorization"));
assertThat(h.getValue(), equalTo("OAuth invalidated"));
}
@Test
public void shouldGenerateUrlWithoutParameters() throws Exception {
assertThat(
api.getURI(new Request("/my-resource"), true, true).toString(),
equalTo("https://api.sandbox-soundcloud.com/my-resource")
);
}
@Test
public void shouldGenerateUrlWithoutSSL() throws Exception {
assertThat(
api.getURI(new Request("/my-resource"), true, false).toString(),
equalTo("http://api.sandbox-soundcloud.com/my-resource")
);
}
@Test
public void shouldGenerateUrlWithParameters() throws Exception {
assertThat(
api.getURI(Request.to("/my-resource").with("foo", "bar"), true, true).toString(),
equalTo("https://api.sandbox-soundcloud.com/my-resource?foo=bar")
);
}
@Test
public void shouldGenerateUrlForWebHost() throws Exception {
assertThat(
api.getURI(Request.to("/my-resource"), false, true).toString(),
equalTo("https://sandbox-soundcloud.com/my-resource")
);
}
@Test
public void shouldGenerateURIForLoginAuthCode() throws Exception {
assertThat(
api.authorizationCodeUrl().toString(),
equalTo("https://sandbox-soundcloud.com/connect"+
"?redirect_uri=redirect%3A%2F%2Fme&client_id=invalid&response_type=code")
);
}
@Test
public void shouldGenerateURIForLoginAuthCodeWithDifferentEndPoint() throws Exception {
assertThat(
api.authorizationCodeUrl(Endpoints.FACEBOOK_CONNECT).toString(),
equalTo("https://sandbox-soundcloud.com/connect/via/facebook"+
"?redirect_uri=redirect%3A%2F%2Fme&client_id=invalid&response_type=code")
);
}
@Test
public void shouldIncludeScopeInAuthorizationUrl() throws Exception {
assertThat(
api.authorizationCodeUrl(Endpoints.FACEBOOK_CONNECT, Token.SCOPE_NON_EXPIRING).toString(),
equalTo("https://sandbox-soundcloud.com/connect/via/facebook"+
"?redirect_uri=redirect%3A%2F%2Fme&client_id=invalid&response_type=code&scope=non-expiring")
);
}
@Test
public void shouldCallTokenStateListenerWhenTokenIsInvalidated() throws Exception {
CloudAPI.TokenListener listener = mock(CloudAPI.TokenListener.class);
api.setTokenListener(listener);
final Token old = api.getToken();
api.invalidateToken();
verify(listener).onTokenInvalid(old);
}
@Test
public void invalidateTokenShouldTryToGetAlternativeToken() throws Exception {
CloudAPI.TokenListener listener = mock(CloudAPI.TokenListener.class);
final Token cachedToken = new Token("new", "fresh");
api.setTokenListener(listener);
when(listener.onTokenInvalid(api.getToken())).thenReturn(cachedToken);
assertThat(api.invalidateToken(), equalTo(cachedToken));
}
@Test
public void invalidateTokenShouldReturnNullIfNoListenerAvailable() throws Exception {
assertThat(api.invalidateToken(), is(nullValue()));
}
@Test
public void shouldCallTokenStateListenerWhenTokenIsRefreshed() throws Exception {
layer.addPendingHttpResponse(200, "{\n" +
" \"access_token\": \"fr3sh\",\n" +
" \"expires_in\": 3600,\n" +
" \"scope\": null,\n" +
" \"refresh_token\": \"refresh\"\n" +
"}");
CloudAPI.TokenListener listener = mock(CloudAPI.TokenListener.class);
api.setToken(new Token("access", "refresh"));
api.setTokenListener(listener);
api.refreshToken();
verify(listener).onTokenRefreshed(api.getToken());
}
@Test
public void shouldSerializeAndDeserializeWrapper() throws Exception {
ApiWrapper wrapper = new ApiWrapper("client", "secret", null, new Token("1", "2"), Env.SANDBOX);
File ser = File.createTempFile("serialized_wrapper", "ser");
wrapper.toFile(ser);
ApiWrapper other = ApiWrapper.fromFile(ser);
assertThat(wrapper.getToken(), equalTo(other.getToken()));
assertThat(wrapper.env, equalTo(other.env));
// make sure we can still use listeners after deserializing
CloudAPI.TokenListener listener = mock(CloudAPI.TokenListener.class);
other.setTokenListener(listener);
final Token old = other.getToken();
other.invalidateToken();
verify(listener).onTokenInvalid(old);
}
@Test
public void testAddScope() throws Exception {
assertThat(ApiWrapper.addScope(new Request(), new String[] { "foo", "bar"}).getParams().get("scope"),
equalTo("foo bar"));
assertFalse(ApiWrapper.addScope(new Request(), new String[] {}).getParams().containsKey("scope"));
assertFalse(ApiWrapper.addScope(new Request(), null).getParams().containsKey("scope"));
}
}
| mit |
guhilling/smart-release-plugin | src/main/java/de/hilling/maven/release/utils/Constants.java | 221 | package de.hilling.maven.release.utils;
/**
* Global constants for plugin
*/
public interface Constants {
String MODULE_BUILD_FILE = "modules-to-build.txt";
String FILES_TO_REVERT = "files-to-revert.txt";
}
| mit |
davalidator/rhombuslibexample | src/com/chumpchange/android/rhombuslibexample/audio/HeadsetStateReceiver.java | 586 | package com.chumpchange.android.rhombuslibexample.audio;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class HeadsetStateReceiver extends BroadcastReceiver {
AudioMonitorActivity activity;
public HeadsetStateReceiver(AudioMonitorActivity activity) {
this.activity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_HEADSET_PLUG)) {
int st = intent.getIntExtra("state", -1);
activity.setDongleReady(st == 1);
}
}
}
| mit |
project-recoin/PybossaTwitterController | src/main/java/sociam/pybossa/twitter/DeleteTweets.java | 1814 | package sociam.pybossa.twitter;
import java.util.List;
import sociam.pybossa.util.TwitterAccount;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
public class DeleteTweets {
public static void main(String[] args) throws InterruptedException {
Boolean res = removeTweets();
if (res == false) {
removeTweets();
} else if (res == true) {
System.out.println("All tweets are deleted");
} else {
System.err.println("Error, exiting the script!!");
}
}
public static Boolean removeTweets() {
Twitter twitter = TwitterAccount.setTwitterAccount(2);
try {
Paging p = new Paging();
p.setCount(200);
List<Status> statuses = twitter.getUserTimeline(p);
while (statuses != null) {
System.out.println("Number of status " + statuses.size());
for (Status status : statuses) {
long id = status.getId();
twitter.destroyStatus(id);
System.out.println("deleted");
Thread.sleep(1000);
}
System.out
.println("Waiting 15 minutes before getting 200 responses");
statuses = twitter.getUserTimeline(p);
Thread.sleep(1000);
}
return true;
} catch (TwitterException e) {
e.printStackTrace();
if (e.exceededRateLimitation()) {
try {
System.err.println("Twitter rate limit is exceeded!");
int waitfor = e.getRateLimitStatus().getSecondsUntilReset();
System.err.println("Waiting for " + (waitfor + 100)
+ " seconds");
Thread.sleep((waitfor * 1000) + 100000);
removeTweets();
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
return null;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
| mit |
macbury/ForgE | core/src/macbury/forge/shaders/uniforms/UniformFog.java | 780 | package macbury.forge.shaders.uniforms;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g3d.utils.RenderContext;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import macbury.forge.level.env.LevelEnv;
import macbury.forge.shaders.utils.BaseUniform;
/**
* Created by macbury on 13.03.15.
*/
public class UniformFog extends BaseUniform {
public final String UNIFORM_FOG_COLOR = "u_fogColor";
@Override
public void defineUniforms() {
define(UNIFORM_FOG_COLOR, Color.class);
}
@Override
public void bind(ShaderProgram shader, LevelEnv env, RenderContext context, Camera camera) {
shader.setUniformf(UNIFORM_FOG_COLOR, env.fogColor);
}
@Override
public void dispose() {
}
}
| mit |
bristy/HackYourself | hackerearth/hacker_earth/Kuliza/FastFuriuous.java | 1191 | /**
* @author: Brajesh
* FastFuriuous .java
*/
import java.io.*;
import java.util.*;
public class FastFuriuous {
public FastFuriuous () {
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
long brian;
long dom;
String[] line = br.readLine().split(" ");
dom = getMax(line, n);
line = br.readLine().split(" ");
brian = getMax(line, n);
if(brian > dom){
System.out.println("Brian\n" + brian);
} else if(dom > brian) {
System.out.println("Don\n" + dom);
} else {
System.out.println("Tie\n" + dom);
}
}
private static long getMax(String[] line, int n) {
long brian = 0;
for(int i = 0; i < n; i++) {
if(i == 0) {
brian = Long.parseLong(line[0]);
} else {
brian = Math.max(brian, Math.abs(Long.parseLong(line[i]) - Long.parseLong(line[i - 1])));
}
}
return brian;
}
}
//FastFuriuous .java
| mit |
ISI-nc/sql2o-dao | src/main/java/nc/isi/slq2o_dao/services/Sql2oDbProviderImpl.java | 1139 | package nc.isi.slq2o_dao.services;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import javax.sql.DataSource;
import org.sql2o.Sql2o;
import org.sql2o.converters.Convert;
import org.sql2o.converters.Converter;
import com.google.common.collect.Maps;
/**
* Implรฉmentation de {@link Sql2oDbProvider} se connectant ร une base Oracle
*
* @author jmaltat
*
*/
public class Sql2oDbProviderImpl implements Sql2oDbProvider {
private final Map<DataSource, Sql2o> dataSourceToSql2o = Maps
.newConcurrentMap();
public Sql2oDbProviderImpl(Map<Class, Converter> converters)
throws SQLException {
for (Entry<Class, Converter> converter : converters.entrySet()) {
Convert.registerConverter(converter.getKey(), converter.getValue());
}
}
@Override
public Sql2o provide(DataSource dataSource) {
return initSql2o(dataSource);
}
private synchronized Sql2o initSql2o(DataSource dataSource) {
Sql2o sql2o = dataSourceToSql2o.get(dataSource);
if (sql2o != null) {
return sql2o;
}
sql2o = new Sql2o(dataSource);
dataSourceToSql2o.put(dataSource, sql2o);
return sql2o;
}
}
| mit |
lossurdo/JDF | src/main/java/com/jdf/security/JDFSecurity.java | 400 | package com.jdf.security;
/**
* Interface implementada pelos objetos de tela para controle de seguranรงa
* @author rafael-lossurdo
* @since 22/04/2009
*/
public interface JDFSecurity {
/**
* Verifica permissรฃo do usuรกrio logado
* @param object Objeto a ser verificado
* @param action Aรงรฃo a ser verificada
*/
public void verifyPermission(String object, String action);
}
| mit |
hockeyhurd/HCoreLib | com/hockeyhurd/hcorelib/api/math/VectorHelper.java | 2410 | package com.hockeyhurd.hcorelib.api.math;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3i;
/**
* Helper class for converting common vectors.
*
* @author hockeyhurd
* @version 5/12/2016.
*/
public final class VectorHelper {
private VectorHelper() {
}
/**
* Function to get Vector3i from Vec3i.
*
* @param vec3i Vec3i.
* @return Vector3i.
*/
public static Vector3<Integer> toVector3i(Vec3i vec3i) {
return vec3i != null ? new Vector3<Integer>(vec3i.getX(), vec3i.getY(), vec3i.getZ()) : new Vector3<Integer>();
}
/**
* Function to get Vector3i from BlockPos.
*
* @param pos BlockPos.
* @return Vector3i.
*/
public static Vector3<Integer> toVector3i(BlockPos pos) {
return pos != null ? new Vector3<Integer>(pos.getX(), pos.getY(), pos.getZ()) : null;
}
/**
* Function to get Vector3i from x, y, z.
*
* @param x int.
* @param y int.
* @param z int.
* @return Vector3i.
*/
public static Vector3<Integer> toVector3i(int x, int y, int z) {
return new Vector3<Integer>(x, y, z);
}
/**
* Function to get Vec3i from Vector3i.
*
* @param vec Vector3i.
* @return Vec3i.
*/
public static Vec3i toVec3i(Vector3<Integer> vec) {
return vec != null ? new Vec3i(vec.x, vec.y, vec.z) : Vec3i.NULL_VECTOR;
}
/**
* Function to get Vec3i from BlockPos.
*
* @param pos BlockPos.
* @return Vec3i.
*/
public static Vec3i toVec3i(BlockPos pos) {
return pos != null ? pos : Vec3i.NULL_VECTOR;
}
/**
* Function to get Vec3i from x, y, z.
*
* @param x int.
* @param y int.
* @param z int.
* @return Vec3i.
*/
public static Vec3i toVec3i(int x, int y, int z) {
return new Vec3i(x, y, z);
}
/**
* Function to get BlockPos from Vector3i.
*
* @param vec Vector3i.
* @return BlockPos.
*/
public static BlockPos toBlockPos(Vector3<Integer> vec) {
return vec != null ? new BlockPos(vec.x, vec.y, vec.z) : new BlockPos(0, 0, 0);
}
/**
* Function to get BlockPos from Vec3i.
*
* @param vec3i Vec3i.
* @return BlockPos.
*/
public static BlockPos toBlockPos(Vec3i vec3i) {
return vec3i != null ? new BlockPos(vec3i) : new BlockPos(0, 0, 0);
}
/**
* Function to get BlockPos from x, y, z.
*
* @param x int.
* @param y int.
* @param z int.
* @return BlockPos.
*/
public static BlockPos toBlockPos(int x, int y, int z) {
return new BlockPos(x, y, z);
}
}
| mit |
brucevsked/vskeddemolist | vskeddemos/mavenproject/springboot2list/springbootkafka/src/main/java/com/vsked/service/kafka/FootBallService.java | 652 | package com.vsked.service.kafka;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class FootBallService implements SaveDataInterface{
private static final Logger log = LoggerFactory.getLogger(FootBallService.class);
@Override
public int saveData(Map<String, Object> inputData) {
try {
log.info("-------------start-----------------FootBall"+inputData.get("count"));
Thread.sleep(6000);
log.info("-------------end-----------------FootBall"+inputData.get("count"));
}catch(Exception e) {
}
return 0;
}
}
| mit |
Softhouse/orchid | se.softhouse.garden.orchid.spring/src/test/java/se/softhouse/garden/orchid/text/TestOrchidMessageSource.java | 6464 | package se.softhouse.garden.orchid.text;
import static se.softhouse.garden.orchid.commons.text.OrchidMessage.arg;
import static se.softhouse.garden.orchid.spring.text.OrchidMessageSource.code;
import java.util.Locale;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import se.softhouse.garden.orchid.commons.text.OrchidMessageArgumentCode;
import se.softhouse.garden.orchid.commons.text.OrchidMessageCode;
import se.softhouse.garden.orchid.spring.text.OrchidReloadableResourceBundleMessageSource;
public class TestOrchidMessageSource {
@Before
public void setup() {
Locale.setDefault(Locale.US);
}
@Test
public void testMessageSource() {
OrchidReloadableResourceBundleMessageSource ms = new OrchidReloadableResourceBundleMessageSource();
ms.setBasename("test");
ms.setUseCodeAsDefaultMessage(true);
Assert.assertEquals("FileTest message", ms.getMessage("msg0", (Object[]) null, Locale.getDefault()));
Assert.assertEquals("FileTest message 1", ms.getMessage("msg1", new Object[] { 1 }, Locale.getDefault()));
Assert.assertEquals("FileTest message 002 with name Micke",
ms.getMessage("msg2", new Object[] { arg(TestArguments.NAME, "Micke").arg(TestArguments.ID, 2) }, Locale.getDefault()));
Assert.assertEquals("FileTest message 02 using name Micke",
ms.getMessage("msg.3", new Object[] { arg(TestArguments.NAME, "Micke").arg(TestArguments.ID, 2) }, Locale.getDefault()));
}
@Test
public void testMessageSourceResolvable() {
OrchidReloadableResourceBundleMessageSource ms = new OrchidReloadableResourceBundleMessageSource();
ms.setBasename("test");
ms.setUseCodeAsDefaultMessage(true);
Assert.assertEquals("x", ms.getMessage(code("x"), Locale.getDefault()));
Assert.assertEquals("y", ms.getMessage(code("x", "y"), Locale.getDefault()));
Assert.assertEquals("FileTest message", ms.getMessage(code(TestMessages.MSG0), Locale.getDefault()));
Assert.assertEquals("FileTest message 1", ms.getMessage(code(TestMessages.MSG1).arg(TestArguments.ID, 1), Locale.getDefault()));
Assert.assertEquals("FileTest message 002 with name Micke",
ms.getMessage(code(TestMessages.MSG2).arg(TestArguments.NAME, "Micke").arg(TestArguments.ID, 2), Locale.getDefault()));
Assert.assertEquals("FileTest message 02 using name Micke",
ms.getMessage(code(TestMessages.MSG_3).arg(TestArguments.NAME, "Micke").arg(TestArguments.ID, 2), Locale.getDefault()));
Assert.assertEquals("FileTest message 02 using name null", ms.getMessage(code(TestMessages.MSG_3).arg(TestArguments.ID, 2), Locale.getDefault()));
Assert.assertEquals("Missed code", ms.getMessage(code(TestMessages.MSG4), Locale.getDefault()));
}
@Test
public void testMessageSourceLocale() {
OrchidReloadableResourceBundleMessageSource ms = new OrchidReloadableResourceBundleMessageSource();
ms.setBasename("test");
Assert.assertEquals("default1", ms.getMessage(code(TestMessages.LOCAL_1), Locale.getDefault()));
Assert.assertEquals("default2", ms.getMessage(code(TestMessages.LOCAL_2), Locale.getDefault()));
Assert.assertEquals("default1", ms.getMessage(code(TestMessages.LOCAL_1), new Locale("se")));
Assert.assertEquals("se2", ms.getMessage(code(TestMessages.LOCAL_2), new Locale("se")));
Assert.assertEquals("se3", ms.getMessage(code(TestMessages.LOCAL_3), new Locale("se")));
Assert.assertEquals("se4", ms.getMessage(code(TestMessages.LOCAL_4), new Locale("se")));
Assert.assertEquals("default1", ms.getMessage(code(TestMessages.LOCAL_1), new Locale("se", "sv")));
Assert.assertEquals("se2", ms.getMessage(code(TestMessages.LOCAL_2), new Locale("se", "sv")));
Assert.assertEquals("se_sv3", ms.getMessage(code(TestMessages.LOCAL_3), new Locale("se", "sv")));
Assert.assertEquals("se_sv4", ms.getMessage(code(TestMessages.LOCAL_4), new Locale("se", "sv")));
Assert.assertEquals("default1", ms.getMessage(code(TestMessages.LOCAL_1), new Locale("se", "sv", "sms")));
Assert.assertEquals("se2", ms.getMessage(code(TestMessages.LOCAL_2), new Locale("se", "sv", "sms")));
Assert.assertEquals("se_sv3", ms.getMessage(code(TestMessages.LOCAL_3), new Locale("se", "sv", "sms")));
Assert.assertEquals("se_sv_sms4", ms.getMessage(code(TestMessages.LOCAL_4), new Locale("se", "sv", "sms")));
Assert.assertEquals("email", ms.getMessage(code(TestMessages.LOCAL_4), new Locale("se", "", "email")));
}
@Test
public void testMessageSourceEmbedded() {
OrchidReloadableResourceBundleMessageSource ms = new OrchidReloadableResourceBundleMessageSource();
ms.setBasename("test");
ms.setUseCodeAsDefaultMessage(true);
Assert.assertEquals("Message with an embedded message EmbeddedMessage", ms.getMessage(code(TestMessages.EMBEDDED_0), Locale.getDefault()));
Assert.assertEquals("Message with an embedded message {embedded.11}", ms.getMessage(code(TestMessages.EMBEDDED_10), Locale.getDefault()));
}
@Test
public void testMessageSourceEmbeddedWithArgs() {
OrchidReloadableResourceBundleMessageSource ms = new OrchidReloadableResourceBundleMessageSource();
ms.setBasename("test");
ms.setUseCodeAsDefaultMessage(true);
Assert.assertEquals("Message with an embedded message Embedded Wille",
ms.getMessage(code(TestMessages.EMBEDDED_20).arg(TestArguments.NAME, "Wille"), Locale.getDefault()));
Assert.assertEquals("Message with an embedded message Embedded Wille",
ms.getMessage("embedded.20", new Object[] { arg(TestArguments.NAME, "Wille") }, Locale.getDefault()));
}
public enum TestMessages implements OrchidMessageCode {
MSG0("Test message"), //
MSG1("Test message {id}"), //
MSG2("Test message {id,number,000} with name {name}"), //
MSG_3("Test message {id,number,000} with name {name}"), //
MSG4("Missed code"), //
LOCAL_1("code1"), //
LOCAL_2("code2"), //
LOCAL_3("code3"), //
LOCAL_4("code3"), //
EMBEDDED_0("embedded message"), //
EMBEDDED_10("XXX"), //
EMBEDDED_20("embedded message"), //
;
private final String realName;
private final String pattern;
private TestMessages(String pattern) {
this.pattern = pattern;
this.realName = name().toLowerCase().replaceAll("_", ".");
}
@Override
public String getPattern() {
return this.pattern;
}
@Override
public String getRealName() {
return this.realName;
}
}
public enum TestArguments implements OrchidMessageArgumentCode {
ID, NAME;
@Override
public String getRealName() {
return name().toLowerCase();
}
}
}
| mit |
TheCynosure/FreeTime | src/Game/PlayerController.java | 2177 | package Game;
import java.awt.*;
import java.awt.event.KeyEvent;
/**
* Created by Jack on 12/23/2015.
*/
public class PlayerController {
private Character character;
private boolean collision_debug;
private int jump_num = 0;
public PlayerController(Character character) {
this.character = character;
}
public void characterDrawMode(Graphics graphics, int scale) {
if(collision_debug) {
character.debugDraw(graphics, scale);
} else {
character.draw(graphics, scale);
}
}
public void keyPress(KeyEvent keyEvent) {
//Handling movement keys
//Left
if(keyEvent.getKeyChar() == 'a') {
character.setVx(-5);
}
//Right
if(keyEvent.getKeyChar() == 'd') {
character.setVx(5);
}
//Jump --> Space keycode is 32
if(keyEvent.getKeyCode() == 32) {
//Only if the character has no Y acceleration will they be able to jump again.
if(jump_num < 2) {
//Give them a Y acceleration.
// - is up
jump_num++;
character.setVy(-20);
}
}
//Start the debug state:
if(keyEvent.getKeyChar() == 'p') {
//Switch the current debug state.
if(collision_debug) {
collision_debug = false;
} else {
collision_debug = true;
}
}
}
public void keyRelease(KeyEvent keyEvent) {
//Handling movement keys
//Left
if(keyEvent.getKeyChar() == 'a') {
character.setVx(0);
}
//Right
if(keyEvent.getKeyChar() == 'd') {
character.setVx(0);
}
}
public boolean isCollisionDebugActive() {
return collision_debug;
}
public void checkCollision(LevelManager levelManager, int scale_amount) {
character.checkCollision(levelManager.getCollidable_objects(), scale_amount);
if(!character.isFalling()) {
//If is on the ground then restore jump num.
jump_num = 0;
}
}
}
| mit |
joshimoo/gdi1-project | src/de/tu_darmstadt/gdi1/gorillas/entities/Cloud.java | 1417 | package de.tu_darmstadt.gdi1.gorillas.entities;
import de.tu_darmstadt.gdi1.gorillas.assets.Assets;
import de.tu_darmstadt.gdi1.gorillas.main.Game;
import de.tu_darmstadt.gdi1.gorillas.main.Gorillas;
import eea.engine.component.render.ImageRenderComponent;
import eea.engine.entity.Entity;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;
public class Cloud extends Entity {
private int windSpeed;
/** Create a Cloud at the initial position affected by wind */
public Cloud(Vector2f pos, int windSpeed) {
super("Cloud");
setPosition(pos);
this.windSpeed = windSpeed;
if (!Game.getInstance().isTestMode()) {
addComponent(new ImageRenderComponent(Assets.loadImage(Assets.Images.CLOUD)));
} else {
// In Test Mode set the size explicitly
setSize(new Vector2f(128, 64));
}
}
@Override
public void update(GameContainer gc, StateBasedGame sb, int delta) {
super.update(gc, sb, delta);
Vector2f pos = getPosition();
pos.x += (windSpeed / 2) * Game.getInstance().getWindScale();
if(pos.x < -getSize().x) {
pos.x = Gorillas.CANVAS_WIDTH;
} else if(pos.x > Gorillas.CANVAS_WIDTH + getSize().x / 2) {
pos.x = -getSize().x;
}
setPosition(pos);
}
}
| mit |
hawkphantomnet/leetcode | FractionToRecurringDecimal/Solution.java | 1615 | public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
Map<Long, Integer> remainIdx = new HashMap<Long, Integer>();
boolean neg = false;
long num = (long) numerator;
long den = (long) denominator;
if (num * den < 0) neg = true;
num = num < 0 ? -num : num;
den = den < 0 ? -den : den;
long remain = num % den;
List<Long> factors = new ArrayList<Long>();
int repeatStart = -1;
String res = "";
res += num / den;
if (remain == 0) return neg == true ? "-" + res : res;
res += ".";
while (remain != 0) {
if (remainIdx.containsKey(remain)) {
repeatStart = remainIdx.get(remain);
break;
} else {
remainIdx.put(remain, factors.size());
remain *= 10;
factors.add(remain / den);
remain = remain % den;
System.out.println(remain + " : " + factors.get(factors.size() - 1) );
}
}
if (repeatStart != -1) {
for (int i = 0; i < repeatStart; i++) {
res += factors.get(i);
}
res += "(";
for (int i = repeatStart; i < factors.size(); i++) {
res += factors.get(i);
}
res += ")";
} else {
for (int i = 0; i < factors.size(); i++) {
res += factors.get(i);
}
}
if (neg == true) {
res = "-" + res;
}
return res;
}
}
| mit |
rafeememon/rcommander-java | src/main/java/com/rbase/rcommander/impl/TemporaryFile.java | 596 | package com.rbase.rcommander.impl;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class TemporaryFile implements AutoCloseable {
private final File file;
public static TemporaryFile create(String prefix, String suffix) throws IOException {
return new TemporaryFile(File.createTempFile(prefix, suffix));
}
private TemporaryFile(File file) {
this.file = file;
}
public File getFile() {
return file;
}
@Override
public void close() {
FileUtils.deleteQuietly(file);
}
}
| mit |
ztory/sleek | sleek_module/src/main/java/com/ztory/lib/sleek/util/UtilSleekTouch.java | 1621 | package com.ztory.lib.sleek.util;
import android.view.MotionEvent;
import com.ztory.lib.sleek.Sleek;
/**
* Util functions related to touch functionality.
* Created by jonruna on 09/10/14.
*/
public class UtilSleekTouch {
public static boolean isTouchInside(MotionEvent event, Sleek view) {
return isTouchInside(event.getX(), event.getY(), view);
}
public static boolean isTouchInside(float eventX, float eventY, Sleek view) {
if (
eventX < view.getSleekX() ||
eventX > view.getSleekX() + view.getSleekW() ||
eventY < view.getSleekY() ||
eventY > view.getSleekY() + view.getSleekH()
) {
return false;
}
return true;
}
public static boolean isTouchInside(
float eventX,
float eventY,
float viewX,
float viewY,
float viewW,
float viewH
) {
if (
eventX < viewX ||
eventX > viewX + viewW ||
eventY < viewY ||
eventY > viewY + viewH
) {
return false;
}
return true;
}
public static boolean isTouchDown(MotionEvent event) {
return event.getActionMasked() == MotionEvent.ACTION_DOWN;
}
public static boolean isTouchUp(MotionEvent event) {
return event.getActionMasked() == MotionEvent.ACTION_UP;
}
public static boolean isTouchCancel(MotionEvent event) {
return event.getActionMasked() == MotionEvent.ACTION_CANCEL;
}
}
| mit |
artem-gabbasov/otus_java_2017_04_L1 | L71/src/main/java/ru/otus/Restorable.java | 283 | package ru.otus;
/**
* Created by Artem Gabbasov on 25.05.2017.
*
* ะะฝัะตััะตะนั ะดะปั ะบะปะฐััะพะฒ, ัะฟะพัะพะฑะฝัั
ัะพั
ัะฐะฝััั ะธ ะทะฐะณััะถะฐัั ัะฒะพะธ ัะพััะพัะฝะธั
*
*/
interface Restorable<T> {
T getState();
void setState(T state);
}
| mit |
pamepros/automatic-test | src/com/automatic/android/controller/ApiController.java | 2025 | package com.automatic.android.controller;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.automatic.android.BaseApplication;
import com.automatic.android.R;
import com.automatic.android.callbacks.TripsCallback;
import com.automatic.android.model.Trip;
import com.automatic.android.parser.TripParser;
import com.automatic.android.parser.TripsParser;
import com.urucas.services.JSONRequestTask;
import com.urucas.services.JSONRequestTaskHandler;
import com.urucas.services.RequestTask;
import com.urucas.services.RequestTaskHandler;
import com.urucas.utils.Utils;
public class ApiController {
private static String BASE_URL = "https://api.automatic.com/v1";
public void getAllTrips(final TripsCallback callback) {
if(!isConnected()) {
Utils.Toast(BaseApplication.getInstance(), R.string.no_connection);
return;
}
String url = BASE_URL + "/trips";
try {
new JSONRequestTask(new JSONRequestTaskHandler() {
@Override
public void onSuccess(JSONObject result) {
}
@Override
public void onError(String message) {
callback.onError(message);
}
@Override
public void onSuccess(JSONArray result) {
// api returns array
Log.i("response array",result.toString());
try {
// parse json result from trips into an array of trips objects
ArrayList<Trip> trips = TripsParser.parse(result);
callback.onSuccess(trips);
} catch (Exception e) {
e.printStackTrace();
callback.onError("error parsing trip");
}
}
}).addHeader("Authorization", "token 8eb376dbda0243633269fd8c3e6dd820aa684646").execute(url);
} catch (Exception e) {
callback.onError("error calling api");
}
}
private boolean isConnected() {
//checks internet connection
return Utils.isConnected(BaseApplication.getInstance().getApplicationContext());
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/magento/bo/magentoapi/ShoppingCartProductUpdateRequestParam.java | 3092 | package com.swfarm.biz.magento.bo.magentoapi;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for anonymous complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="sessionId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="quoteId" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="productsData" type="{urn:Magento}shoppingCartProductEntityArray"/>
* <element name="store" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "sessionId", "quoteId", "productsData",
"store" })
@XmlRootElement(name = "shoppingCartProductUpdateRequestParam")
public class ShoppingCartProductUpdateRequestParam {
@XmlElement(required = true)
protected String sessionId;
protected int quoteId;
@XmlElement(required = true)
protected ShoppingCartProductEntityArray productsData;
protected String store;
/**
* Gets the value of the sessionId property.
*
* @return possible object is {@link String }
*
*/
public String getSessionId() {
return sessionId;
}
/**
* Sets the value of the sessionId property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setSessionId(String value) {
this.sessionId = value;
}
/**
* Gets the value of the quoteId property.
*
*/
public int getQuoteId() {
return quoteId;
}
/**
* Sets the value of the quoteId property.
*
*/
public void setQuoteId(int value) {
this.quoteId = value;
}
/**
* Gets the value of the productsData property.
*
* @return possible object is {@link ShoppingCartProductEntityArray }
*
*/
public ShoppingCartProductEntityArray getProductsData() {
return productsData;
}
/**
* Sets the value of the productsData property.
*
* @param value
* allowed object is {@link ShoppingCartProductEntityArray }
*
*/
public void setProductsData(ShoppingCartProductEntityArray value) {
this.productsData = value;
}
/**
* Gets the value of the store property.
*
* @return possible object is {@link String }
*
*/
public String getStore() {
return store;
}
/**
* Sets the value of the store property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setStore(String value) {
this.store = value;
}
}
| mit |
petitparser/java-petitparser | petitparser-core/src/main/java/org/petitparser/parser/actions/TokenParser.java | 980 | package org.petitparser.parser.actions;
import org.petitparser.context.Context;
import org.petitparser.context.Result;
import org.petitparser.context.Token;
import org.petitparser.parser.Parser;
import org.petitparser.parser.combinators.DelegateParser;
/**
* A parser that creates a token from the parsed input.
*/
public class TokenParser extends DelegateParser {
public TokenParser(Parser delegate) {
super(delegate);
}
@Override
public Result parseOn(Context context) {
Result result = delegate.parseOn(context);
if (result.isSuccess()) {
Token token = new Token(context.getBuffer(), context.getPosition(),
result.getPosition(), result.get());
return result.success(token);
} else {
return result;
}
}
@Override
public int fastParseOn(String buffer, int position) {
return delegate.fastParseOn(buffer, position);
}
@Override
public TokenParser copy() {
return new TokenParser(delegate);
}
}
| mit |
mhe504/MigSim | src/org/cloudbus/cloudsim/network/datacenter/NetworkCloudlet.java | 5461 | /*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.network.datacenter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.UtilizationModel;
import uk.ac.york.mhe504.util.DataTimeMap;
/**
* NetworkCloudlet class extends Cloudlet to support simulation of complex applications. Each such
* a network Cloudlet represents a task of the application. Each task consists of several stages.
*
* <br/>Please refer to following publication for more details:<br/>
* <ul>
* <li><a href="http://dx.doi.org/10.1109/UCC.2011.24">Saurabh Kumar Garg and Rajkumar Buyya, NetworkCloudSim: Modelling Parallel Applications in Cloud
* Simulations, Proceedings of the 4th IEEE/ACM International Conference on Utility and Cloud
* Computing (UCC 2011, IEEE CS Press, USA), Melbourne, Australia, December 5-7, 2011.</a>
* </ul>
*
* @author Saurabh Kumar Garg
* @since CloudSim Toolkit 1.0
* @todo Attributes should be private
* @todo The different cloudlet classes should have a class hierarchy, by means
* of a super class and/or interface.
*/
public class NetworkCloudlet extends Cloudlet implements Comparable<Object> {
public static int FINISH = -2;
/** Time when cloudlet will be submitted. */
public double submittime;
/** Time when cloudlet finishes execution. */
public double finishtime;
/** Current stage of cloudlet execution. */
public int currStagenum;
/** Star time of the current stage.
*/
public double timetostartStage;
/** Time spent in the current stage.
*/
public double timespentInStage;
/** All stages which cloudlet execution. */
public ArrayList<TaskStage> stages;
private long data = 0; //The data this NetworkCloudlet is storing
private long dataSentRecieved = 0;
private int appId;
private double computeCost, storageCost, ioCost;
private String name;
private List<DataTimeMap> dataTimeMap;
public NetworkCloudlet(int cloudletId, long cloudletLength, int pesNumber, long cloudletFileSize,
long cloudletOutputSize, UtilizationModel utilizationModelCpu,
UtilizationModel utilizationModelRam, UtilizationModel utilizationModelBw, long data,
double computeCost, double storageCost, double ioCost, String name) {
super(
cloudletId,
cloudletLength,
pesNumber,
cloudletFileSize,
cloudletOutputSize,
utilizationModelCpu,
utilizationModelRam,
utilizationModelBw);
currStagenum = -1;
this.data = data;
stages = new ArrayList<TaskStage>();
setComputeCost(computeCost);
setStorageCost(storageCost);
setIoCost(ioCost);
setName(name);
setDataTimeMap(new LinkedList<>());
}
private void setComputeCost(double computeCost) {
this.computeCost= computeCost;
}
@Override
public int compareTo(Object arg0) {
return 0;
}
public double getSubmittime() {
return submittime;
}
public long getData() {
return data;
}
public void setData(long newValue, double time) {
if (newValue >= 0)
{
dataSentRecieved += difference(newValue,data);
data = newValue;
getDataTimeMap().add(new DataTimeMap(newValue, time));
}
}
public double getRequestedCPUTime() {
if (getStatus() != Cloudlet.CREATED ||
getStatus() != Cloudlet.READY ||
getStatus() != Cloudlet.QUEUED) {
double totalTime=0.0;
for (TaskStage ts : stages)
if (ts instanceof ExecutionTaskStage &&
ts.getIgnoreInResults() == false)
{
totalTime = totalTime + ((ExecutionTaskStage)ts).getTime();
}
return totalTime;
}
return 0.0;
}
public int getRequestedComputeHours()
{
return (int)(getRequestedCPUTime()/ 3600);
}
private long difference(long newValue, long data2) {
if (newValue > data)
return newValue - data;
else if (newValue < data)
return data - newValue;
else
return 0;
}
public int getAppId() {
return appId;
}
public void setAppId(int appId) {
this.appId = appId;
}
public double calculateComputeCost()
{
double hours = getActualCPUTime() / 3600;
int computeHours = (int)hours;
return computeHours * getComputeCost();
}
public double calculateStorageCost()
{
double estimatedGB = getData()/1000000.0;
int egb = (int) Math.ceil(estimatedGB);
return egb * getStorageCost();
}
public double calcualateIOCost()
{
double millionIOPS = dataSentRecieved/1000000.0;
int mIOPS = (int) Math.ceil(millionIOPS);
return mIOPS*getIoCost();
}
public double getDataSentRecieved()
{
return dataSentRecieved;
}
public double getComputeCost() {
return computeCost;
}
public double getStorageCost() {
return storageCost;
}
public void setStorageCost(double storageCost) {
this.storageCost = storageCost;
}
public double getIoCost() {
return ioCost;
}
public void setIoCost(double ioCost) {
this.ioCost = ioCost;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DataTimeMap> getDataTimeMap() {
return dataTimeMap;
}
public void setDataTimeMap(List<DataTimeMap> dataTimeMap) {
this.dataTimeMap = dataTimeMap;
}
}
| mit |
eilslabs/Roddy | RoddyCore/src/de/dkfz/roddy/execution/jobs/JobConstants.java | 531 | /*
* Copyright (c) 2017 German Cancer Research Center (Deutsches Krebsforschungszentrum, DKFZ).
*
* Distributed under the MIT License (license terms are at https://www.github.com/TheRoddyWMS/Roddy/LICENSE.txt).
*/
package de.dkfz.roddy.execution.jobs;
/**
* BEJob and de.dkfz.execution specific constant fields
*/
public class JobConstants {
public static final String PRM_TOOLS_DIR = "TOOLSDIR";
public static final String PRM_TOOL_ID = "TOOL_ID";
public static final String PRM_WORKFLOW_ID = "WORKFLOW_ID";
}
| mit |
hexagonc/Android-Lisp | projects/eclipse/AndroidLispGUIBuilder/src/com/evolved/automata/android/lisp/guibuilder/ProjectManagementView.java | 8565 | package com.evolved.automata.android.lisp.guibuilder;
import java.util.ArrayList;
import com.evolved.automata.CorrectableException;
import com.evolved.automata.android.lisp.guibuilder.workspace.Workspace;
import com.evolved.automata.android.widgets.ShadowButton;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
public class ProjectManagementView extends FrameLayout
{
public interface ProjectSelectedListener
{
public void onSelected(String projectName);
public void onCancelled();
}
Context _con;
ShadowButton _createProjectButton;
ShadowButton _selectProjectButton;
ShadowButton _renameProjectButton;
ShadowButton _deleteProjectButton;
ShadowButton _cancelButton;
ListView _allProjectsListView;
ArrayList<String> _projectNameList = new ArrayList<>();
ArrayAdapter<String> _projectNameAdapter;
ProjectSelectedListener _projectSelectedListener;
EditText _selectedProjectEdit;
ViewGroup _rootView = null;
public ProjectManagementView(Context context)
{
super(context);
_con = context;
}
public ProjectManagementView(Context context, AttributeSet attrs)
{
super(context, attrs);
_con = context;
}
public void setManagementListener(ProjectSelectedListener listener)
{
_projectSelectedListener = listener;
}
private void configure(Context context)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_rootView = (ViewGroup)inflater.inflate(R.layout.project_management, this, false);
addView(_rootView);
String tag;
_createProjectButton = (ShadowButton)findViewById(R.id.sdw_but_project_create);
_createProjectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String projectName;
if ((projectName = checkProjectNameDefined())!=null)
{
createProject(projectName);
}
}
});
tag = (String)_createProjectButton.getTag();
_selectProjectButton = (ShadowButton)findViewById(R.id.sdw_but_project_select);
_selectProjectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String projectName;
if ((projectName = checkProjectNameDefined("Project name is undefined"))!=null)
{
_projectSelectedListener.onSelected(projectName);
}
}
});
tag = (String)_selectProjectButton.getTag();
_renameProjectButton = (ShadowButton)findViewById(R.id.sdw_but_project_rename);
_renameProjectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String projectName;
if ((projectName = checkProjectNameDefined())!=null)
{
renameProject(projectName);
}
}
});
tag = (String)_renameProjectButton.getTag();
_deleteProjectButton = (ShadowButton)findViewById(R.id.sdw_but_project_delete);
_deleteProjectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String projectName;
if ((projectName = checkProjectNameDefined())!=null)
{
deleteProject(projectName);
}
}
});
tag = (String)_deleteProjectButton.getTag();
_cancelButton = (ShadowButton)findViewById(R.id.sdw_but_project_cancel);
_cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
_projectSelectedListener.onCancelled();
}
});
tag = (String)_cancelButton.getTag();
_selectedProjectEdit = (EditText)findViewById(R.id.edit_project_name);
_allProjectsListView = (ListView)findViewById(R.id.lst_project_names);
_projectNameAdapter = new ArrayAdapter<String>(context, R.layout.project_name_list_item, R.id.txt_project_name_list_item, _projectNameList);
Workspace workspace = CodeManager.get().getWorkspace();
_projectNameList.addAll(workspace.getProjectMap().keySet());
_allProjectsListView.setAdapter(_projectNameAdapter);
_allProjectsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String proj = _projectNameList.get(position);
_selectedProjectEdit.setText(proj);
}
});
}
private String checkProjectNameDefined(String errorMessage)
{
String name = _selectedProjectEdit.getText().toString().trim();
if (name.length()>0)
return name;
else
{
showErrorDialog("Error", (errorMessage != null)?errorMessage:"Project name can't be blank");
return null;
}
}
private String checkProjectNameDefined()
{
return checkProjectNameDefined(null);
}
private void showErrorDialog(String title, String errorMessage)
{
AlertDialog.Builder builder = new AlertDialog.Builder(_con);
builder.setTitle(title);
builder.setMessage(errorMessage);
builder.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private void showConfirmationDialog(String title, String message, final Runnable onAcceptRunnable)
{
AlertDialog.Builder builder = new AlertDialog.Builder(_con);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
onAcceptRunnable.run();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private void createProject(final String name)
{
final Workspace workspace = CodeManager.get().getWorkspace();
if (workspace.hasProject(name))
{
showConfirmationDialog(
"Overwrite Existing Project?",
"Creating " + name + " will clear all code pages.",
new Runnable()
{
public void run()
{
workspace.deleteProject(name, CodeManager.get().getDefaultProjectName());
workspace.createNewProject(name, false);
}
});
}
else
{
workspace.createNewProject(name, false);
_projectNameList.add(name);
_projectNameAdapter.notifyDataSetChanged();
}
}
private void deleteProject(final String name)
{
final Workspace workspace = CodeManager.get().getWorkspace();
if (workspace.hasProject(name))
{
showConfirmationDialog(
"Delete Project?",
"Are you sure you want to delete \"" + name + "\"? This action is irreversible.",
new Runnable()
{
public void run()
{
workspace.deleteProject(name, CodeManager.get().getDefaultProjectName());
_projectNameList.remove(name);
_projectNameAdapter.notifyDataSetChanged();
_selectedProjectEdit.setText("");
}
});
}
else
{
showErrorDialog("Error", "No project exists by the nane: " + name);
}
}
private void renameProject(final String oldName)
{
SimpleTextInputDialog inputDialog = new SimpleTextInputDialog(
_con,
new SimpleTextInputDialog.DialogButtonListener() {
@Override
public void onCancel() {
}
@Override
public void onAccept(String inputText) {
handleRename(oldName, inputText);
}
},
"Rename Project",
"Enter name of new project",
SimpleTextInputDialog.ButtonType.SHADOW
);
inputDialog.show();
}
private void handleRename(final String oldName, final String newName)
{
final Workspace workspace = CodeManager.get().getWorkspace();
try
{
workspace.renameProject(oldName, newName);
_projectNameList.remove(oldName);
_projectNameList.remove(newName);
_projectNameAdapter.notifyDataSetChanged();
}
catch (final CorrectableException ce) {
showConfirmationDialog("Error", ce.getMessage(), new Runnable()
{
public void run()
{
ce.fix();
_projectNameList.remove(oldName);
_projectNameList.remove(newName);
_projectNameAdapter.notifyDataSetChanged();
}
});
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
configure(_con);
}
}
| mit |
joshkurien/Scrambled-Peer-to-Peer | src/quanatisation/assimilation.java | 960 | package quanatisation;
public class assimilation {
public static String assemble(String key,char scrambled[][],int len,int no_channel)
{
char assembled[];
int i,msg_size;
msg_size = len*no_channel;
assembled = new char[msg_size];
int temp[]={0,0},map[] = random_permutation.kbrp(key,msg_size,no_channel);
for(i=0;i<msg_size;i++)
{
assembled[map[i]-1] = scrambled[temp[0]][temp[1]];
temp[1]++;
if(temp[1]==len)
{
temp[1]=0;
temp[0]++;
}
}
i=assembled[msg_size-1];
i+=no_channel*2;
assembled[msg_size-i] = '\0';
return (new String(assembled));
}
/* public static void main(String Args[])
{
int chno=4,len;
String key="k3cew",message="This is a very very very long message that I'm trying to make for debugging purposes only";
char scrambled[][] = division.scramble(key, message, chno);
len = scrambled[0].length;
System.out.println(assemble(key,scrambled,len,chno));
}*/
}
| mit |
nh13/picard | src/main/java/picard/sam/markduplicates/UmiAwareDuplicateSetIterator.java | 6968 | /*
* The MIT License
*
* Copyright (c) 2017 The Broad Institute
*
* 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.
*/
/**
* This acts as an iterator over duplicate sets. If a particular duplicate
* set consists of records that contain UMIs this iterator breaks up a single
* duplicate set into multiple duplicate based on the content of the UMIs.
* Since there may be sequencing errors in the UMIs, this class allows for
* simple error correction based on edit distances between the UMIs.
*
* @author fleharty
*/
package picard.sam.markduplicates;
import htsjdk.samtools.DuplicateSet;
import htsjdk.samtools.DuplicateSetIterator;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.util.CloseableIterator;
import picard.PicardException;
import java.util.*;
import static htsjdk.samtools.util.StringUtil.hammingDistance;
/**
* UmiAwareDuplicateSetIterator is an iterator that wraps a duplicate set iterator
* in such a way that each duplicate set may be broken up into subsets according
* to UMIs in the records. Some tolerance for errors in the UMIs is allowed, and
* the degree of this is controlled by the maxEditDistanceToJoin parameter.
*/
class UmiAwareDuplicateSetIterator implements CloseableIterator<DuplicateSet> {
private final DuplicateSetIterator wrappedIterator;
private Iterator<DuplicateSet> nextSetsIterator;
private final int maxEditDistanceToJoin;
private final String umiTag;
private final String inferredUmiTag;
private final boolean allowMissingUmis;
private boolean isOpen = false;
private UmiMetrics metrics;
private boolean haveWeSeenFirstRead = false;
private long observedUmiBases = 0;
/**
* Creates a UMI aware duplicate set iterator
*
* @param wrappedIterator Iterator of DuplicatesSets to use and break-up by UMI.
* @param maxEditDistanceToJoin The edit distance between UMIs that will be used to union UMIs into groups
* @param umiTag The tag used in the bam file that designates the UMI
* @param assignedUmiTag The tag in the bam file that designates the assigned UMI
*/
UmiAwareDuplicateSetIterator(final DuplicateSetIterator wrappedIterator, final int maxEditDistanceToJoin,
final String umiTag, final String assignedUmiTag, final boolean allowMissingUmis,
final UmiMetrics metrics) {
this.wrappedIterator = wrappedIterator;
this.maxEditDistanceToJoin = maxEditDistanceToJoin;
this.umiTag = umiTag;
this.inferredUmiTag = assignedUmiTag;
this.allowMissingUmis = allowMissingUmis;
this.metrics = metrics;
isOpen = true;
nextSetsIterator = Collections.emptyIterator();
}
@Override
public void close() {
isOpen = false;
wrappedIterator.close();
metrics.calculateDerivedFields();
}
@Override
public boolean hasNext() {
if (!isOpen) {
return false;
} else {
if (nextSetsIterator.hasNext() || wrappedIterator.hasNext()) {
return true;
} else {
isOpen = false;
return false;
}
}
}
@Override
public DuplicateSet next() {
if (!nextSetsIterator.hasNext()) {
process(wrappedIterator.next());
}
return nextSetsIterator.next();
}
/**
* Takes a duplicate set and breaks it up into possible smaller sets according to the UMI,
* and updates nextSetsIterator to be an iterator on that set of DuplicateSets.
*
* @param set Duplicate set that may be broken up into subsets according the UMIs
*/
private void process(final DuplicateSet set) {
// Ensure that the nextSetsIterator isn't already occupied
if (nextSetsIterator.hasNext()) {
throw new PicardException("nextSetsIterator is expected to be empty, but already contains data.");
}
final UmiGraph umiGraph = new UmiGraph(set, umiTag, inferredUmiTag, allowMissingUmis);
List<DuplicateSet> duplicateSets = umiGraph.joinUmisIntoDuplicateSets(maxEditDistanceToJoin);
// Collect statistics on numbers of observed and inferred UMIs
// and total numbers of observed and inferred UMIs
for (DuplicateSet ds : duplicateSets) {
List<SAMRecord> records = ds.getRecords();
SAMRecord representativeRead = ds.getRepresentative();
String inferredUmi = representativeRead.getStringAttribute(inferredUmiTag);
for (SAMRecord rec : records) {
String currentUmi = rec.getStringAttribute(umiTag);
if (currentUmi != null) {
// All UMIs should be the same length, the code presently does not support variable length UMIs
// TODO: Add support for variable length UMIs
if (!haveWeSeenFirstRead) {
metrics.MEAN_UMI_LENGTH = currentUmi.length();
haveWeSeenFirstRead = true;
} else {
if (metrics.MEAN_UMI_LENGTH != currentUmi.length()) {
throw new PicardException("UMIs of differing lengths were found.");
}
}
// Update UMI metrics associated with each record
metrics.OBSERVED_BASE_ERRORS += hammingDistance(currentUmi, inferredUmi);
observedUmiBases += currentUmi.length();
metrics.addUmiObservation(currentUmi, inferredUmi);
}
}
}
// Update UMI metrics associated with each duplicate set
metrics.DUPLICATE_SETS_WITH_UMI += duplicateSets.size();
metrics.DUPLICATE_SETS_IGNORING_UMI++;
nextSetsIterator = duplicateSets.iterator();
}
}
| mit |
zhqhzhqh/FbreaderJ | app/src/main/java/org/geometerplus/fbreader/fbreader/FBAction.java | 1083 | /*
* Copyright (C) 2007-2015 FBReader.ORG Limited <contact@fbreader.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.fbreader.fbreader;
import org.geometerplus.zlibrary.core.application.ZLApplication;
public abstract class FBAction extends ZLApplication.ZLAction {
protected final FBReaderApp Reader;
public FBAction(FBReaderApp fbreader) {
Reader = fbreader;
}
}
| mit |
ehuacui/ehuacui-bbs | bbs-server/src/main/java/org/ehuacui/bbs/service/OAuthService.java | 395 | package org.ehuacui.bbs.service;
import org.ehuacui.bbs.model.OAuthUserInfo;
/**
* OAuth Service Interface
* Created by jianwei.zhou on 2016/9/30.
*/
public interface OAuthService {
/**
* Get AuthorizationUrl
*
* @return AuthorizationUrl
*/
String getAuthorizationUrl(String secretState);
OAuthUserInfo getOAuthUserInfo(String code, String secretState);
}
| mit |
robjperez/opentok-android-sdk-samples | Signaling/app/src/main/java/com/tokbox/android/tutorials/signaling/OpenTokConfig.java | 2636 | package com.tokbox.android.tutorials.signaling;
import android.webkit.URLUtil;
public class OpenTokConfig {
// *** Fill the following variables using your own Project info from the OpenTok dashboard ***
// *** https://dashboard.tokbox.com/projects ***
// Replace with your OpenTok API key
public static final String API_KEY = "";
// Replace with a generated Session ID
public static final String SESSION_ID = "";
// Replace with a generated token (from the dashboard or using an OpenTok server SDK)
public static final String TOKEN = "";
/* ***** OPTIONAL *****
If you have set up one of the OpenTok server side samples to provide session information
replace the null value in CHAT_SERVER_URL with it.
For example (if using a heroku subdomain), enter : "https://yoursubdomain.herokuapp.com"
*/
public static final String CHAT_SERVER_URL = null;
public static final String SESSION_INFO_ENDPOINT = CHAT_SERVER_URL + "/session";
// *** The code below is to validate this configuration file. You do not need to modify it ***
public static String webServerConfigErrorMessage;
public static String hardCodedConfigErrorMessage;
public static boolean areHardCodedConfigsValid() {
if (OpenTokConfig.API_KEY != null && !OpenTokConfig.API_KEY.isEmpty()
&& OpenTokConfig.SESSION_ID != null && !OpenTokConfig.SESSION_ID.isEmpty()
&& OpenTokConfig.TOKEN != null && !OpenTokConfig.TOKEN.isEmpty()) {
return true;
}
else {
hardCodedConfigErrorMessage = "API KEY, SESSION ID, and TOKEN in OpenTokConfig.java cannot be null or empty.";
return false;
}
}
public static boolean isWebServerConfigUrlValid(){
if (OpenTokConfig.CHAT_SERVER_URL == null || OpenTokConfig.CHAT_SERVER_URL.isEmpty()) {
webServerConfigErrorMessage = "CHAT_SERVER_URL in OpenTokConfig.java must not be null or empty";
return false;
} else if ( !( URLUtil.isHttpsUrl(OpenTokConfig.CHAT_SERVER_URL) || URLUtil.isHttpUrl(OpenTokConfig.CHAT_SERVER_URL)) ) {
webServerConfigErrorMessage = "CHAT_SERVER_URL in OpenTokConfig.java must be specified as either http or https";
return false;
} else if ( !URLUtil.isValidUrl(OpenTokConfig.CHAT_SERVER_URL) ) {
webServerConfigErrorMessage = "CHAT_SERVER_URL in OpenTokConfig.java is not a valid URL";
return false;
} else {
return true;
}
}
}
| mit |
Rudolfking/TreatLookaheadMatcher | hu.bme.mit.inf.LookaheadMatcher/src/hu/bme/mit/inf/lookaheadmatcher/impl/FindConstraint.java | 3805 | package hu.bme.mit.inf.lookaheadmatcher.impl;
import hu.bme.mit.inf.lookaheadmatcher.IPartialPatternCacher;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.eclipse.incquery.runtime.matchers.psystem.PVariable;
import org.eclipse.incquery.runtime.matchers.psystem.annotations.PAnnotation;
import org.eclipse.incquery.runtime.matchers.psystem.basicenumerables.PositivePatternCall;
import org.eclipse.incquery.runtime.matchers.tuple.Tuple;
import com.google.common.collect.Multiset;
public class FindConstraint extends AxisConstraint implements IConstraint
{
private List<PVariable> affectedVariables;
private IPartialPatternCacher treatPatternCacher;
private PositivePatternCall innerFindCall;
@SuppressWarnings("unused")
public List<Object[]> GetMatchingsFromPartial(HashMap<PVariable, Object> MatchingVariables)
{
if (true || innerFindCall.getReferredQuery().getAllAnnotations().contains(new PAnnotation("incremental")))
{
Multiset<LookaheadMatching> result = treatPatternCacher.GetMatchingsFromPartial(innerFindCall.getReferredQuery(), MatchingVariables, affectedVariables, false);
// result must be parsed to List<Object[]>
List<Object[]> ret = new ArrayList<Object[]>();
// toarraylist false because only REAL matches count as a match, no need to count local-duplicated matches multiple mode
for(LookaheadMatching match : result.elementSet())//.toArrayList(false))
{
// add all matchings as a "line" multi-matches only once
ret.add(match.getParameterMatchValuesOnlyAsArray().toArray());
}
return ret;
}
return null;
}
@SuppressWarnings("unused")
public int GetMatchCountFromPartial(HashMap<PVariable, Object> MatchingVariables)
{
if (true || innerFindCall.getReferredQuery().getAllAnnotations().contains(new PAnnotation("incremental")))
{
int result = treatPatternCacher.GetMatchCountFromPartial(innerFindCall.getReferredQuery(), MatchingVariables, affectedVariables, false);
// result must be parsed to List<Object[]>
return result;
}
// will throw exception!?:
return -1;
}
public boolean IsAllAffectedVariablesMatched(HashMap<PVariable, Object> matchingVariables)
{
// mhm, can be evaluated when not all variables bound? no
for (PVariable one : this.affectedVariables)
{
if (one.isVirtual() == false && Utils.isRunning(one) == false && matchingVariables.get(one) == null)
return false;
}
return true;
}
@Override
public String toString()
{
return this.innerFindCall.getReferredQuery().getFullyQualifiedName() + "(" + writeArray(this.affectedVariables) + ")";
}
public List<PVariable> getAffectedVariables()
{
return affectedVariables;
}
@SuppressWarnings("unused")
private FindConstraint()
{
}
private String writeArray(List<PVariable> affectedVars)
{
String ret = "";
for (PVariable v : affectedVars)
{
ret += v.getName() + ",";
}
ret = ret.substring(0, ret.length() - 1);
return ret;
}
public FindConstraint(PositivePatternCall findCons, IPartialPatternCacher treatPatternCacher)
{
this.treatPatternCacher = treatPatternCacher;
this.innerFindCall = findCons;
// and affecteds from tuple (order needed!)
Tuple tup = findCons.getVariablesTuple();
this.affectedVariables = new ArrayList<PVariable>();
for(int i=0;i<tup.getSize();i++)
{
this.affectedVariables.add((PVariable) tup.get(i));
}
}
public PositivePatternCall getInnerFindCall() {
return innerFindCall;
}
public void setInnerFindCall(PositivePatternCall innerFindCall) {
this.innerFindCall = innerFindCall;
}
@Override
public int getAffectedVariablesSize()
{
return this.affectedVariables.size();
}
}
| mit |
narusas/deplor-ui | src/main/java/net/narusas/tools/deplor/domain/repository/RepoRepository.java | 335 | package net.narusas.tools.deplor.domain.repository;
import net.narusas.tools.deplor.domain.model.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
@org.springframework.stereotype.Repository
public interface RepoRepository extends JpaRepository<Repository, Long> {
Repository findByName(String name);
}
| mit |
terrinoni/m101j | week_2_crud/homeworks/hw2-4_create_blog_authors/src/main/java/course/UserDAO.java | 4223 | /*
* Copyright 2015 MongoDB, Inc.
*
* 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 course;
import com.mongodb.ErrorCategory;
import com.mongodb.MongoWriteException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import static com.mongodb.client.model.Filters.eq;
import org.bson.conversions.Bson;
public class UserDAO {
private final MongoCollection<Document> usersCollection;
private Random random = new SecureRandom();
public UserDAO(final MongoDatabase blogDatabase) {
usersCollection = blogDatabase.getCollection("users");
}
// validates that username is unique and insert into db
public boolean addUser(String username, String password, String email) {
String passwordHash = makePasswordHash(password, Integer.toString(random.nextInt()));
// XXX WORK HERE
// create an object suitable for insertion into the user collection
// be sure to add username and hashed password to the document. problem instructions
// will tell you the schema that the documents must follow.
Document user = new Document("_id", username)
.append("password", passwordHash);
if (email != null && !email.equals("")) {
// XXX WORK HERE
// if there is an email address specified, add it to the document too.
user.append("email", email);
}
try {
// XXX WORK HERE
// insert the document into the user collection here
System.out.println("saving");
usersCollection.insertOne(user);
return true;
} catch (MongoWriteException e) {
if (e.getError().getCategory().equals(ErrorCategory.DUPLICATE_KEY)) {
System.out.println("Username already in use: " + username);
return false;
}
throw e;
}
}
public Document validateLogin(String username, String password) {
Document user = null;
// XXX look in the user collection for a user that has this username
// assign the result to the user variable.
Bson filter = eq("_id", username);
user = usersCollection.find(filter).first();
if (user == null) {
System.out.println("User not in database");
return null;
}
String hashedAndSalted = user.get("password").toString();
String salt = hashedAndSalted.split(",")[1];
if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
System.out.println("Submitted password is not a match");
return null;
}
return user;
}
private String makePasswordHash(String password, String salt) {
try {
String saltedAndHashed = password + "," + salt;
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(saltedAndHashed.getBytes());
BASE64Encoder encoder = new BASE64Encoder();
byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes();
return encoder.encode(hashedBytes) + "," + salt;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 is not available", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 unavailable? Not a chance", e);
}
}
}
| mit |
dmascenik/cloudlbs | webapp/src/main/java/com/cloudlbs/web/core/gwt/ui/View.java | 469 | package com.cloudlbs.web.core.gwt.ui;
import com.cloudlbs.web.core.gwt.ui.wrapper.Wrapper;
import com.google.gwt.user.client.ui.Widget;
public interface View {
/**
* Toggles a "working" indicator, if one is present.
*
* @param isWorking
*/
void setWorking(boolean isWorking);
/**
* Displays an alert to the user.
*
* @param msg
*/
void alert(String msg);
Widget asWidget();
Wrapper getWrapper();
}
| mit |
jrrombaldo/algorithms | Algorithms/src/br/jrrombaldo/algorithms/Heap.java | 1304 | package br.jrrombaldo.algorithms;
public class Heap extends BaseAlgorithm {
protected static void insert(int[] vect, int k) {
int n = getN(vect);
vect[n + 1] = k;
swim(vect, n + 1);
}
protected static int delMax(int[] vect) {
int n = getN(vect);
int max = vect[1];
vect[1] = vect[n];
vect[n] = 0;
sink(vect, 1);
return max;
}
protected static int getN(int[] vect) {
int n = 0;
for (n = vect.length - 1; n > 0 && vect[n] == 0; n--) {
}
return n;
}
/* Bottom-up reheapify (swim) */
protected static void swim(int[] vect, int k) {
while (k > 1 && vect[k] > vect[k / 2]) {
swap(vect, k, k / 2);
k = k / 2;
}
}
/* Top-down heapify (sink) */
protected static void sink(int[] vect, int k) {
int n = getN(vect);
while (2 * k <= n) {
/* j = greater son */
int j = vect[2 * k] > vect[2 * k + 1] ? (2 * k) : (2 * k + 1);
if (vect[k] < vect[j])
swap(vect, j, k);
k = j;
}
}
public static void main(String[] args) {
int[] heap = new int[32];
System.out.println("testing insert...");
for (int x : _vect) {
insert(heap, x);
}
print(heap);
System.out.println("\n\ntesting delmax...");
for (int y = 0; y < 10; y++) {
System.out.println("del: " + delMax(heap));
print(heap);
}
}
}
| mit |
Woogis/SisatongPodcast | app/src/androidTest/java/net/sisatong/podcast/test/util/syndication/feedgenerator/FeedGenerator.java | 1224 | package net.sisatong.podcast.test.util.syndication.feedgenerator;
import net.sisatong.podcast.core.feed.Feed;
import java.io.IOException;
import java.io.OutputStream;
/**
* Generates a machine-readable, platform-independent representation of a Feed object.
*/
public interface FeedGenerator {
/**
* Creates a machine-readable, platform-independent representation of a given
* Feed object and writes it to the given OutputStream.
* <p>
* The representation might not be compliant with its specification if the feed
* is missing certain attribute values. This is intentional because the FeedGenerator is
* used for creating test data.
*
* @param feed The feed that should be written. Must not be null.
* @param outputStream The output target that the feed will be written to. The outputStream is not closed after
* the method's execution Must not be null.
* @param encoding The encoding to use. Must not be null.
* @param flags Optional argument for enabling implementation-dependent features.
*/
public void writeFeed(Feed feed, OutputStream outputStream, String encoding, long flags) throws IOException;
}
| mit |
maxdemarzi/grittier_ext | src/test/java/com/maxdemarzi/users/UserValidatorTest.java | 339 | package com.maxdemarzi.users;
import com.maxdemarzi.Exceptions;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class UserValidatorTest {
@Test
public void shouldHaveExceptions() throws IOException {
Assert.assertThrows(Exceptions.class, () -> UserValidator.validate(null));
}
}
| mit |
dermotblair/TouchBall | src/com/dermotblair/touchball/MainActivity.java | 6111 | package com.dermotblair.touchball;
import java.util.ArrayList;
import com.dermotblair.touchball.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private BallControllerTask ballControllerTask = null;
private DurationTimerTask durationTimerTask = null;
private MusicTask musicTask = null;
private PopulateHighScoresTask populateHighScoresTask = null;
private TouchView touchView = null;
private TextView timeTextView = null;
private TextView missedBallCountTextView = null;
private TextView scoreTextView = null;
private ProgressDialog progressDialog = null;
private long timeStartedMillis = 0;
private long timeFinishedMillis = 0;
private int score = 0;
private int topLayoutHeight = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Keep screen awake
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
touchView = (TouchView)findViewById(R.id.touchView);
timeTextView = (TextView)findViewById(R.id.timeTextView);
scoreTextView = (TextView)findViewById(R.id.scoreTextView);
missedBallCountTextView = (TextView)findViewById(R.id.missedBallCountTextView);
LinearLayout topLayout = (LinearLayout)findViewById(R.id.topLayout);
topLayoutHeight = topLayout.getHeight();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Instructions")
.setMessage("Touch each ball as it appears. To gain a point, you must touch "
+ "the ball before the next ball is displayed. The balls will be displayed "
+ "faster and faster as the game progresses. When you miss "
+ Constants.MAX_CONSECUTIVE_BALLS_MISSED + " balls in a row, it is game over.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startGame();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public int getScore() {
return score;
}
public void updateTouchView()
{
runOnUiThread(new Runnable() {
@Override
public void run() {
touchView.invalidate();
}
});
}
public void startGame()
{
score = 0;
scoreTextView.setText(String.valueOf(score));
missedBallCountTextView.setText("0");
timeTextView.setText("0:00");
touchView.setGameOver(false);
timeStartedMillis = System.currentTimeMillis();
ballControllerTask = new BallControllerTask(this);//, timeStartedMillis);
ballControllerTask.execute();
durationTimerTask = new DurationTimerTask(this, timeStartedMillis);
durationTimerTask.execute();
musicTask = new MusicTask(this);
musicTask.execute();
}
public void doGameOver(){
runOnUiThread(new Runnable() {
@Override
public void run() {
touchView.setGameOver(true);
timeFinishedMillis = System.currentTimeMillis();
stopThreads();
progressDialog = ProgressDialog.show(MainActivity.this, "Loading", "Loading scoreboard...", true);
populateHighScoresTask = new PopulateHighScoresTask(MainActivity.this,
timeFinishedMillis, score);
populateHighScoresTask.execute();
}
});
}
public void onPopulateHighScoresTaskFinished(PopulateHighScoresTask.Status populateHighScoresStatus)
{
runOnUiThread(new Runnable()
{
@Override
public void run() {
if(progressDialog != null)
progressDialog.dismiss();
}
});
displayGameOverDialog(populateHighScoresStatus);
}
private void displayGameOverDialog(final PopulateHighScoresTask.Status populateHighScoresStatus)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayList<HighScore> highScoresList = new ArrayList<HighScore>();
boolean newHighScoreAchieved = false;
if(populateHighScoresTask != null)
{
highScoresList = populateHighScoresTask.getHighScoreList();
newHighScoreAchieved = populateHighScoresTask.newHighScoreAchieved();
}
ScoreBoardDialog scoreBoardDialog = new ScoreBoardDialog(MainActivity.this,
populateHighScoresStatus, highScoresList, score, timeFinishedMillis, newHighScoreAchieved);
scoreBoardDialog.show();
}
});
}
public void updateMissedBallCount(final int missedBallCount) {
runOnUiThread(new Runnable() {
@Override
public void run() {
missedBallCountTextView.setText(String.valueOf(missedBallCount));
}
});
if(ballControllerTask != null)
ballControllerTask.setConsecutiveBallsMissedCount(missedBallCount);
}
public void updateTime(final String duration) {
runOnUiThread(new Runnable() {
@Override
public void run() {
timeTextView.setText(duration);
}
});
}
public void addToScore(final int amount) {
score += amount;
runOnUiThread(new Runnable() {
@Override
public void run() {
scoreTextView.setText(String.valueOf(score));
}
});
}
@Override
public void onDestroy()
{
super.onDestroy();
stopThreads();
}
private void stopThreads()
{
ballControllerTask.setContinueRunning(false);
durationTimerTask.setContinueRunning(false);
musicTask.setContinueRunning(false);
// No need to cancel populateHighScoresTask as it is not running all the time or
// running in a loop and does not execute for long.
}
public int getTopLayoutHeight()
{
return topLayoutHeight;
}
public Ball getBallCurrentlyDisplayed()
{
if(ballControllerTask != null)
return ballControllerTask.getBallCurrentlyDisplayed();
else
return null;
}
}
| mit |
simondean/vertx-async | src/main/java/org/simondean/vertx/async/Series.java | 280 | package org.simondean.vertx.async;
import org.vertx.java.core.AsyncResultHandler;
import java.util.List;
import java.util.function.Consumer;
public interface Series<T> {
Series<T> task(Consumer<AsyncResultHandler<T>> task);
void run(AsyncResultHandler<List<T>> handler);
} | mit |
xmljim/w3odrl21 | W3COdrl2/src/main/java/org/w3c/odrl/W3COdrl2/parsers/entityhandlers/package-info.java | 130 | /**
*
*/
/**
* @author Jim Earley <xml.jim@gmail.com> Sep 5, 2014
*
*/
package org.w3c.odrl.W3COdrl2.parsers.entityhandlers; | mit |
Hysen95/blog-spring-angularjs | src/main/java/it/hysen/springmvc/controller/admin/ArticleAdminController.java | 443 | package it.hysen.springmvc.controller.admin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ArticleAdminController extends AdminController {
@RequestMapping(value = "/article/index", method = RequestMethod.GET)
public String getHome() {
return "partials/admin/article/index";
}
}
| mit |
SuperSpyTX/MCLib | src/se/jkrau/mclib/org/objectweb/asm/util/ASMifier.java | 43343 | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package se.jkrau.mclib.org.objectweb.asm.util;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import se.jkrau.mclib.org.objectweb.asm.Attribute;
import se.jkrau.mclib.org.objectweb.asm.ClassReader;
import se.jkrau.mclib.org.objectweb.asm.Handle;
import se.jkrau.mclib.org.objectweb.asm.Label;
import se.jkrau.mclib.org.objectweb.asm.Opcodes;
import se.jkrau.mclib.org.objectweb.asm.Type;
import se.jkrau.mclib.org.objectweb.asm.TypePath;
/**
* A {@link Printer} that prints the ASM code to generate the classes if visits.
*
* @author Eric Bruneton
*/
public class ASMifier extends Printer {
/**
* The name of the visitor variable in the produced code.
*/
protected final String name;
/**
* Identifier of the annotation visitor variable in the produced code.
*/
protected final int id;
/**
* The label names. This map associates String values to Label keys. It is
* used only in ASMifierMethodVisitor.
*/
protected Map<Label, String> labelNames;
/**
* Pseudo access flag used to distinguish class access flags.
*/
private static final int ACCESS_CLASS = 262144;
/**
* Pseudo access flag used to distinguish field access flags.
*/
private static final int ACCESS_FIELD = 524288;
/**
* Pseudo access flag used to distinguish inner class flags.
*/
private static final int ACCESS_INNER = 1048576;
/**
* Constructs a new {@link ASMifier}. <i>Subclasses must not use this
* constructor</i>. Instead, they must use the
* {@link #ASMifier(int, String, int)} version.
*
* @throws IllegalStateException
* If a subclass calls this constructor.
*/
public ASMifier() {
this(Opcodes.ASM5, "cw", 0);
if (getClass() != ASMifier.class) {
throw new IllegalStateException();
}
}
/**
* Constructs a new {@link ASMifier}.
*
* @param api
* the ASM API version implemented by this class. Must be one of
* {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
* @param name
* the name of the visitor variable in the produced code.
* @param id
* identifier of the annotation visitor variable in the produced
* code.
*/
protected ASMifier(final int api, final String name, final int id) {
super(api);
this.name = name;
this.id = id;
}
/**
* Prints the ASM source code to generate the given class to the standard
* output.
* <p>
* Usage: ASMifier [-debug] <binary class name or class file name>
*
* @param args
* the command line arguments.
*
* @throws Exception
* if the class cannot be found, or if an IO exception occurs.
*/
public static void main(final String[] args) throws Exception {
int i = 0;
int flags = ClassReader.SKIP_DEBUG;
boolean ok = true;
if (args.length < 1 || args.length > 2) {
ok = false;
}
if (ok && "-debug".equals(args[0])) {
i = 1;
flags = 0;
if (args.length != 2) {
ok = false;
}
}
if (!ok) {
System.err
.println("Prints the ASM code to generate the given class.");
System.err.println("Usage: ASMifier [-debug] "
+ "<fully qualified class name or class file name>");
return;
}
ClassReader cr;
if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1
|| args[i].indexOf('/') > -1) {
cr = new ClassReader(new FileInputStream(args[i]));
} else {
cr = new ClassReader(args[i]);
}
cr.accept(new TraceClassVisitor(null, new ASMifier(), new PrintWriter(
System.out)), flags);
}
// ------------------------------------------------------------------------
// Classes
// ------------------------------------------------------------------------
@Override
public void visit(final int version, final int access, final String name,
final String signature, final String superName,
final String[] interfaces) {
String simpleName;
int n = name.lastIndexOf('/');
if (n == -1) {
simpleName = name;
} else {
text.add("package asm." + name.substring(0, n).replace('/', '.')
+ ";\n");
simpleName = name.substring(n + 1);
}
text.add("import java.util.*;\n");
text.add("import org.objectweb.asm.*;\n");
text.add("public class " + simpleName + "Dump implements Opcodes {\n\n");
text.add("public static byte[] dump () throws Exception {\n\n");
text.add("ClassWriter cw = new ClassWriter(0);\n");
text.add("FieldVisitor fv;\n");
text.add("MethodVisitor mv;\n");
text.add("AnnotationVisitor av0;\n\n");
buf.setLength(0);
buf.append("cw.visit(");
switch (version) {
case Opcodes.V1_1:
buf.append("V1_1");
break;
case Opcodes.V1_2:
buf.append("V1_2");
break;
case Opcodes.V1_3:
buf.append("V1_3");
break;
case Opcodes.V1_4:
buf.append("V1_4");
break;
case Opcodes.V1_5:
buf.append("V1_5");
break;
case Opcodes.V1_6:
buf.append("V1_6");
break;
case Opcodes.V1_7:
buf.append("V1_7");
break;
default:
buf.append(version);
break;
}
buf.append(", ");
appendAccess(access | ACCESS_CLASS);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(signature);
buf.append(", ");
appendConstant(superName);
buf.append(", ");
if (interfaces != null && interfaces.length > 0) {
buf.append("new String[] {");
for (int i = 0; i < interfaces.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendConstant(interfaces[i]);
}
buf.append(" }");
} else {
buf.append("null");
}
buf.append(");\n\n");
text.add(buf.toString());
}
@Override
public void visitSource(final String file, final String debug) {
buf.setLength(0);
buf.append("cw.visitSource(");
appendConstant(file);
buf.append(", ");
appendConstant(debug);
buf.append(");\n\n");
text.add(buf.toString());
}
@Override
public void visitOuterClass(final String owner, final String name,
final String desc) {
buf.setLength(0);
buf.append("cw.visitOuterClass(");
appendConstant(owner);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(");\n\n");
text.add(buf.toString());
}
@Override
public ASMifier visitClassAnnotation(final String desc,
final boolean visible) {
return visitAnnotation(desc, visible);
}
@Override
public ASMifier visitClassTypeAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
return visitTypeAnnotation(typeRef, typePath, desc, visible);
}
@Override
public void visitClassAttribute(final Attribute attr) {
visitAttribute(attr);
}
@Override
public void visitInnerClass(final String name, final String outerName,
final String innerName, final int access) {
buf.setLength(0);
buf.append("cw.visitInnerClass(");
appendConstant(name);
buf.append(", ");
appendConstant(outerName);
buf.append(", ");
appendConstant(innerName);
buf.append(", ");
appendAccess(access | ACCESS_INNER);
buf.append(");\n\n");
text.add(buf.toString());
}
@Override
public ASMifier visitField(final int access, final String name,
final String desc, final String signature, final Object value) {
buf.setLength(0);
buf.append("{\n");
buf.append("fv = cw.visitField(");
appendAccess(access | ACCESS_FIELD);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(", ");
appendConstant(signature);
buf.append(", ");
appendConstant(value);
buf.append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("fv", 0);
text.add(a.getText());
text.add("}\n");
return a;
}
@Override
public ASMifier visitMethod(final int access, final String name,
final String desc, final String signature, final String[] exceptions) {
buf.setLength(0);
buf.append("{\n");
buf.append("mv = cw.visitMethod(");
appendAccess(access);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(", ");
appendConstant(signature);
buf.append(", ");
if (exceptions != null && exceptions.length > 0) {
buf.append("new String[] {");
for (int i = 0; i < exceptions.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendConstant(exceptions[i]);
}
buf.append(" }");
} else {
buf.append("null");
}
buf.append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("mv", 0);
text.add(a.getText());
text.add("}\n");
return a;
}
@Override
public void visitClassEnd() {
text.add("cw.visitEnd();\n\n");
text.add("return cw.toByteArray();\n");
text.add("}\n");
text.add("}\n");
}
// ------------------------------------------------------------------------
// Annotations
// ------------------------------------------------------------------------
@Override
public void visit(final String name, final Object value) {
buf.setLength(0);
buf.append("av").append(id).append(".visit(");
appendConstant(buf, name);
buf.append(", ");
appendConstant(buf, value);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitEnum(final String name, final String desc,
final String value) {
buf.setLength(0);
buf.append("av").append(id).append(".visitEnum(");
appendConstant(buf, name);
buf.append(", ");
appendConstant(buf, desc);
buf.append(", ");
appendConstant(buf, value);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public ASMifier visitAnnotation(final String name, final String desc) {
buf.setLength(0);
buf.append("{\n");
buf.append("AnnotationVisitor av").append(id + 1).append(" = av");
buf.append(id).append(".visitAnnotation(");
appendConstant(buf, name);
buf.append(", ");
appendConstant(buf, desc);
buf.append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("av", id + 1);
text.add(a.getText());
text.add("}\n");
return a;
}
@Override
public ASMifier visitArray(final String name) {
buf.setLength(0);
buf.append("{\n");
buf.append("AnnotationVisitor av").append(id + 1).append(" = av");
buf.append(id).append(".visitArray(");
appendConstant(buf, name);
buf.append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("av", id + 1);
text.add(a.getText());
text.add("}\n");
return a;
}
@Override
public void visitAnnotationEnd() {
buf.setLength(0);
buf.append("av").append(id).append(".visitEnd();\n");
text.add(buf.toString());
}
// ------------------------------------------------------------------------
// Fields
// ------------------------------------------------------------------------
@Override
public ASMifier visitFieldAnnotation(final String desc,
final boolean visible) {
return visitAnnotation(desc, visible);
}
@Override
public ASMifier visitFieldTypeAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
return visitTypeAnnotation(typeRef, typePath, desc, visible);
}
@Override
public void visitFieldAttribute(final Attribute attr) {
visitAttribute(attr);
}
@Override
public void visitFieldEnd() {
buf.setLength(0);
buf.append(name).append(".visitEnd();\n");
text.add(buf.toString());
}
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
@Override
public void visitParameter(String parameterName, int access) {
buf.setLength(0);
buf.append(name).append(".visitParameter(");
appendString(buf, parameterName);
buf.append(", ");
appendAccess(access);
text.add(buf.append(");\n").toString());
}
@Override
public ASMifier visitAnnotationDefault() {
buf.setLength(0);
buf.append("{\n").append("av0 = ").append(name)
.append(".visitAnnotationDefault();\n");
text.add(buf.toString());
ASMifier a = createASMifier("av", 0);
text.add(a.getText());
text.add("}\n");
return a;
}
@Override
public ASMifier visitMethodAnnotation(final String desc,
final boolean visible) {
return visitAnnotation(desc, visible);
}
@Override
public ASMifier visitMethodTypeAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
return visitTypeAnnotation(typeRef, typePath, desc, visible);
}
@Override
public ASMifier visitParameterAnnotation(final int parameter,
final String desc, final boolean visible) {
buf.setLength(0);
buf.append("{\n").append("av0 = ").append(name)
.append(".visitParameterAnnotation(").append(parameter)
.append(", ");
appendConstant(desc);
buf.append(", ").append(visible).append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("av", 0);
text.add(a.getText());
text.add("}\n");
return a;
}
@Override
public void visitMethodAttribute(final Attribute attr) {
visitAttribute(attr);
}
@Override
public void visitCode() {
text.add(name + ".visitCode();\n");
}
@Override
public void visitFrame(final int type, final int nLocal,
final Object[] local, final int nStack, final Object[] stack) {
buf.setLength(0);
switch (type) {
case Opcodes.F_NEW:
case Opcodes.F_FULL:
declareFrameTypes(nLocal, local);
declareFrameTypes(nStack, stack);
if (type == Opcodes.F_NEW) {
buf.append(name).append(".visitFrame(Opcodes.F_NEW, ");
} else {
buf.append(name).append(".visitFrame(Opcodes.F_FULL, ");
}
buf.append(nLocal).append(", new Object[] {");
appendFrameTypes(nLocal, local);
buf.append("}, ").append(nStack).append(", new Object[] {");
appendFrameTypes(nStack, stack);
buf.append('}');
break;
case Opcodes.F_APPEND:
declareFrameTypes(nLocal, local);
buf.append(name).append(".visitFrame(Opcodes.F_APPEND,")
.append(nLocal).append(", new Object[] {");
appendFrameTypes(nLocal, local);
buf.append("}, 0, null");
break;
case Opcodes.F_CHOP:
buf.append(name).append(".visitFrame(Opcodes.F_CHOP,")
.append(nLocal).append(", null, 0, null");
break;
case Opcodes.F_SAME:
buf.append(name).append(
".visitFrame(Opcodes.F_SAME, 0, null, 0, null");
break;
case Opcodes.F_SAME1:
declareFrameTypes(1, stack);
buf.append(name).append(
".visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {");
appendFrameTypes(1, stack);
buf.append('}');
break;
}
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitInsn(final int opcode) {
buf.setLength(0);
buf.append(name).append(".visitInsn(").append(OPCODES[opcode])
.append(");\n");
text.add(buf.toString());
}
@Override
public void visitIntInsn(final int opcode, final int operand) {
buf.setLength(0);
buf.append(name)
.append(".visitIntInsn(")
.append(OPCODES[opcode])
.append(", ")
.append(opcode == Opcodes.NEWARRAY ? TYPES[operand] : Integer
.toString(operand)).append(");\n");
text.add(buf.toString());
}
@Override
public void visitVarInsn(final int opcode, final int var) {
buf.setLength(0);
buf.append(name).append(".visitVarInsn(").append(OPCODES[opcode])
.append(", ").append(var).append(");\n");
text.add(buf.toString());
}
@Override
public void visitTypeInsn(final int opcode, final String type) {
buf.setLength(0);
buf.append(name).append(".visitTypeInsn(").append(OPCODES[opcode])
.append(", ");
appendConstant(type);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitFieldInsn(final int opcode, final String owner,
final String name, final String desc) {
buf.setLength(0);
buf.append(this.name).append(".visitFieldInsn(")
.append(OPCODES[opcode]).append(", ");
appendConstant(owner);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(");\n");
text.add(buf.toString());
}
@Deprecated
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc) {
if (api >= Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc);
return;
}
doVisitMethodInsn(opcode, owner, name, desc,
opcode == Opcodes.INVOKEINTERFACE);
}
@Override
public void visitMethodInsn(final int opcode, final String owner,
final String name, final String desc, final boolean itf) {
if (api < Opcodes.ASM5) {
super.visitMethodInsn(opcode, owner, name, desc, itf);
return;
}
doVisitMethodInsn(opcode, owner, name, desc, itf);
}
private void doVisitMethodInsn(final int opcode, final String owner,
final String name, final String desc, final boolean itf) {
buf.setLength(0);
buf.append(this.name).append(".visitMethodInsn(")
.append(OPCODES[opcode]).append(", ");
appendConstant(owner);
buf.append(", ");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(", ");
buf.append(itf ? "true" : "false");
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm,
Object... bsmArgs) {
buf.setLength(0);
buf.append(this.name).append(".visitInvokeDynamicInsn(");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(", ");
appendConstant(bsm);
buf.append(", new Object[]{");
for (int i = 0; i < bsmArgs.length; ++i) {
appendConstant(bsmArgs[i]);
if (i != bsmArgs.length - 1) {
buf.append(", ");
}
}
buf.append("});\n");
text.add(buf.toString());
}
@Override
public void visitJumpInsn(final int opcode, final Label label) {
buf.setLength(0);
declareLabel(label);
buf.append(name).append(".visitJumpInsn(").append(OPCODES[opcode])
.append(", ");
appendLabel(label);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitLabel(final Label label) {
buf.setLength(0);
declareLabel(label);
buf.append(name).append(".visitLabel(");
appendLabel(label);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitLdcInsn(final Object cst) {
buf.setLength(0);
buf.append(name).append(".visitLdcInsn(");
appendConstant(cst);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitIincInsn(final int var, final int increment) {
buf.setLength(0);
buf.append(name).append(".visitIincInsn(").append(var).append(", ")
.append(increment).append(");\n");
text.add(buf.toString());
}
@Override
public void visitTableSwitchInsn(final int min, final int max,
final Label dflt, final Label... labels) {
buf.setLength(0);
for (int i = 0; i < labels.length; ++i) {
declareLabel(labels[i]);
}
declareLabel(dflt);
buf.append(name).append(".visitTableSwitchInsn(").append(min)
.append(", ").append(max).append(", ");
appendLabel(dflt);
buf.append(", new Label[] {");
for (int i = 0; i < labels.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendLabel(labels[i]);
}
buf.append(" });\n");
text.add(buf.toString());
}
@Override
public void visitLookupSwitchInsn(final Label dflt, final int[] keys,
final Label[] labels) {
buf.setLength(0);
for (int i = 0; i < labels.length; ++i) {
declareLabel(labels[i]);
}
declareLabel(dflt);
buf.append(name).append(".visitLookupSwitchInsn(");
appendLabel(dflt);
buf.append(", new int[] {");
for (int i = 0; i < keys.length; ++i) {
buf.append(i == 0 ? " " : ", ").append(keys[i]);
}
buf.append(" }, new Label[] {");
for (int i = 0; i < labels.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendLabel(labels[i]);
}
buf.append(" });\n");
text.add(buf.toString());
}
@Override
public void visitMultiANewArrayInsn(final String desc, final int dims) {
buf.setLength(0);
buf.append(name).append(".visitMultiANewArrayInsn(");
appendConstant(desc);
buf.append(", ").append(dims).append(");\n");
text.add(buf.toString());
}
@Override
public ASMifier visitInsnAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
return visitTypeAnnotation("visitInsnAnnotation", typeRef, typePath,
desc, visible);
}
@Override
public void visitTryCatchBlock(final Label start, final Label end,
final Label handler, final String type) {
buf.setLength(0);
declareLabel(start);
declareLabel(end);
declareLabel(handler);
buf.append(name).append(".visitTryCatchBlock(");
appendLabel(start);
buf.append(", ");
appendLabel(end);
buf.append(", ");
appendLabel(handler);
buf.append(", ");
appendConstant(type);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public ASMifier visitTryCatchAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
return visitTypeAnnotation("visitTryCatchAnnotation", typeRef,
typePath, desc, visible);
}
@Override
public void visitLocalVariable(final String name, final String desc,
final String signature, final Label start, final Label end,
final int index) {
buf.setLength(0);
buf.append(this.name).append(".visitLocalVariable(");
appendConstant(name);
buf.append(", ");
appendConstant(desc);
buf.append(", ");
appendConstant(signature);
buf.append(", ");
appendLabel(start);
buf.append(", ");
appendLabel(end);
buf.append(", ").append(index).append(");\n");
text.add(buf.toString());
}
@Override
public Printer visitLocalVariableAnnotation(int typeRef, TypePath typePath,
Label[] start, Label[] end, int[] index, String desc,
boolean visible) {
buf.setLength(0);
buf.append("{\n").append("av0 = ").append(name)
.append(".visitLocalVariableAnnotation(");
buf.append(typeRef);
buf.append(", TypePath.fromString(\"").append(typePath).append("\"), ");
buf.append("new Label[] {");
for (int i = 0; i < start.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendLabel(start[i]);
}
buf.append(" }, new Label[] {");
for (int i = 0; i < end.length; ++i) {
buf.append(i == 0 ? " " : ", ");
appendLabel(end[i]);
}
buf.append(" }, new int[] {");
for (int i = 0; i < index.length; ++i) {
buf.append(i == 0 ? " " : ", ").append(index[i]);
}
buf.append(" }, ");
appendConstant(desc);
buf.append(", ").append(visible).append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("av", 0);
text.add(a.getText());
text.add("}\n");
return a;
}
@Override
public void visitLineNumber(final int line, final Label start) {
buf.setLength(0);
buf.append(name).append(".visitLineNumber(").append(line).append(", ");
appendLabel(start);
buf.append(");\n");
text.add(buf.toString());
}
@Override
public void visitMaxs(final int maxStack, final int maxLocals) {
buf.setLength(0);
buf.append(name).append(".visitMaxs(").append(maxStack).append(", ")
.append(maxLocals).append(");\n");
text.add(buf.toString());
}
@Override
public void visitMethodEnd() {
buf.setLength(0);
buf.append(name).append(".visitEnd();\n");
text.add(buf.toString());
}
// ------------------------------------------------------------------------
// Common methods
// ------------------------------------------------------------------------
public ASMifier visitAnnotation(final String desc, final boolean visible) {
buf.setLength(0);
buf.append("{\n").append("av0 = ").append(name)
.append(".visitAnnotation(");
appendConstant(desc);
buf.append(", ").append(visible).append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("av", 0);
text.add(a.getText());
text.add("}\n");
return a;
}
public ASMifier visitTypeAnnotation(final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
return visitTypeAnnotation("visitTypeAnnotation", typeRef, typePath,
desc, visible);
}
public ASMifier visitTypeAnnotation(final String method, final int typeRef,
final TypePath typePath, final String desc, final boolean visible) {
buf.setLength(0);
buf.append("{\n").append("av0 = ").append(name).append(".")
.append(method).append("(");
buf.append(typeRef);
buf.append(", TypePath.fromString(\"").append(typePath).append("\"), ");
appendConstant(desc);
buf.append(", ").append(visible).append(");\n");
text.add(buf.toString());
ASMifier a = createASMifier("av", 0);
text.add(a.getText());
text.add("}\n");
return a;
}
public void visitAttribute(final Attribute attr) {
buf.setLength(0);
buf.append("// ATTRIBUTE ").append(attr.type).append('\n');
if (attr instanceof ASMifiable) {
if (labelNames == null) {
labelNames = new HashMap<Label, String>();
}
buf.append("{\n");
((ASMifiable) attr).asmify(buf, "attr", labelNames);
buf.append(name).append(".visitAttribute(attr);\n");
buf.append("}\n");
}
text.add(buf.toString());
}
// ------------------------------------------------------------------------
// Utility methods
// ------------------------------------------------------------------------
protected ASMifier createASMifier(final String name, final int id) {
return new ASMifier(Opcodes.ASM5, name, id);
}
/**
* Appends a string representation of the given access modifiers to
* {@link #buf buf}.
*
* @param access
* some access modifiers.
*/
void appendAccess(final int access) {
boolean first = true;
if ((access & Opcodes.ACC_PUBLIC) != 0) {
buf.append("ACC_PUBLIC");
first = false;
}
if ((access & Opcodes.ACC_PRIVATE) != 0) {
buf.append("ACC_PRIVATE");
first = false;
}
if ((access & Opcodes.ACC_PROTECTED) != 0) {
buf.append("ACC_PROTECTED");
first = false;
}
if ((access & Opcodes.ACC_FINAL) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_FINAL");
first = false;
}
if ((access & Opcodes.ACC_STATIC) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_STATIC");
first = false;
}
if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) {
if (!first) {
buf.append(" + ");
}
if ((access & ACCESS_CLASS) == 0) {
buf.append("ACC_SYNCHRONIZED");
} else {
buf.append("ACC_SUPER");
}
first = false;
}
if ((access & Opcodes.ACC_VOLATILE) != 0
&& (access & ACCESS_FIELD) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_VOLATILE");
first = false;
}
if ((access & Opcodes.ACC_BRIDGE) != 0 && (access & ACCESS_CLASS) == 0
&& (access & ACCESS_FIELD) == 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_BRIDGE");
first = false;
}
if ((access & Opcodes.ACC_VARARGS) != 0 && (access & ACCESS_CLASS) == 0
&& (access & ACCESS_FIELD) == 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_VARARGS");
first = false;
}
if ((access & Opcodes.ACC_TRANSIENT) != 0
&& (access & ACCESS_FIELD) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_TRANSIENT");
first = false;
}
if ((access & Opcodes.ACC_NATIVE) != 0 && (access & ACCESS_CLASS) == 0
&& (access & ACCESS_FIELD) == 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_NATIVE");
first = false;
}
if ((access & Opcodes.ACC_ENUM) != 0
&& ((access & ACCESS_CLASS) != 0
|| (access & ACCESS_FIELD) != 0 || (access & ACCESS_INNER) != 0)) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_ENUM");
first = false;
}
if ((access & Opcodes.ACC_ANNOTATION) != 0
&& ((access & ACCESS_CLASS) != 0 || (access & ACCESS_INNER) != 0)) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_ANNOTATION");
first = false;
}
if ((access & Opcodes.ACC_ABSTRACT) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_ABSTRACT");
first = false;
}
if ((access & Opcodes.ACC_INTERFACE) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_INTERFACE");
first = false;
}
if ((access & Opcodes.ACC_STRICT) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_STRICT");
first = false;
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_SYNTHETIC");
first = false;
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_DEPRECATED");
first = false;
}
if ((access & Opcodes.ACC_MANDATED) != 0) {
if (!first) {
buf.append(" + ");
}
buf.append("ACC_MANDATED");
first = false;
}
if (first) {
buf.append('0');
}
}
/**
* Appends a string representation of the given constant to the given
* buffer.
*
* @param cst
* an {@link Integer}, {@link Float}, {@link Long},
* {@link Double} or {@link String} object. May be <tt>null</tt>.
*/
protected void appendConstant(final Object cst) {
appendConstant(buf, cst);
}
/**
* Appends a string representation of the given constant to the given
* buffer.
*
* @param buf
* a string buffer.
* @param cst
* an {@link Integer}, {@link Float}, {@link Long},
* {@link Double} or {@link String} object. May be <tt>null</tt>.
*/
static void appendConstant(final StringBuffer buf, final Object cst) {
if (cst == null) {
buf.append("null");
} else if (cst instanceof String) {
appendString(buf, (String) cst);
} else if (cst instanceof Type) {
buf.append("Type.getType(\"");
buf.append(((Type) cst).getDescriptor());
buf.append("\")");
} else if (cst instanceof Handle) {
buf.append("new Handle(");
Handle h = (Handle) cst;
buf.append("Opcodes.").append(HANDLE_TAG[h.getTag()])
.append(", \"");
buf.append(h.getOwner()).append("\", \"");
buf.append(h.getName()).append("\", \"");
buf.append(h.getDesc()).append("\")");
} else if (cst instanceof Byte) {
buf.append("new Byte((byte)").append(cst).append(')');
} else if (cst instanceof Boolean) {
buf.append(((Boolean) cst).booleanValue() ? "Boolean.TRUE"
: "Boolean.FALSE");
} else if (cst instanceof Short) {
buf.append("new Short((short)").append(cst).append(')');
} else if (cst instanceof Character) {
int c = ((Character) cst).charValue();
buf.append("new Character((char)").append(c).append(')');
} else if (cst instanceof Integer) {
buf.append("new Integer(").append(cst).append(')');
} else if (cst instanceof Float) {
buf.append("new Float(\"").append(cst).append("\")");
} else if (cst instanceof Long) {
buf.append("new Long(").append(cst).append("L)");
} else if (cst instanceof Double) {
buf.append("new Double(\"").append(cst).append("\")");
} else if (cst instanceof byte[]) {
byte[] v = (byte[]) cst;
buf.append("new byte[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
} else if (cst instanceof boolean[]) {
boolean[] v = (boolean[]) cst;
buf.append("new boolean[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
} else if (cst instanceof short[]) {
short[] v = (short[]) cst;
buf.append("new short[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(short)").append(v[i]);
}
buf.append('}');
} else if (cst instanceof char[]) {
char[] v = (char[]) cst;
buf.append("new char[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(char)")
.append((int) v[i]);
}
buf.append('}');
} else if (cst instanceof int[]) {
int[] v = (int[]) cst;
buf.append("new int[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
} else if (cst instanceof long[]) {
long[] v = (long[]) cst;
buf.append("new long[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('L');
}
buf.append('}');
} else if (cst instanceof float[]) {
float[] v = (float[]) cst;
buf.append("new float[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('f');
}
buf.append('}');
} else if (cst instanceof double[]) {
double[] v = (double[]) cst;
buf.append("new double[] {");
for (int i = 0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('d');
}
buf.append('}');
}
}
private void declareFrameTypes(final int n, final Object[] o) {
for (int i = 0; i < n; ++i) {
if (o[i] instanceof Label) {
declareLabel((Label) o[i]);
}
}
}
private void appendFrameTypes(final int n, final Object[] o) {
for (int i = 0; i < n; ++i) {
if (i > 0) {
buf.append(", ");
}
if (o[i] instanceof String) {
appendConstant(o[i]);
} else if (o[i] instanceof Integer) {
switch (((Integer) o[i]).intValue()) {
case 0:
buf.append("Opcodes.TOP");
break;
case 1:
buf.append("Opcodes.INTEGER");
break;
case 2:
buf.append("Opcodes.FLOAT");
break;
case 3:
buf.append("Opcodes.DOUBLE");
break;
case 4:
buf.append("Opcodes.LONG");
break;
case 5:
buf.append("Opcodes.NULL");
break;
case 6:
buf.append("Opcodes.UNINITIALIZED_THIS");
break;
}
} else {
appendLabel((Label) o[i]);
}
}
}
/**
* Appends a declaration of the given label to {@link #buf buf}. This
* declaration is of the form "Label lXXX = new Label();". Does nothing if
* the given label has already been declared.
*
* @param l
* a label.
*/
protected void declareLabel(final Label l) {
if (labelNames == null) {
labelNames = new HashMap<Label, String>();
}
String name = labelNames.get(l);
if (name == null) {
name = "l" + labelNames.size();
labelNames.put(l, name);
buf.append("Label ").append(name).append(" = new Label();\n");
}
}
/**
* Appends the name of the given label to {@link #buf buf}. The given label
* <i>must</i> already have a name. One way to ensure this is to always call
* {@link #declareLabel declared} before calling this method.
*
* @param l
* a label.
*/
protected void appendLabel(final Label l) {
buf.append(labelNames.get(l));
}
}
| mit |
egroeg92/LaserSquirrel | core/src/squirrelgame/SquirrelGame.java | 486 | package squirrelgame;
import screens.GameScreen;
import shelpers.AssetLoader;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class SquirrelGame extends Game {
SpriteBatch batch;
Texture img;
@Override
public void create() {
AssetLoader.load();
setScreen(new GameScreen());
}
@Override
public void dispose(){
super.dispose();
AssetLoader.dispose();
}
}
| mit |
facebook/fresco | imagepipeline/src/test/java/com/facebook/imagepipeline/request/ImageRequestBuilderCacheEnabledTest.java | 1919 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.request;
import static org.junit.Assert.assertEquals;
import android.net.Uri;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.ParameterizedRobolectricTestRunner;
@RunWith(ParameterizedRobolectricTestRunner.class)
public class ImageRequestBuilderCacheEnabledTest {
@ParameterizedRobolectricTestRunner.Parameters(name = "URI of scheme \"{0}://\"")
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] {
{"asset", false},
{"content", false},
{"data", false},
{"file", false},
{"http", true},
{"https", true},
{"res", false},
});
}
private final String mUriScheme;
private final boolean mExpectedDefaultDiskCacheEnabled;
public ImageRequestBuilderCacheEnabledTest(
String uriScheme, Boolean expectedDefaultDiskCacheEnabled) {
mUriScheme = uriScheme;
mExpectedDefaultDiskCacheEnabled = expectedDefaultDiskCacheEnabled;
}
@Test
public void testIsDiskCacheEnabledByDefault() throws Exception {
ImageRequestBuilder imageRequestBuilder = createBuilder();
assertEquals(mExpectedDefaultDiskCacheEnabled, imageRequestBuilder.isDiskCacheEnabled());
}
@Test
public void testIsDiskCacheDisabledIfRequested() throws Exception {
ImageRequestBuilder imageRequestBuilder = createBuilder();
imageRequestBuilder.disableDiskCache();
assertEquals(false, imageRequestBuilder.isDiskCacheEnabled());
}
private ImageRequestBuilder createBuilder() {
return ImageRequestBuilder.newBuilderWithSource(Uri.parse(mUriScheme + "://request"));
}
}
| mit |
stoiandan/msg-code | Daniel/week2Project/src/main/java/utils/SortingMethods.java | 1087 | /*
* 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 utils;
import com.msgsystems.week2project.Produs;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* @author stavad
*/
public class SortingMethods {
public static void sortUsingJava7(List<Produs> listaProduse) {
Collections.sort(listaProduse, new Comparator<Produs>() {
@Override
public int compare(Produs o1, Produs o2) {
return Double.compare(o1.getPretFaraTva(), o2.getPretFaraTva());
}
});
}
public static void sortUsingJava8(List<Produs> listaProduse) {
Collections.sort(listaProduse, (s1, s2) -> Double.compare(s1.getPretFaraTva(), s2.getPretFaraTva()));
//prin referinta e)
// ToDoubleFunction<? super Produs> keyExtractor = Produs::getPretFaraTva;
// listaProduse.sort(Comparator.comparingDouble(keyExtractor));
}
}
| mit |
hankooxiaozei/adcelebrity | library/src/androidTest/java/com/liulishuo/engzo/lingorecorder/CancelRecordTest.java | 2924 | package com.liulishuo.engzo.lingorecorder;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import com.liulishuo.engzo.lingorecorder.processor.AudioProcessor;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
/**
* Created by wcw on 8/9/17.
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class CancelRecordTest {
private LingoRecorder lingoRecorder;
@Before
public void before() {
lingoRecorder = new LingoRecorder();
}
@Test
public void testCancelRecorderWhenProcessingBlock() {
lingoRecorder.put("blockProcessing", new AudioProcessor() {
private void block(long time) throws InterruptedException {
Thread.sleep(time);
}
@Override
public void start() throws Exception {
block(100000);
}
@Override
public void flow(byte[] bytes, int size) throws Exception {
block(100000);
}
@Override
public boolean needExit() {
return false;
}
@Override
public void end() throws Exception {
block(100000);
}
@Override
public void release() {
}
});
final CountDownLatch countDownLatch = new CountDownLatch(2);
final Throwable[] throwables = new Throwable[2];
lingoRecorder.setOnProcessStopListener(new LingoRecorder.OnProcessStopListener() {
@Override
public void onProcessStop(Throwable throwable, Map<String, AudioProcessor> map) {
countDownLatch.countDown();
throwables[1] = throwable;
}
});
lingoRecorder.setOnRecordStopListener(new LingoRecorder.OnRecordStopListener() {
@Override
public void onRecordStop(Throwable throwable, Result result) {
countDownLatch.countDown();
throwables[0] = throwable;
}
});
lingoRecorder.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lingoRecorder.cancel();
long startTime = System.currentTimeMillis();
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long cancelCostTime = System.currentTimeMillis() - startTime;
Assert.assertTrue(cancelCostTime < 1000);
Assert.assertNull(throwables[0]);
Assert.assertNotNull(throwables[1]);
Assert.assertEquals(LingoRecorder.CancelProcessingException.class, throwables[1].getClass());
}
}
| mit |
karim/adila | database/src/main/java/adila/db/hwy5162dt_huawei20y5162dt00.java | 232 | // This file is automatically generated.
package adila.db;
/*
* Huawei Y516-
*
* DEVICE: HWY516-T
* MODEL: HUAWEI Y516-T00
*/
final class hwy5162dt_huawei20y5162dt00 {
public static final String DATA = "Huawei|Y516-|";
}
| mit |
ymzong/dsf14 | MapReduce/src/com/yzong/dsf14/mapred/io/PairInputFormat.java | 440 | package com.yzong.dsf14.mapred.io;
/**
* An input format where each line is viewed as a key-value pair with respective <tt>Writer</tt>s.
*
* @author Jimmy Zong <yzong@cmu.edu>
*
*/
public class PairInputFormat implements InputFormat {
public Class<?> KeyLineWriter;
public Class<?> ValLineWriter;
public PairInputFormat(Class<?> keyType, Class<?> valType) {
KeyLineWriter = keyType;
ValLineWriter = valType;
}
}
| mit |
atyukavkin/Algorithms | src/main/java/com/wiley/algorithms/searching/BinarySearcher.java | 827 | package com.wiley.algorithms.searching;
/**
* Created by Andrey Tyukavkin on 4/11/2017.
* Binary search
*/
public class BinarySearcher<T extends Comparable<T>> implements Searching<T> {
@Override
public int search(T[] input, T keyword) {
if (input.length == 0) {
return -1;
}
int low = 0;
int high = input.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
if (keyword.compareTo(input[middle]) > 0) {
low = middle + 1;
} else if (keyword.compareTo(input[middle]) < 0) {
high = middle - 1;
} else {
return middle;
}
}
return -1;
}
@Override
public String toString() {
return "Binary searching";
}
}
| mit |
peter10110/Android-SteamVR-controller | app/src/main/java/com/bearbunny/controllerdemo/DebugFragment.java | 6059 | package com.bearbunny.controllerdemo;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import org.hitlabnz.sensor_fusion_demo.representation.Quaternion;
import org.hitlabnz.sensor_fusion_demo.representation.Vector3f;
import org.w3c.dom.Text;
/**
* Created by Peter on 2016.12.28..
*/
public class DebugFragment extends Fragment {
private View view;
private ControllerDataProvider dataProvider;
ToggleButton orientationLockBtn;
ToggleButton dummyOrientationBtn;
SeekBar seekBar1;
SeekBar seekBar2;
SeekBar seekBar3;
TextView seekBar1_value;
TextView seekBar2_value;
TextView seekBar3_value;
TextView quaternionValue;
TextView normalizedQuaternionValue;
TextView quaternionEulerValue;
private float yaw = 0f;
private float pitch = 0f;
private float roll = 0f;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.view = inflater.inflate(R.layout.debug_fragment_layout, container, false);
orientationLockBtn = (ToggleButton) view.findViewById(R.id.toggleLockOrientation);
orientationLockBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
dataProvider.setOrientationLock(isChecked);
}
});
dummyOrientationBtn = (ToggleButton) view.findViewById(R.id.toggleDummyOrientation);
dummyOrientationBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
dataProvider.setDummyOrientation(isChecked);
}
});
seekBar1 = (SeekBar) view.findViewById(R.id.seekBar1);
seekBar1_value = (TextView) view.findViewById(R.id.slider1Value);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// X
seekBar1_value.setText(Integer.toString(progress));
yaw = progress;
dataProvider.getHmdCorrection().setEulerAngle(yaw, pitch, roll);
quaternionValue.setText(dataProvider.getHmdCorrection().toString());
double[] euler = dataProvider.getHmdCorrection().toEulerAnglesDeg();
quaternionEulerValue.setText(euler[0] + "; " + euler[1] + "; " + euler[2]);
Quaternion temp = new Quaternion();
temp.normalize();
normalizedQuaternionValue.setText(temp.toString());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2 = (SeekBar) view.findViewById(R.id.seekBar2);
seekBar2_value = (TextView) view.findViewById(R.id.slider2Value);
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Y
seekBar2_value.setText(Integer.toString(progress));
pitch = progress;
dataProvider.getHmdCorrection().setEulerAngle(yaw, pitch, roll);
quaternionValue.setText(dataProvider.getHmdCorrection().toString());
double[] euler = dataProvider.getHmdCorrection().toEulerAnglesDeg();
quaternionEulerValue.setText(euler[0] + "; " + euler[1] + "; " + euler[2]);
Quaternion temp = new Quaternion();
temp.normalize();
normalizedQuaternionValue.setText(temp.toString());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar3 = (SeekBar) view.findViewById(R.id.seekBar3);
seekBar3_value = (TextView) view.findViewById(R.id.slider3Value);
seekBar3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Z
seekBar3_value.setText(Integer.toString(progress));
roll = progress;
dataProvider.getHmdCorrection().setEulerAngle(yaw, pitch, roll);
quaternionValue.setText(dataProvider.getHmdCorrection().toString());
double[] euler = dataProvider.getHmdCorrection().toEulerAnglesDeg();
quaternionEulerValue.setText(euler[0] + "; " + euler[1] + "; " + euler[2]);
Quaternion temp = new Quaternion();
temp.normalize();
normalizedQuaternionValue.setText(temp.toString());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
quaternionValue = (TextView) view.findViewById(R.id.hmd_quaternion_text);
normalizedQuaternionValue = (TextView) view.findViewById(R.id.hmd_quaternion_norm_text);
quaternionEulerValue = (TextView) view.findViewById(R.id.hmd_euler_text);
return view;
}
public void SetDataProvider(ControllerDataProvider dataProvider) {
this.dataProvider = dataProvider;
}
}
| mit |
CMPUT301F17T07/inGroove | inGroove/app/src/main/java/com/cmput301f17t07/ingroove/DataManagers/Command/UpdateUserCommand.java | 1563 | package com.cmput301f17t07.ingroove.DataManagers.Command;
import com.cmput301f17t07.ingroove.DataManagers.DataManager;
import com.cmput301f17t07.ingroove.Model.User;
/**
* [Command Class]
* Command to update the user data on the server
*
* Created by Christopher Walter on 2017-11-27.
*/
public class UpdateUserCommand extends ServerCommand {
private User user;
private int orderAdded;
/**
* default ctor
*
* @param user the user to be added to the server
*/
public UpdateUserCommand(User user) {
this.user = user;
this.orderAdded = ServerCommandManager.getInstance().getTopIndex();
}
/**
* @return its position on the command queue
*/
public int getOrderAdded() {
return this.orderAdded;
}
/**
* Called when the command is at the top of the queue
*
* @throws Exception if execution fails
*/
@Override
public void execute() throws Exception {
DataManager.getInstance().addUserToServer(user);
}
/**
* Called to undo a command if allowed.
*/
@Override
public void unexecute() {
}
/**
* Checks whether a command is undo-able or not
*
* @return true if the command is undo-able, false if not
*/
@Override
public Boolean isUndoable() {
return null;
}
/**
* String describing the command
*
* @return description
*/
@Override
public String toString() {
return " UPD UC with user named: " + user.getName();
}
}
| mit |
OzanKurt/Citelic-742 | src/com/citelic/game/entity/npc/impl/impossiblejad/Dessourt.java | 1239 | package com.citelic.game.entity.npc.impl.impossiblejad;
import com.citelic.game.engine.task.EngineTask;
import com.citelic.game.engine.task.EngineTaskManager;
import com.citelic.game.entity.Animation;
import com.citelic.game.entity.Entity;
import com.citelic.game.entity.npc.combat.NPCCombatDefinitions;
import com.citelic.game.entity.player.content.controllers.impl.ImpossibleJad;
import com.citelic.game.map.tile.Tile;
@SuppressWarnings("serial")
public class Dessourt extends ImpossibleJadNPC {
private ImpossibleJad controler;
public Dessourt(int id, Tile tile, ImpossibleJad controler) {
super(id, tile);
this.controler = controler;
}
@Override
public void processNPC() {
super.processNPC();
}
@Override
public void sendDeath(Entity source) {
final NPCCombatDefinitions defs = getCombatDefinitions();
resetWalkSteps();
getCombat().removeTarget();
setNextAnimation(null);
EngineTaskManager.schedule(new EngineTask() {
int loop;
@Override
public void run() {
if (loop == 0) {
setNextAnimation(new Animation(defs.getDeathEmote()));
} else if (loop >= defs.getDeathDelay()) {
reset();
finish();
controler.removeNPC();
stop();
}
loop++;
}
}, 0, 1);
}
} | mit |
olavloite/spanner-jdbc | src/main/java/nl/topicus/jdbc/util/CloudSpannerConversionUtil.java | 8363 | package nl.topicus.jdbc.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.google.cloud.ByteArray;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Type.Code;
import com.google.common.base.Preconditions;
import nl.topicus.jdbc.exception.CloudSpannerSQLException;
public class CloudSpannerConversionUtil {
private CloudSpannerConversionUtil() {}
public static Date toSqlDate(com.google.cloud.Date date) {
return toSqlDate(date, Calendar.getInstance());
}
public static Date toSqlDate(com.google.cloud.Date date, Calendar cal) {
cal.set(date.getYear(), date.getMonth() - 1, date.getDayOfMonth(), 0, 0, 0);
cal.clear(Calendar.MILLISECOND);
return new Date(cal.getTimeInMillis());
}
public static com.google.cloud.Date toCloudSpannerDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return com.google.cloud.Date.fromYearMonthDay(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH));
}
public static List<com.google.cloud.Date> toCloudSpannerDates(Date[] dates) {
List<com.google.cloud.Date> res = new ArrayList<>(dates.length);
for (int index = 0; index < dates.length; index++)
res.add(toCloudSpannerDate(dates[index]));
return res;
}
public static List<Date> toJavaDates(List<com.google.cloud.Date> dates) {
List<Date> res = new ArrayList<>(dates.size());
for (com.google.cloud.Date date : dates)
res.add(CloudSpannerConversionUtil.toSqlDate(date));
return res;
}
public static com.google.cloud.Timestamp toCloudSpannerTimestamp(Timestamp ts) {
long milliseconds = ts.getTime();
long seconds = milliseconds / 1000l;
int nanos = ts.getNanos();
return com.google.cloud.Timestamp.ofTimeSecondsAndNanos(seconds, nanos);
}
public static List<com.google.cloud.Timestamp> toCloudSpannerTimestamps(Timestamp[] timestamps) {
List<com.google.cloud.Timestamp> res = new ArrayList<>(timestamps.length);
for (int index = 0; index < timestamps.length; index++)
res.add(toCloudSpannerTimestamp(timestamps[index]));
return res;
}
public static Time toSqlTime(com.google.cloud.Timestamp ts) {
return toSqlTime(ts, Calendar.getInstance());
}
public static Time toSqlTime(com.google.cloud.Timestamp ts, Calendar cal) {
cal.set(1970, 0, 1, 0, 0, 0);
cal.clear(Calendar.MILLISECOND);
cal.setTimeInMillis(ts.getSeconds() * 1000
+ TimeUnit.MILLISECONDS.convert(ts.getNanos(), TimeUnit.NANOSECONDS));
return new Time(cal.getTimeInMillis());
}
public static List<Timestamp> toJavaTimestamps(List<com.google.cloud.Timestamp> timestamps) {
List<Timestamp> res = new ArrayList<>(timestamps.size());
for (com.google.cloud.Timestamp timestamp : timestamps)
res.add(timestamp.toSqlTimestamp());
return res;
}
public static List<ByteArray> toCloudSpannerBytes(byte[][] bytes) {
List<ByteArray> res = new ArrayList<>(bytes.length);
for (int index = 0; index < bytes.length; index++)
res.add(ByteArray.copyFrom(bytes[index]));
return res;
}
public static List<byte[]> toJavaByteArrays(List<ByteArray> bytes) {
List<byte[]> res = new ArrayList<>(bytes.size());
for (ByteArray ba : bytes)
res.add(ba.toByteArray());
return res;
}
/**
* Converts the given value from the Google {@link Type} to the Java {@link Class} type.
*
* @param value The value to convert
* @param type The type in the database
* @param targetType The java class target type to convert to
* @return The converted value
* @throws CloudSpannerSQLException Thrown if the given value cannot be converted to the specified
* type
*/
public static Object convert(Object value, Type type, Class<?> targetType)
throws CloudSpannerSQLException {
Preconditions.checkNotNull(type, "type may not be null");
Preconditions.checkNotNull(targetType, "targetType may not be null");
if (value == null)
return null;
if (targetType.equals(String.class))
return value.toString();
try {
if (targetType.equals(Boolean.class) && type.getCode() == Code.BOOL)
return value;
if (targetType.equals(Boolean.class) && type.getCode() == Code.INT64)
return Boolean.valueOf((Long) value != 0);
if (targetType.equals(Boolean.class) && type.getCode() == Code.FLOAT64)
return Boolean.valueOf((Double) value != 0d);
if (targetType.equals(Boolean.class) && type.getCode() == Code.STRING)
return Boolean.valueOf((String) value);
if (targetType.equals(BigDecimal.class) && type.getCode() == Code.BOOL)
return (Boolean) value ? BigDecimal.ONE : BigDecimal.ZERO;
if (targetType.equals(BigDecimal.class) && type.getCode() == Code.INT64)
return BigDecimal.valueOf((Long) value);
if (targetType.equals(BigDecimal.class) && type.getCode() == Code.FLOAT64)
return BigDecimal.valueOf((Double) value);
if (targetType.equals(BigDecimal.class) && type.getCode() == Code.STRING)
return new BigDecimal((String) value);
if (targetType.equals(Long.class) && type.getCode() == Code.BOOL)
return (Boolean) value ? 1L : 0L;
if (targetType.equals(Long.class) && type.getCode() == Code.INT64)
return value;
if (targetType.equals(Long.class) && type.getCode() == Code.FLOAT64)
return ((Double) value).longValue();
if (targetType.equals(Long.class) && type.getCode() == Code.STRING)
return Long.valueOf((String) value);
if (targetType.equals(Integer.class) && type.getCode() == Code.BOOL)
return (Boolean) value ? 1 : 0;
if (targetType.equals(Integer.class) && type.getCode() == Code.INT64)
return ((Long) value).intValue();
if (targetType.equals(Integer.class) && type.getCode() == Code.FLOAT64)
return ((Double) value).intValue();
if (targetType.equals(Integer.class) && type.getCode() == Code.STRING)
return Integer.valueOf((String) value);
if (targetType.equals(BigInteger.class) && type.getCode() == Code.BOOL)
return (Boolean) value ? BigInteger.ONE : BigInteger.ZERO;
if (targetType.equals(BigInteger.class) && type.getCode() == Code.INT64)
return BigInteger.valueOf((Long) value);
if (targetType.equals(BigInteger.class) && type.getCode() == Code.FLOAT64)
return BigInteger.valueOf(((Double) value).longValue());
if (targetType.equals(BigInteger.class) && type.getCode() == Code.STRING)
return new BigInteger((String) value);
if (targetType.equals(Float.class) && type.getCode() == Code.BOOL)
return (Boolean) value ? Float.valueOf(1f) : Float.valueOf(0f);
if (targetType.equals(Float.class) && type.getCode() == Code.INT64)
return ((Long) value).floatValue();
if (targetType.equals(Float.class) && type.getCode() == Code.FLOAT64)
return ((Double) value).floatValue();
if (targetType.equals(Float.class) && type.getCode() == Code.STRING)
return Float.valueOf((String) value);
if (targetType.equals(Double.class) && type.getCode() == Code.BOOL)
return (Boolean) value ? Double.valueOf(1d) : Double.valueOf(0d);
if (targetType.equals(Double.class) && type.getCode() == Code.INT64)
return ((Long) value).doubleValue();
if (targetType.equals(Double.class) && type.getCode() == Code.FLOAT64)
return value;
if (targetType.equals(Double.class) && type.getCode() == Code.STRING)
return Double.valueOf((String) value);
} catch (Exception e) {
throw new CloudSpannerSQLException("Cannot convert " + value + " to " + targetType.getName(),
com.google.rpc.Code.INVALID_ARGUMENT, e);
}
throw new CloudSpannerSQLException(
"Cannot convert " + type.getCode().name() + " to " + targetType.getName(),
com.google.rpc.Code.INVALID_ARGUMENT);
}
}
| mit |
gregbiv/news-today | app/src/main/java/com/github/gregbiv/news/core/repository/ArticleRepository.java | 614 |
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Gregory Kornienko <gregbiv@gmail.com>
* @license MIT
*/
package com.github.gregbiv.news.core.repository;
import java.util.List;
import com.github.gregbiv.news.core.model.Article;
import rx.Observable;
public interface ArticleRepository {
Observable<List<Article>> search(String source, String text, int limit, int offset);
Observable<List<Article>> searchAndGroupBy(String source, String text, String groupBy);
Observable<Article> getOne(int id);
}
| mit |
micwypych/usos-time-table | src/main/java/com/github/micwypych/usos_time_table/model/usosaccess/package-info.java | 104 | /**
*
*/
/**
* @author mwypych
*
*/
package com.github.micwypych.usos_time_table.model.usosaccess; | mit |
mpyan/JTableArray | src/JTableArray.java | 1859 | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* This class is used to store a 2D table of values
* @author Mark Yan
*
*/
public class JTableArray {
public ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>();
private int numCols;
/**
* Create a new TableArray
*/
public JTableArray(int cols){
this.numCols = cols;
}
/**
* Get the number of rows in this table
* @return the number of rows
*/
public int getNumRows(){
return data.size();
}
public int getNumCols(){
return numCols;
}
public void pushRow(double...numbers){
if (numbers.length == numCols) {
ArrayList<Double> newRow = new ArrayList<Double>();
for (double num : numbers){
newRow.add(num);
}
data.add(newRow);
}
}
/**
* Print the table
*/
public void print(){
for (int r = 0; r < this.getNumRows(); r++){
for (int c = 0; c < numCols; c++){
System.out.print(""+this.getItem(r, c)+"\t");
}
System.out.println();
}
}
/**
* Get an item
* @param col the row
* @param row the column
* @return the value stored at (col,row)
*/
public double getItem(int col, int row){
return data.get(col).get(row);
}
/**
* Set an item value
* @param col column
* @param row row
* @param value the value to be stored
*/
public void setItem(int col, int row, double value){
data.get(col).set(row, value);
}
/**
* Sort the table
* @param col the column to sort on
*/
public void sort(int col){
final int COLUMN = col;
Comparator<ArrayList<Double>> myComparator = new Comparator<ArrayList<Double>>() {
@Override
public int compare(ArrayList<Double> o1, ArrayList<Double> o2) {
return o1.get(COLUMN).compareTo(o2.get(COLUMN));
}
};
Collections.sort(data, myComparator);
}
}
| mit |
Manjago/glvrd | src/main/java/com/temnenkov/tgibot/tgapi/dto/ChosenInlineResult.java | 994 | package com.temnenkov.tgibot.tgapi.dto;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import java.io.Serializable;
@SuppressWarnings("squid:S1068")
@Data
public class ChosenInlineResult implements Serializable {
/**
* The unique identifier for the result that was chosen
*/
@SerializedName("result_id")
private String resultId;
/**
* The user that chose the result
*/
private User from;
/**
* Optional.
* Sender location, only for bots that require user location
*/
private Location location;
/**
* Optional.
* Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message.
* Will be also received in callback queries and can be used to edit the message.
*/
@SerializedName("inline_message_id")
private String inlineMessageId;
/**
* The query that was used to obtain the result
*/
private String query;
}
| mit |
DFabric/browser-tools | apps/doppio/programs/Bench.java | 2427 | public class Bench {
public static void main(String args[]) {
final long startTime = System.currentTimeMillis();
sortBenchmark();
nQueensBenchmark();
final long endTime = System.currentTimeMillis();
System.out.println("Time taken: " + (endTime - startTime));
}
private static void sortBenchmark() {
final int[] values = new int[11000];
final java.util.Random r = new java.util.Random(16);
for (int i = 0; i < values.length; i++) {
values[i] = r.nextInt();
}
System.out.println(""+values[0]);
for (int i = 0; i < values.length; i++) {
for (int j = i+1; j < values.length; j++) {
if (values[i] < values[j]) {
// swap
final int tmp = values[j];
values[j] = values[i];
values[i] = tmp;
}
}
}
System.out.println(""+values[0]);
}
private static void nQueensBenchmark() {
placeQueens(21);
}
// Credit: http://javabypatel.blogspot.in/2015/09/backtracking-n-queens-problem.html
private static void placeQueens(int gridSize) {
if(gridSize<4){
System.out.println("No Solution available");
}else{
int[] board = new int[gridSize]; // Lets take example of 4*4
placeAllQueens(board, 0);
printBoard(board);
}
}
private static boolean placeAllQueens(int[] board, int row) {
if(row == board.length){
return true;
}
boolean isAllQueensPlaced = false;
for (int column = 0; column < board.length; column++) {
board[row] = column;
if(isSafe(board, row)){
isAllQueensPlaced = placeAllQueens(board, row+1);
}
if(isAllQueensPlaced){
return true;
}
}
return false;
}
// Return true if queen placement board[row] does not conflict with
// other queens board[0] through board[row-1]
private static boolean isSafe(int[] board, int row) {
for (int i = 0; i < row; i++) {
//Check any column
if(board[row] == board[i]){
return false;
}
//Check upper left and upper right diagonal
if(Math.abs(board[row] - board[i]) == Math.abs(row-i)){
return false;
}
}
return true;
}
private static void printBoard(int[] board) {
// for (int i = 0; i < board.length; i++) {
for (int i = 0; i < 4; i++) {
// for (int j = 0; j < board.length; j++) {
for (int j = 0; j < 4; j++) {
if(j==board[i]){
System.out.print("Q ");
}else{
System.out.print("_ ");
}
}
System.out.println();
}
}
}
| mit |
KarboniteKream/scc | src/scc/seman/SymbTable.java | 2880 | package scc.seman;
import java.util.*;
import scc.*;
import scc.abstr.tree.*;
public class SymbTable {
/** Simbolna tabela. */
private static HashMap<String, LinkedList<AbsDef>> mapping = new HashMap<String, LinkedList<AbsDef>>();
/** Trenutna globina nivoja gnezdenja. */
private static int scope = 0;
/**
* Preide na naslednji nivo gnezdenja.
*/
public static void newScope() {
scope++;
}
/**
* Odstrani vse definicije na trenutnem nivoju gnezdenja in preide na
* predhodni nivo gnezdenja.
*/
public static void oldScope() {
LinkedList<String> allNames = new LinkedList<String>();
allNames.addAll(mapping.keySet());
for (String name : allNames) {
try {
SymbTable.del(name);
} catch (SemIllegalDeleteException __) {
}
}
scope--;
}
/**
* Vstavi novo definicijo imena na trenutni nivo gnezdenja.
*
* @param name
* Ime.
* @param newDef
* Nova definicija.
* @throws SemIllegalInsertException
* Ce definicija imena na trenutnem nivoju gnezdenja ze obstaja.
*/
public static void ins(String name, AbsDef newDef)
throws SemIllegalInsertException {
LinkedList<AbsDef> allNameDefs = mapping.get(name);
if (allNameDefs == null) {
allNameDefs = new LinkedList<AbsDef>();
allNameDefs.addFirst(newDef);
SymbDesc.setScope(newDef, scope);
mapping.put(name, allNameDefs);
return;
}
if ((allNameDefs.size() == 0)
|| (SymbDesc.getScope(allNameDefs.getFirst()) == null)) {
Thread.dumpStack();
Report.error("Internal error.");
return;
}
if (SymbDesc.getScope(allNameDefs.getFirst()) == scope)
throw new SemIllegalInsertException();
allNameDefs.addFirst(newDef);
SymbDesc.setScope(newDef, scope);
}
/**
* Odstrani definicijo imena s trenutnega nivoja gnezdenja.
*
* @param name
* Ime.
* @throws SemIllegalDeleteException
* Ce definicije imena na trenutnem nivoju gnezdenja ni.
*/
public static void del(String name) throws SemIllegalDeleteException {
LinkedList<AbsDef> allNameDefs = mapping.get(name);
if (allNameDefs == null)
throw new SemIllegalDeleteException();
if ((allNameDefs.size() == 0)
|| (SymbDesc.getScope(allNameDefs.getFirst()) == null)) {
Thread.dumpStack();
Report.error("Internal error.");
return;
}
if (SymbDesc.getScope(allNameDefs.getFirst()) < scope)
throw new SemIllegalDeleteException();
allNameDefs.removeFirst();
if (allNameDefs.size() == 0)
mapping.remove(name);
}
/**
* Vrne definicijo imena.
*
* @param name
* Ime.
* @return Definicija imena ali null, ce definicija imena ne obstaja.
*/
public static AbsDef fnd(String name) {
LinkedList<AbsDef> allNameDefs = mapping.get(name);
if (allNameDefs == null)
return null;
if (allNameDefs.size() == 0)
return null;
return allNameDefs.getFirst();
}
}
| mit |
punpunm/GameLibrary | Deck.java | 15473 | package gamelibrary;
import java.util.*;
/**
* The implementation of deck system such as UNO, dominion, Yu-gi-oh. This
* implementation provides most of the operation of a deck-base system.
*
* <p /> An application can restrict the capacity of a <tt>Deck</tt> instance
* using the <tt>minSize</tt> and <tt>maxSize</tt> variable.
*
* <p /><strong>Note that this implementation is not synchronized.</strong> If
* multiple threads access a <tt>Deck</tt> instance concurrently, and at least
* one of the threads modifies the list structurally, it <i>must</i> be
* synchronized externally. (A structural modification is any operation that
* adds or deletes one or more elements, or explicitly resizes the backing
* array; merely setting the value of an element is not a structural
* modification.) This is typically accomplished by synchronizing on some object
* that naturally encapsulates the deck.
*
* @param <C> The type of the card for this deck
* @author punpunm
* @since 1.0
*/
public class Deck<C> {
private List<C> deck;
/**
* The minimum size of the deck.
*/
public int minSize;
/**
* The maximum size of the deck.
*/
public int maxSize;
/**
* Constructs an empty <tt>Deck</tt> with the specified min-size and
* max-size capacity.
*
* @param minSize the minimum capacity of the deck
* @param maxSize the maximum capacity of the deck or 0 if the deck has
* unlimited size
* @throws IllegalArgumentException if the minimum or maximum capacity is
* negative
*/
public Deck(int minSize, int maxSize) {
if (minSize < 0) {
throw new IllegalArgumentException("Illegal Capacity: "
+ minSize);
}
if (maxSize < 0) {
throw new IllegalArgumentException("Illegal Capacity: "
+ maxSize);
}
if (maxSize > 0 && minSize > maxSize) {
throw new IllegalArgumentException("Illegal Capacity: minSize < maxSize");
}
this.minSize = minSize;
this.maxSize = maxSize;
deck = new ArrayList<>(maxSize);
}
/**
* Constructs an empty <tt>Deck</tt> with zero minimum capacity and
* unlimited maximum capacity.
*/
public Deck() {
deck = new ArrayList<>();
this.minSize = 0;
this.maxSize = 0;
}
/**
* Constructs a <tt>Deck</tt> with zero minimum capacity and unlimited
* maximum capacity that containing the elements of the specified
* collection, in the order they are returned by the collection's iterator.
*
* @param cards the collection whose elements are to be placed into this
* deck
* @throws NullPointerException if the specified collection is null
*/
public Deck(Collection<? extends C> cards) {
this(cards, 0, 0);
}
/**
* Constructs a <tt>Deck</tt> with the specified min-size and max-size
* capacity that containing the elements of the specified collection, in the
* order they are returned by the collection's iterator.
*
* @param cards the collection whose elements are to be placed into this
* deck
* @param minSize the minimum capacity of the deck
* @param maxSize the maximum capacity of the deck or 0 if the deck has
* unlimited size
* @throws NullPointerException if the specified collection is null
* @throws IllegalArgumentException if the initial capacity is negative
*/
public Deck(Collection<? extends C> cards, int minSize, int maxSize) {
if (minSize < 0) {
throw new IllegalArgumentException("Illegal Capacity: "
+ minSize);
}
if (maxSize < 0) {
throw new IllegalArgumentException("Illegal Capacity: "
+ maxSize);
}
if (maxSize > 0 && minSize > maxSize) {
throw new IllegalArgumentException("Illegal Capacity: minSize < maxSize");
}
this.deck = new ArrayList<>(cards);
this.minSize = minSize;
this.maxSize = maxSize;
}
/**
* Returns the list of the deck (in proper sequence).
*
* @return the list of the deck
*/
public List<C> getDeck() {
return deck;
}
/**
* Count the cards in the deck with same card.
*
* @return a map group with all cards and count the number of each set
*/
public Map<C, Integer> showDeck() {
Map<C, Integer> mapDeck = new HashMap<>();
for (C t : deck) {
if (!mapDeck.containsKey(t)) {
mapDeck.put(t, 1);
} else {
mapDeck.put(t, mapDeck.get(t) + 1);
}
}
return mapDeck;
}
/**
* Draw a card from the top of the deck and remove it from the deck.
*
* @return the card at the top of the deck
* @throws gamelibrary.Deck.NotEnoughCardException if the deck is empty or
* the total number of the deck (after drawing a card) <= the
* <tt>minSize</tt>
*/
public C drawDeck() throws NotEnoughCardException {
return drawDeck(0);
}
/**
* Draw a card at the specified position in this list and remove it. Shifts
* any subsequent elements to the left (subtracts one from their indices).
*
* @param index the index of the deck to be draw
* @return the card that was removed from the list
* @throws gamelibrary.Deck.NotEnoughCardException if the deck is empty or
* the total number of the deck (after drawing a card) <= the
* <tt>minSize</tt>
* @throws IndexOutOfBoundsException if the index is out of range (<tt>index
* < 0 || index >= size()</tt>)
*/
public C drawDeck(int index) throws NotEnoughCardException {
if (deck.isEmpty() || deck.size() <= minSize) {
throw new NotEnoughCardException();
}
C card = deck.get(index);
deck.remove(index);
return card;
}
/**
* Draw a card from the top of the deck and remove it from the deck without
* checking the deck <tt>minSize</tt>.
*
* @return the card at the top of the deck or null if no cards in the deck
* @throws NotEnoughCardException if the deck is empty
*/
public C drawDeckForce() throws NotEnoughCardException {
return drawDeckForce(0);
}
/**
* Draw a card at the specified position in this list and remove it without
* checking the deck <tt>minSize</tt>. Shifts any subsequent elements to the
* left (subtracts one from their indices).
*
* @param index the index of the deck to be draw
* @return the card that was removed from the list
* @throws gamelibrary.Deck.NotEnoughCardException if the deck is empty
* @throws IndexOutOfBoundsException if the index is out of range (<tt>index
* < 0 || index >= size()</tt>)
*/
public C drawDeckForce(int index) throws NotEnoughCardException {
if (deck.isEmpty()) {
throw new NotEnoughCardException();
}
C card = deck.get(index);
deck.remove(index);
return card;
}
/**
* Draw a card from the bottom of the deck and remove it from the deck.
*
* @return the card at the bottom of the deck
* @throws gamelibrary.Deck.NotEnoughCardException if the deck is empty or
* the total number of the deck (after drawing a card) <= the
* <tt>minSize</tt>
*/
public C drawDeckFromBottom() throws NotEnoughCardException {
return drawDeck(deck.size() - 1);
}
/**
* Draw a card from the bottom of the deck and remove it from the deck
* without checking the deck <tt>minSize</tt>.
*
* @return the card at the bottom of the deck
* @throws gamelibrary.Deck.NotEnoughCardException if the deck is empty
*/
public C drawDeckFromBottomForce() throws NotEnoughCardException {
return drawDeckForce(deck.size() - 1);
}
/**
* Add the specified card to the bottom of this deck.
*
* @param card the card to be appended to this deck
* @throws gamelibrary.Deck.TooMuchCardException if the total number of the
* deck (after adding a card) > the <tt>maxSize</tt>
*/
public void addDeckToBottom(C card) throws TooMuchCardException {
if ((maxSize > 0) && (deck.size() >= maxSize)) {
throw new TooMuchCardException();
}
addDeckToBottomForce(card);
}
/**
* Add the specified card to the bottom of this deck without checking the
* deck <tt>maxSize</tt>.
*
* @param card the card to be appended to this deck
*/
public void addDeckToBottomForce(C card) {
deck.add(card);
}
/**
* Add all of the cards in the specified collection to the bottom of this
* deck, in the order that they are returned by the specified collection's
* Iterator. The behavior of this operation is undefined if the specified
* collection is modified while the operation is in progress. (This implies
* that the behavior of this call is undefined if the specified collection
* is this list, and this list is nonempty.)
*
* @param c collection containing cards to be added to this deck
* @throws gamelibrary.Deck.TooMuchCardException if the total number of the
* deck (after adding the cards) > the <tt>maxSize</tt>
*/
public void addDeckToBottom(Collection<? extends C> c) throws TooMuchCardException {
if ((maxSize > 0) && (deck.size() + c.size() > maxSize)) {
throw new TooMuchCardException();
}
addDeckToBottomForce(c);
}
/**
* Add all of the cards in the specified collection to the bottom of this
* deck without checking the deck <tt>maxSize</tt>, in the order that they
* are returned by the specified collection's Iterator. The behavior of this
* operation is undefined if the specified collection is modified while the
* operation is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this list is
* nonempty.)
*
* @param c collection containing cards to be added to this deck
*/
public void addDeckToBottomForce(Collection<? extends C> c) {
deck.addAll(c);
}
/**
* Add the specified card to the top of this deck.
*
* @param card the card to be added to this deck
* @throws gamelibrary.Deck.TooMuchCardException if the total number of the
* deck (after adding a card) > the <tt>maxSize</tt>
*/
public void addDeckToTop(C card) throws TooMuchCardException {
if ((maxSize > 0) && (deck.size() >= maxSize)) {
throw new TooMuchCardException();
}
addDeckToTopForce(card);
}
/**
* Add the specified card to the top of this deck without checking the deck
* <tt>maxSize</tt>.
*
* @param card the card to be added to this deck
*/
public void addDeckToTopForce(C card) {
deck.add(0, card);
}
/**
* Add all of the cards in the specified collection to the top of this deck,
* in the order that they are returned by the specified collection's
* Iterator. The behavior of this operation is undefined if the specified
* collection is modified while the operation is in progress. (This implies
* that the behavior of this call is undefined if the specified collection
* is this list, and this list is nonempty.)
*
* @param c collection containing cards to be added to this deck
* @throws gamelibrary.Deck.TooMuchCardException if the total number of the
* deck (after adding the cards) > the <tt>maxSize</tt>
*/
public void addDeckToTop(Collection<? extends C> c) throws TooMuchCardException {
if ((maxSize > 0) && (deck.size() + c.size() > maxSize)) {
throw new TooMuchCardException();
}
addDeckToTopForce(c);
}
/**
* Add all of the cards in the specified collection to the top of this deck
* without checking the deck <tt>maxSize</tt>, in the order that they are
* returned by the specified collection's Iterator. The behavior of this
* operation is undefined if the specified collection is modified while the
* operation is in progress. (This implies that the behavior of this call is
* undefined if the specified collection is this list, and this list is
* nonempty.)
*
* @param c collection containing cards to be added to this deck
*/
public void addDeckToTopForce(Collection<? extends C> c) {
deck.addAll(0, c);
}
/**
* Removes the first occurrence of the specified card from this deck, if it
* is present. If the list does not contain the element, it is unchanged.
* More formally, removes the card with the lowest index <tt>i</tt> such
* that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this deck contained
* the specified card (or equivalently, if this list changed as a result of
* the call).
*
* @param card element to be removed from this deck, if present
* @return <tt>true</tt> if this list contained the specified element
* @throws gamelibrary.Deck.NotEnoughCardException if the total number of
* the deck (after remove a card) <= the <tt>minSize</tt>
*/
public boolean removeFromDeck(C card) throws NotEnoughCardException {
if (deck.isEmpty() || deck.size() <= minSize) {
throw new NotEnoughCardException();
}
return removeFromDeckForce(card);
}
/**
* Removes the first occurrence of the specified card from this deck without
* checking the deck <tt>minSize</tt>, if it is present. If the list does
* not contain the element, it is unchanged. More formally, removes the card
* with the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this deck contained
* the specified card (or equivalently, if this list changed as a result of
* the call).
*
* @param card element to be removed from this deck, if present
* @return <tt>true</tt> if this list contained the specified element
*/
public boolean removeFromDeckForce(C card) {
return deck.remove(card);
}
/**
* Randomly permutes the deck using a default source of randomness.
*
* @see Collections#shuffle(List<?> list)
*/
public void shuffle() {
Collections.shuffle(deck);
}
/**
* Removes all of the cards from this deck. The deck will be empty after
* this call returns.
*/
public void clear() {
deck.clear();
}
@Override
public String toString() {
return deck.toString();
}
/**
* Thrown to indicate the operation cause the number of cards <
* <tt>minSize</tt>.
*/
public static class NotEnoughCardException extends RuntimeException {
}
/**
* Thrown to indicate the operation cause the number of cards >
* <tt>maxSize</tt>.
*/
public static class TooMuchCardException extends RuntimeException {
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/models/VirtualNetworkGatewayPropertiesFormat.java | 19451 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.management.SubResource;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.network.models.AddressSpace;
import com.azure.resourcemanager.network.models.BgpSettings;
import com.azure.resourcemanager.network.models.ProvisioningState;
import com.azure.resourcemanager.network.models.VirtualNetworkGatewaySku;
import com.azure.resourcemanager.network.models.VirtualNetworkGatewayType;
import com.azure.resourcemanager.network.models.VpnClientConfiguration;
import com.azure.resourcemanager.network.models.VpnGatewayGeneration;
import com.azure.resourcemanager.network.models.VpnType;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** VirtualNetworkGateway properties. */
@Fluent
public final class VirtualNetworkGatewayPropertiesFormat {
@JsonIgnore private final ClientLogger logger = new ClientLogger(VirtualNetworkGatewayPropertiesFormat.class);
/*
* IP configurations for virtual network gateway.
*/
@JsonProperty(value = "ipConfigurations")
private List<VirtualNetworkGatewayIpConfigurationInner> ipConfigurations;
/*
* The type of this virtual network gateway.
*/
@JsonProperty(value = "gatewayType")
private VirtualNetworkGatewayType gatewayType;
/*
* The type of this virtual network gateway.
*/
@JsonProperty(value = "vpnType")
private VpnType vpnType;
/*
* The generation for this VirtualNetworkGateway. Must be None if
* gatewayType is not VPN.
*/
@JsonProperty(value = "vpnGatewayGeneration")
private VpnGatewayGeneration vpnGatewayGeneration;
/*
* Whether BGP is enabled for this virtual network gateway or not.
*/
@JsonProperty(value = "enableBgp")
private Boolean enableBgp;
/*
* Whether private IP needs to be enabled on this gateway for connections
* or not.
*/
@JsonProperty(value = "enablePrivateIpAddress")
private Boolean enablePrivateIpAddress;
/*
* ActiveActive flag.
*/
@JsonProperty(value = "activeActive")
private Boolean active;
/*
* disableIPSecReplayProtection flag.
*/
@JsonProperty(value = "disableIPSecReplayProtection")
private Boolean disableIpSecReplayProtection;
/*
* The reference to the LocalNetworkGateway resource which represents local
* network site having default routes. Assign Null value in case of
* removing existing default site setting.
*/
@JsonProperty(value = "gatewayDefaultSite")
private SubResource gatewayDefaultSite;
/*
* The reference to the VirtualNetworkGatewaySku resource which represents
* the SKU selected for Virtual network gateway.
*/
@JsonProperty(value = "sku")
private VirtualNetworkGatewaySku sku;
/*
* The reference to the VpnClientConfiguration resource which represents
* the P2S VpnClient configurations.
*/
@JsonProperty(value = "vpnClientConfiguration")
private VpnClientConfiguration vpnClientConfiguration;
/*
* Virtual network gateway's BGP speaker settings.
*/
@JsonProperty(value = "bgpSettings")
private BgpSettings bgpSettings;
/*
* The reference to the address space resource which represents the custom
* routes address space specified by the customer for virtual network
* gateway and VpnClient.
*/
@JsonProperty(value = "customRoutes")
private AddressSpace customRoutes;
/*
* The resource GUID property of the virtual network gateway resource.
*/
@JsonProperty(value = "resourceGuid", access = JsonProperty.Access.WRITE_ONLY)
private String resourceGuid;
/*
* The provisioning state of the virtual network gateway resource.
*/
@JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/*
* Whether dns forwarding is enabled or not.
*/
@JsonProperty(value = "enableDnsForwarding")
private Boolean enableDnsForwarding;
/*
* The IP address allocated by the gateway to which dns requests can be
* sent.
*/
@JsonProperty(value = "inboundDnsForwardingEndpoint", access = JsonProperty.Access.WRITE_ONLY)
private String inboundDnsForwardingEndpoint;
/*
* Customer vnet resource id. VirtualNetworkGateway of type local gateway
* is associated with the customer vnet.
*/
@JsonProperty(value = "vNetExtendedLocationResourceId")
private String vNetExtendedLocationResourceId;
/*
* NatRules for virtual network gateway.
*/
@JsonProperty(value = "natRules")
private List<VirtualNetworkGatewayNatRuleInner> natRules;
/*
* EnableBgpRouteTranslationForNat flag.
*/
@JsonProperty(value = "enableBgpRouteTranslationForNat")
private Boolean enableBgpRouteTranslationForNat;
/**
* Get the ipConfigurations property: IP configurations for virtual network gateway.
*
* @return the ipConfigurations value.
*/
public List<VirtualNetworkGatewayIpConfigurationInner> ipConfigurations() {
return this.ipConfigurations;
}
/**
* Set the ipConfigurations property: IP configurations for virtual network gateway.
*
* @param ipConfigurations the ipConfigurations value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withIpConfigurations(
List<VirtualNetworkGatewayIpConfigurationInner> ipConfigurations) {
this.ipConfigurations = ipConfigurations;
return this;
}
/**
* Get the gatewayType property: The type of this virtual network gateway.
*
* @return the gatewayType value.
*/
public VirtualNetworkGatewayType gatewayType() {
return this.gatewayType;
}
/**
* Set the gatewayType property: The type of this virtual network gateway.
*
* @param gatewayType the gatewayType value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withGatewayType(VirtualNetworkGatewayType gatewayType) {
this.gatewayType = gatewayType;
return this;
}
/**
* Get the vpnType property: The type of this virtual network gateway.
*
* @return the vpnType value.
*/
public VpnType vpnType() {
return this.vpnType;
}
/**
* Set the vpnType property: The type of this virtual network gateway.
*
* @param vpnType the vpnType value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withVpnType(VpnType vpnType) {
this.vpnType = vpnType;
return this;
}
/**
* Get the vpnGatewayGeneration property: The generation for this VirtualNetworkGateway. Must be None if gatewayType
* is not VPN.
*
* @return the vpnGatewayGeneration value.
*/
public VpnGatewayGeneration vpnGatewayGeneration() {
return this.vpnGatewayGeneration;
}
/**
* Set the vpnGatewayGeneration property: The generation for this VirtualNetworkGateway. Must be None if gatewayType
* is not VPN.
*
* @param vpnGatewayGeneration the vpnGatewayGeneration value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withVpnGatewayGeneration(VpnGatewayGeneration vpnGatewayGeneration) {
this.vpnGatewayGeneration = vpnGatewayGeneration;
return this;
}
/**
* Get the enableBgp property: Whether BGP is enabled for this virtual network gateway or not.
*
* @return the enableBgp value.
*/
public Boolean enableBgp() {
return this.enableBgp;
}
/**
* Set the enableBgp property: Whether BGP is enabled for this virtual network gateway or not.
*
* @param enableBgp the enableBgp value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withEnableBgp(Boolean enableBgp) {
this.enableBgp = enableBgp;
return this;
}
/**
* Get the enablePrivateIpAddress property: Whether private IP needs to be enabled on this gateway for connections
* or not.
*
* @return the enablePrivateIpAddress value.
*/
public Boolean enablePrivateIpAddress() {
return this.enablePrivateIpAddress;
}
/**
* Set the enablePrivateIpAddress property: Whether private IP needs to be enabled on this gateway for connections
* or not.
*
* @param enablePrivateIpAddress the enablePrivateIpAddress value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withEnablePrivateIpAddress(Boolean enablePrivateIpAddress) {
this.enablePrivateIpAddress = enablePrivateIpAddress;
return this;
}
/**
* Get the active property: ActiveActive flag.
*
* @return the active value.
*/
public Boolean active() {
return this.active;
}
/**
* Set the active property: ActiveActive flag.
*
* @param active the active value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withActive(Boolean active) {
this.active = active;
return this;
}
/**
* Get the disableIpSecReplayProtection property: disableIPSecReplayProtection flag.
*
* @return the disableIpSecReplayProtection value.
*/
public Boolean disableIpSecReplayProtection() {
return this.disableIpSecReplayProtection;
}
/**
* Set the disableIpSecReplayProtection property: disableIPSecReplayProtection flag.
*
* @param disableIpSecReplayProtection the disableIpSecReplayProtection value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withDisableIpSecReplayProtection(
Boolean disableIpSecReplayProtection) {
this.disableIpSecReplayProtection = disableIpSecReplayProtection;
return this;
}
/**
* Get the gatewayDefaultSite property: The reference to the LocalNetworkGateway resource which represents local
* network site having default routes. Assign Null value in case of removing existing default site setting.
*
* @return the gatewayDefaultSite value.
*/
public SubResource gatewayDefaultSite() {
return this.gatewayDefaultSite;
}
/**
* Set the gatewayDefaultSite property: The reference to the LocalNetworkGateway resource which represents local
* network site having default routes. Assign Null value in case of removing existing default site setting.
*
* @param gatewayDefaultSite the gatewayDefaultSite value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withGatewayDefaultSite(SubResource gatewayDefaultSite) {
this.gatewayDefaultSite = gatewayDefaultSite;
return this;
}
/**
* Get the sku property: The reference to the VirtualNetworkGatewaySku resource which represents the SKU selected
* for Virtual network gateway.
*
* @return the sku value.
*/
public VirtualNetworkGatewaySku sku() {
return this.sku;
}
/**
* Set the sku property: The reference to the VirtualNetworkGatewaySku resource which represents the SKU selected
* for Virtual network gateway.
*
* @param sku the sku value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withSku(VirtualNetworkGatewaySku sku) {
this.sku = sku;
return this;
}
/**
* Get the vpnClientConfiguration property: The reference to the VpnClientConfiguration resource which represents
* the P2S VpnClient configurations.
*
* @return the vpnClientConfiguration value.
*/
public VpnClientConfiguration vpnClientConfiguration() {
return this.vpnClientConfiguration;
}
/**
* Set the vpnClientConfiguration property: The reference to the VpnClientConfiguration resource which represents
* the P2S VpnClient configurations.
*
* @param vpnClientConfiguration the vpnClientConfiguration value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withVpnClientConfiguration(
VpnClientConfiguration vpnClientConfiguration) {
this.vpnClientConfiguration = vpnClientConfiguration;
return this;
}
/**
* Get the bgpSettings property: Virtual network gateway's BGP speaker settings.
*
* @return the bgpSettings value.
*/
public BgpSettings bgpSettings() {
return this.bgpSettings;
}
/**
* Set the bgpSettings property: Virtual network gateway's BGP speaker settings.
*
* @param bgpSettings the bgpSettings value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withBgpSettings(BgpSettings bgpSettings) {
this.bgpSettings = bgpSettings;
return this;
}
/**
* Get the customRoutes property: The reference to the address space resource which represents the custom routes
* address space specified by the customer for virtual network gateway and VpnClient.
*
* @return the customRoutes value.
*/
public AddressSpace customRoutes() {
return this.customRoutes;
}
/**
* Set the customRoutes property: The reference to the address space resource which represents the custom routes
* address space specified by the customer for virtual network gateway and VpnClient.
*
* @param customRoutes the customRoutes value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withCustomRoutes(AddressSpace customRoutes) {
this.customRoutes = customRoutes;
return this;
}
/**
* Get the resourceGuid property: The resource GUID property of the virtual network gateway resource.
*
* @return the resourceGuid value.
*/
public String resourceGuid() {
return this.resourceGuid;
}
/**
* Get the provisioningState property: The provisioning state of the virtual network gateway resource.
*
* @return the provisioningState value.
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get the enableDnsForwarding property: Whether dns forwarding is enabled or not.
*
* @return the enableDnsForwarding value.
*/
public Boolean enableDnsForwarding() {
return this.enableDnsForwarding;
}
/**
* Set the enableDnsForwarding property: Whether dns forwarding is enabled or not.
*
* @param enableDnsForwarding the enableDnsForwarding value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withEnableDnsForwarding(Boolean enableDnsForwarding) {
this.enableDnsForwarding = enableDnsForwarding;
return this;
}
/**
* Get the inboundDnsForwardingEndpoint property: The IP address allocated by the gateway to which dns requests can
* be sent.
*
* @return the inboundDnsForwardingEndpoint value.
*/
public String inboundDnsForwardingEndpoint() {
return this.inboundDnsForwardingEndpoint;
}
/**
* Get the vNetExtendedLocationResourceId property: Customer vnet resource id. VirtualNetworkGateway of type local
* gateway is associated with the customer vnet.
*
* @return the vNetExtendedLocationResourceId value.
*/
public String vNetExtendedLocationResourceId() {
return this.vNetExtendedLocationResourceId;
}
/**
* Set the vNetExtendedLocationResourceId property: Customer vnet resource id. VirtualNetworkGateway of type local
* gateway is associated with the customer vnet.
*
* @param vNetExtendedLocationResourceId the vNetExtendedLocationResourceId value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withVNetExtendedLocationResourceId(
String vNetExtendedLocationResourceId) {
this.vNetExtendedLocationResourceId = vNetExtendedLocationResourceId;
return this;
}
/**
* Get the natRules property: NatRules for virtual network gateway.
*
* @return the natRules value.
*/
public List<VirtualNetworkGatewayNatRuleInner> natRules() {
return this.natRules;
}
/**
* Set the natRules property: NatRules for virtual network gateway.
*
* @param natRules the natRules value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withNatRules(List<VirtualNetworkGatewayNatRuleInner> natRules) {
this.natRules = natRules;
return this;
}
/**
* Get the enableBgpRouteTranslationForNat property: EnableBgpRouteTranslationForNat flag.
*
* @return the enableBgpRouteTranslationForNat value.
*/
public Boolean enableBgpRouteTranslationForNat() {
return this.enableBgpRouteTranslationForNat;
}
/**
* Set the enableBgpRouteTranslationForNat property: EnableBgpRouteTranslationForNat flag.
*
* @param enableBgpRouteTranslationForNat the enableBgpRouteTranslationForNat value to set.
* @return the VirtualNetworkGatewayPropertiesFormat object itself.
*/
public VirtualNetworkGatewayPropertiesFormat withEnableBgpRouteTranslationForNat(
Boolean enableBgpRouteTranslationForNat) {
this.enableBgpRouteTranslationForNat = enableBgpRouteTranslationForNat;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (ipConfigurations() != null) {
ipConfigurations().forEach(e -> e.validate());
}
if (sku() != null) {
sku().validate();
}
if (vpnClientConfiguration() != null) {
vpnClientConfiguration().validate();
}
if (bgpSettings() != null) {
bgpSettings().validate();
}
if (customRoutes() != null) {
customRoutes().validate();
}
if (natRules() != null) {
natRules().forEach(e -> e.validate());
}
}
}
| mit |
bo-git/visearch-sdk-java | src/main/java/com/visenze/visearch/internal/DataOperations.java | 600 | package com.visenze.visearch.internal;
import com.visenze.visearch.Image;
import com.visenze.visearch.InsertStatus;
import com.visenze.visearch.InsertTrans;
import com.visenze.visearch.RemoveStatus;
import java.util.List;
import java.util.Map;
public interface DataOperations {
InsertTrans insert(List<Image> imageList);
InsertTrans insert(List<Image> imageList, Map<String, String> customParams);
InsertStatus insertStatus(String transId);
InsertStatus insertStatus(String transId, Integer errorPage, Integer errorLimit);
RemoveStatus remove(List<String> imNameList);
}
| mit |
jrmunson/Android-Dev | outsystems-app-android/Outsytems/platforms/android/src/com/outsystems/android/ApplicationOutsystems.java | 2255 | /*
* OutSystems Project
*
* Copyright (C) 2014 OutSystems.
*
* This software is proprietary.
*/
package com.outsystems.android;
import java.util.List;
import com.outsystems.android.core.DatabaseHandler;
import com.outsystems.android.core.WebServicesClient;
import com.outsystems.android.helpers.HubManagerHelper;
import com.outsystems.android.model.HubApplicationModel;
import android.app.Application;
/**
* Class description.
*
* @author <a href="mailto:vmfo@xpand-it.com">vmfo</a>
* @version $Revision: 666 $
*
*/
public class ApplicationOutsystems extends Application {
/** The demo applications. */
public boolean demoApplications = false;
/*
* (non-Javadoc)
*
* @see android.app.Application#onLowMemory()
*/
@Override
public void onLowMemory() {
super.onLowMemory();
}
/*
* (non-Javadoc)
*
* @see android.app.Application#onTrimMemory(int)
*/
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
}
/**
* @return the demoApplications
*/
public boolean isDemoApplications() {
return demoApplications;
}
/**
* @param demoApplications the demoApplications to set
*/
public void setDemoApplications(boolean demoApplications) {
this.demoApplications = demoApplications;
}
/**
* Register default hub application.
*/
public void registerDefaultHubApplication() {
if (isDemoApplications()) {
HubManagerHelper.getInstance().setApplicationHosted(WebServicesClient.DEMO_HOST_NAME);
} else {
DatabaseHandler database = new DatabaseHandler(getApplicationContext());
List<HubApplicationModel> hubApplications = database.getAllHubApllications();
if (hubApplications != null && hubApplications.size() > 0) {
HubApplicationModel hubApplication = hubApplications.get(0);
if (hubApplication != null) {
HubManagerHelper.getInstance().setApplicationHosted(hubApplication.getHost());
HubManagerHelper.getInstance().setJSFApplicationServer(hubApplication.isJSF());
}
}
}
}
}
| mit |
shiyimin/androidtestdebug | lecture-demo/jenkins/androidalarm/app/src/main/java/mobiletest/vowei/com/androidalarm/IGetDate.java | 214 | package mobiletest.vowei.com.androidalarm;
import java.util.Date;
public interface IGetDate {
// ่ทๅ็ฐๅจ็ๆถ้ด
// ้่ฟๆๅๆฅๅฃ็ๆนๅผ๏ผไพฟไบๅจๆต่ฏๆถ่ฟๅไปปๆ็ๆถ้ดใ
Date Now();
}
| mit |
lemaiyan/KeenClient-Java | core/src/test/java/io/keen/client/java/KeenClientTest.java | 31014 | package io.keen.client.java;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import io.keen.client.java.exceptions.KeenException;
import io.keen.client.java.exceptions.NoWriteKeyException;
import io.keen.client.java.exceptions.ServerException;
import io.keen.client.java.http.HttpHandler;
import io.keen.client.java.http.Request;
import io.keen.client.java.http.Response;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* KeenClientTest
*
* @author dkador
* @since 1.0.0
*/
public class KeenClientTest {
private static KeenProject TEST_PROJECT;
private static List<Map<String, Object>> TEST_EVENTS;
private static final String TEST_COLLECTION = "test_collection";
private static final String TEST_COLLECTION_2 = "test_collection_2";
private static final String POST_EVENT_SUCCESS = "{\"created\": true}";
/**
* JSON object mapper that the test infrastructure can use without worrying about any
* interference with the Keen library's JSON handler.
*/
private static ObjectMapper JSON_MAPPER;
private KeenClient client;
private HttpHandler mockHttpHandler;
@BeforeClass
public static void classSetUp() {
KeenLogging.enableLogging();
TEST_PROJECT = new KeenProject("<project ID>", "<write key>", "<read key");
TEST_EVENTS = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 10; i++) {
Map<String, Object> event = new HashMap<String, Object>();
event.put("test-key", "test-value-" + i);
TEST_EVENTS.add(event);
}
JSON_MAPPER = new ObjectMapper();
JSON_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Before
public void setup() throws IOException {
// Set up a mock HTTP handler.
mockHttpHandler = mock(HttpHandler.class);
setMockResponse(500, "Unexpected HTTP request");
// Build the client.
client = new TestKeenClientBuilder()
.withHttpHandler(mockHttpHandler)
.build();
client.setBaseUrl(null);
client.setDebugMode(true);
client.setDefaultProject(TEST_PROJECT);
// Clear the RAM event store.
((RamEventStore) client.getEventStore()).clear();
}
@After
public void cleanUp() {
client = null;
}
@Test
public void initializeWithEnvironmentVariables() throws Exception {
// Construct a new test client and make sure it doesn't have a default project.
KeenClient testClient = new TestKeenClientBuilder().build();
assertNull(testClient.getDefaultProject());
// Mock an environment with a project.
Environment mockEnv = mock(Environment.class);
when(mockEnv.getKeenProjectId()).thenReturn("<project ID>");
// Make sure a new test client using the mock environment has the expected default project.
testClient = new TestKeenClientBuilder(mockEnv).build();
KeenProject defaultProject = testClient.getDefaultProject();
assertNotNull(defaultProject);
assertEquals("<project ID>", defaultProject.getProjectId());
}
@Test
public void testInvalidEventCollection() throws KeenException {
String tooLong = TestUtils.getString(257);
runValidateAndBuildEventTest(TestUtils.getSimpleEvent(), tooLong, "collection can't be longer than 256 chars",
"An event collection name cannot be longer than 256 characters.");
}
@Test
public void nullEvent() throws Exception {
runValidateAndBuildEventTest(null, "foo", "null event",
"You must specify a non-null, non-empty event.");
}
@Test
public void emptyEvent() throws Exception {
runValidateAndBuildEventTest(new HashMap<String, Object>(), "foo", "empty event",
"You must specify a non-null, non-empty event.");
}
@Test
public void eventWithKeenRootProperty() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("keen", "reserved");
runValidateAndBuildEventTest(event, "foo", "keen reserved",
"An event cannot contain a root-level property named 'keen'.");
}
@Test
public void eventWithDotInPropertyName() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("ab.cd", "whatever");
runValidateAndBuildEventTest(event, "foo", ". in property name",
"An event cannot contain a property with the period (.) character in it.");
}
@Test
public void eventWithTooLongPropertyName() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
String tooLong = TestUtils.getString(257);
event.put(tooLong, "whatever");
runValidateAndBuildEventTest(event, "foo", "too long property name",
"An event cannot contain a property name longer than 256 characters.");
}
@Test
public void eventWithTooLongStringValue() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
String tooLong = TestUtils.getString(10000);
event.put("long", tooLong);
runValidateAndBuildEventTest(event, "foo", "too long property value",
"An event cannot contain a string property value longer than 10,000 characters.");
}
@Test
public void eventWithSelfReferencingProperty() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("recursion", event);
runValidateAndBuildEventTest(event, "foo", "self referencing",
"An event's depth (i.e. layers of nesting) cannot exceed " + KeenConstants.MAX_EVENT_DEPTH);
}
@Test
public void eventWithInvalidPropertyInList() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
List<String> invalidList = new ArrayList<String>();
String tooLong = TestUtils.getString(10000);
invalidList.add(tooLong);
event.put("invalid_list", invalidList);
runValidateAndBuildEventTest(event, "foo", "invalid value in list",
"An event cannot contain a string property value longer than 10,000 characters.");
}
@Test
public void validEvent() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("valid key", "valid value");
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null);
assertNotNull(builtEvent);
assertEquals("valid value", builtEvent.get("valid key"));
// also make sure the event has been timestamped
@SuppressWarnings("unchecked")
Map<String, Object> keenNamespace = (Map<String, Object>) builtEvent.get("keen");
assertNotNull(keenNamespace);
assertNotNull(keenNamespace.get("timestamp"));
}
@Test
public void validEventWithTimestamp() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("valid key", "valid value");
Calendar now = Calendar.getInstance();
event.put("datetime", now);
client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null);
}
@Test
public void validEventWithKeenPropertiesWithoutTimestamp() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("valid key", "valid value");
Map<String, Object> keenProperties = new HashMap<String, Object>();
keenProperties.put("keen key", "keen value");
Map<String, Object> result = client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, keenProperties);
@SuppressWarnings("unchecked")
Map<String, Object> keenPropResult = (Map<String, Object>)result.get("keen");
assertNotNull(keenPropResult.get("timestamp"));
assertNull(keenProperties.get("timestamp"));
assertEquals(keenProperties.get("keen key"), "keen value");
assertEquals(keenPropResult.get("keen key"), "keen value");
assertEquals(keenProperties.get("keen key"), keenPropResult.get("keen key"));
}
@Test
public void validEventWithNestedKeenProperty() throws Exception {
Map<String, Object> event = TestUtils.getSimpleEvent();
Map<String, Object> nested = new HashMap<String, Object>();
nested.put("keen", "value");
event.put("nested", nested);
client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null);
}
@Test
public void testAddEventNoWriteKey() throws KeenException, IOException {
client.setDefaultProject(new KeenProject("508339b0897a2c4282000000", null, null));
Map<String, Object> event = new HashMap<String, Object>();
event.put("test key", "test value");
try {
client.addEvent("foo", event);
fail("add event without write key should fail");
} catch (NoWriteKeyException e) {
assertEquals("You can't send events to Keen IO if you haven't set a write key.",
e.getLocalizedMessage());
}
}
@Test
public void testAddEvent() throws Exception {
setMockResponse(201, POST_EVENT_SUCCESS);
client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
ArgumentCaptor<Request> capturedRequest = ArgumentCaptor.forClass(Request.class);
verify(mockHttpHandler).execute(capturedRequest.capture());
assertThat(capturedRequest.getValue().url.toString(), startsWith("https://api.keen.io"));
}
@Test
public void testAddEventNonSSL() throws Exception {
setMockResponse(201, POST_EVENT_SUCCESS);
client.setBaseUrl("http://api.keen.io");
client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
ArgumentCaptor<Request> capturedRequest = ArgumentCaptor.forClass(Request.class);
verify(mockHttpHandler).execute(capturedRequest.capture());
assertThat(capturedRequest.getValue().url.toString(), startsWith("http://api.keen.io"));
}
@Test(expected = ServerException.class)
public void testAddEventServerFailure() throws Exception {
setMockResponse(500, "Injected server error");
client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
}
@Test
public void testAddEventWithCallback() throws Exception {
setMockResponse(201, POST_EVENT_SUCCESS);
final CountDownLatch latch = new CountDownLatch(1);
client.addEvent(null, TEST_COLLECTION, TEST_EVENTS.get(0), null, new LatchKeenCallback(latch));
latch.await(2, TimeUnit.SECONDS);
}
@Test
public void testSendQueuedEvents() throws Exception {
// Mock the response from the server.
Map<String, Integer> expectedResponse = new HashMap<String, Integer>();
expectedResponse.put(TEST_COLLECTION, 3);
setMockResponse(200, getPostEventsResponse(buildSuccessMap(expectedResponse)));
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Check that the expected number of events are in the store.
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
assertEquals(3, handleMap.get(TEST_COLLECTION).size());
// Send the queued events.
client.sendQueuedEvents();
// Validate that the store is now empty.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(0, handleMap.size());
// Try sending events again; this should be a no-op.
setMockResponse(200, "{}");
client.sendQueuedEvents();
// Validate that the store is still empty.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(0, handleMap.size());
}
@Test
public void testSendQueuedEventsWithSingleFailure() throws Exception {
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Check that the expected number of events are in the store.
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
assertEquals(3, handleMap.get(TEST_COLLECTION).size());
// Mock a response containing an error.
Map<String, Integer> expectedResponse = new HashMap<String, Integer>();
expectedResponse.put(TEST_COLLECTION, 3);
Map<String, Object> responseMap = buildSuccessMap(expectedResponse);
replaceSuccessWithFailure(responseMap, TEST_COLLECTION, 2, "TestInjectedError",
"This is an error injected by the unit test code");
setMockResponse(200, getPostEventsResponse(responseMap));
// Send the events.
client.sendQueuedEvents();
// Validate that the store still contains the failed event, but not the other events.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
List<Object> handles = handleMap.get(TEST_COLLECTION);
assertEquals(1, handles.size());
Object handle = handles.get(0);
assertThat(store.get(handle), containsString("test-value-2"));
}
@Test
public void testSendQueuedEventsWithServerFailure() throws Exception {
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Mock a server failure.
setMockResponse(500, "Injected server failure");
// Send the events.
try {
client.sendQueuedEvents();
} catch (ServerException e) {
// This exception is expected; continue.
}
// Validate that the store still contains all the events.
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
List<Object> handles = handleMap.get(TEST_COLLECTION);
assertEquals(3, handles.size());
}
@Test
public void testSendQueuedEventsCountingAttemptsWithServerFailure() throws Exception {
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Mock a server failure.
setMockResponse(500, "Injected server failure");
// Send the events.
try {
client.sendQueuedEvents();
} catch (ServerException e) {
// This exception is expected; continue.
}
// Validate that the store still contains all the events.
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
List<Object> handles = handleMap.get(TEST_COLLECTION);
assertEquals(3, handles.size());
String attemptsJSON = store.getAttempts(TEST_PROJECT.getProjectId(), TEST_COLLECTION);
assertNotNull(attemptsJSON);
Map<String, Integer> attempts = JSON_MAPPER.readValue(attemptsJSON, Map.class);
assertEquals(3, attempts.entrySet().size());
assertEquals(2, attempts.values().toArray()[0]);
assertEquals(2, attempts.values().toArray()[1]);
assertEquals(2, attempts.values().toArray()[2]);
// Send the events again.
try {
client.sendQueuedEvents();
} catch (ServerException e) {
// This exception is expected; continue.
}
// Send the events yet again.
try {
client.sendQueuedEvents();
} catch (ServerException e) {
// This exception is expected; continue.
}
attemptsJSON = store.getAttempts(TEST_PROJECT.getProjectId(), TEST_COLLECTION);
assertNotNull(attemptsJSON);
attempts = JSON_MAPPER.readValue(attemptsJSON, Map.class);
assertEquals(3, attempts.entrySet().size());
assertEquals(0, attempts.values().toArray()[0]);
assertEquals(0, attempts.values().toArray()[1]);
assertEquals(0, attempts.values().toArray()[2]);
// Try to send the events again, but this time they'll get dropped
try {
client.sendQueuedEvents();
} catch (ServerException e) {
// This exception is expected; continue.
}
// Validate that the store still contains all the events.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(0, handleMap.size());
attemptsJSON = store.getAttempts(TEST_PROJECT.getProjectId(), TEST_COLLECTION);
assertNotNull(attemptsJSON);
attempts = JSON_MAPPER.readValue(attemptsJSON, Map.class);
assertEquals(0, attempts.entrySet().size());
}
@Test
public void testSendQueuedEventsConcurrentProjects() throws Exception {
// Queue some events in each of two separate projects
KeenProject otherProject = new KeenProject("<other project>", "<write>", "<read>");
client.queueEvent(TEST_PROJECT, TEST_COLLECTION, TEST_EVENTS.get(0), null, null);
client.queueEvent(TEST_PROJECT, TEST_COLLECTION_2, TEST_EVENTS.get(1), null, null);
client.queueEvent(otherProject, TEST_COLLECTION, TEST_EVENTS.get(2), null, null);
client.queueEvent(otherProject, TEST_COLLECTION, TEST_EVENTS.get(3), null, null);
// Check that the expected number of events are in the store, in the expected collections
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(2, handleMap.size());
assertEquals(1, handleMap.get(TEST_COLLECTION).size());
assertEquals(1, handleMap.get(TEST_COLLECTION_2).size());
handleMap = store.getHandles(otherProject.getProjectId());
assertEquals(1, handleMap.size());
assertEquals(2, handleMap.get(TEST_COLLECTION).size());
}
@Test
public void testGlobalPropertiesMap() throws Exception {
// a null map should be okay
runGlobalPropertiesMapTest(null, 1);
// an empty map should be okay
runGlobalPropertiesMapTest(new HashMap<String, Object>(), 1);
// a map w/ non-conflicting property names should be okay
Map<String, Object> globals = new HashMap<String, Object>();
globals.put("default name", "default value");
Map<String, Object> builtEvent = runGlobalPropertiesMapTest(globals, 2);
assertEquals("default value", builtEvent.get("default name"));
// a map that returns a conflicting property name should not overwrite the property on the event
globals = new HashMap<String, Object>();
globals.put("a", "c");
builtEvent = runGlobalPropertiesMapTest(globals, 1);
assertEquals("b", builtEvent.get("a"));
}
private Map<String, Object> runGlobalPropertiesMapTest(Map<String, Object> globalProperties,
int expectedNumProperties) throws Exception {
client.setGlobalProperties(globalProperties);
Map<String, Object> event = TestUtils.getSimpleEvent();
String eventCollection = String.format("foo%d", Calendar.getInstance().getTimeInMillis());
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null);
assertEquals(expectedNumProperties + 1, builtEvent.size());
return builtEvent;
}
@Test
public void testGlobalPropertiesEvaluator() throws Exception {
// a null evaluator should be okay
runGlobalPropertiesEvaluatorTest(null, 1);
// an evaluator that returns an empty map should be okay
GlobalPropertiesEvaluator evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
return new HashMap<String, Object>();
}
};
runGlobalPropertiesEvaluatorTest(evaluator, 1);
// an evaluator that returns a map w/ non-conflicting property names should be okay
evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
Map<String, Object> globals = new HashMap<String, Object>();
globals.put("default name", "default value");
return globals;
}
};
Map<String, Object> builtEvent = runGlobalPropertiesEvaluatorTest(evaluator, 2);
assertEquals("default value", builtEvent.get("default name"));
// an evaluator that returns a map w/ conflicting property name should not overwrite the property on the event
evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
Map<String, Object> globals = new HashMap<String, Object>();
globals.put("a", "c");
return globals;
}
};
builtEvent = runGlobalPropertiesEvaluatorTest(evaluator, 1);
assertEquals("b", builtEvent.get("a"));
}
private Map<String, Object> runGlobalPropertiesEvaluatorTest(GlobalPropertiesEvaluator evaluator,
int expectedNumProperties) throws Exception {
client.setGlobalPropertiesEvaluator(evaluator);
Map<String, Object> event = TestUtils.getSimpleEvent();
String eventCollection = String.format("foo%d", Calendar.getInstance().getTimeInMillis());
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null);
assertEquals(expectedNumProperties + 1, builtEvent.size());
return builtEvent;
}
@Test
public void testGlobalPropertiesTogether() throws Exception {
// properties from the evaluator should take precedence over properties from the map
// but properties from the event itself should take precedence over all
Map<String, Object> globalProperties = new HashMap<String, Object>();
globalProperties.put("default property", 5);
globalProperties.put("foo", "some new value");
GlobalPropertiesEvaluator evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("default property", 6);
map.put("foo", "some other value");
return map;
}
};
client.setGlobalProperties(globalProperties);
client.setGlobalPropertiesEvaluator(evaluator);
Map<String, Object> event = new HashMap<String, Object>();
event.put("foo", "bar");
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), "apples", event, null);
assertEquals("bar", builtEvent.get("foo"));
assertEquals(6, builtEvent.get("default property"));
assertEquals(3, builtEvent.size());
}
private void runValidateAndBuildEventTest(Map<String, Object> event, String eventCollection, String msg,
String expectedMessage) {
try {
client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null);
fail(msg);
} catch (KeenException e) {
assertEquals(expectedMessage, e.getLocalizedMessage());
}
}
private void setMockResponse(int statusCode, String body) throws IOException {
Response response = new Response(statusCode, body);
when(mockHttpHandler.execute(any(Request.class))).thenReturn(response);
}
private Map<String, Object> buildSuccessMap(Map<String, Integer> postedEvents) throws IOException {
// Build a map that will represent the response.
Map<String, Object> response = new HashMap<String, Object>();
// Create a single map for a successfully posted event; this can be reused for each event.
final Map<String, Boolean> success = new HashMap<String, Boolean>();
success.put("success", true);
// Build the response map by creating a list of the appropriate number of successes for
// each event collection.
for (Map.Entry<String, Integer> entry : postedEvents.entrySet()) {
List<Map<String, Boolean>> list = new ArrayList<Map<String, Boolean>>();
for (int i = 0; i < entry.getValue(); i++) {
list.add(success);
}
response.put(entry.getKey(), list);
}
// Return the success map.
return response;
}
@SuppressWarnings("unchecked")
private void replaceSuccessWithFailure(Map<String, Object> response, String collection,
int index, String errorName, String errorDescription) {
// Build the failure map.
Map<String, Object> failure = new HashMap<String, Object>();
failure.put("success", Boolean.FALSE);
Map<String, String> reason = new HashMap<String, String>();
reason.put("name", errorName);
reason.put("description", errorDescription);
failure.put("error", reason);
// Replace the element at the appropriate index with the failure.
List<Object> eventStatuses = (List<Object>) response.get(collection);
eventStatuses.set(index, failure);
}
private String getPostEventsResponse(Map<String, Object> postedEvents) throws IOException {
return JSON_MAPPER.writeValueAsString(postedEvents);
}
private static class LatchKeenCallback implements KeenCallback {
private final CountDownLatch latch;
LatchKeenCallback(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void onSuccess() {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
}
}
@Test
public void testProxy() throws Exception {
KeenClient testClient = new TestKeenClientBuilder().build();
testClient.setProxy("1.2.3.4", 1234);
assertNotNull(testClient.getProxy());
assertEquals("/1.2.3.4:1234", testClient.getProxy().address().toString());
testClient.setProxy(null);
assertNull(testClient.getProxy());
}
@Test
public void testNotConnected() throws Exception {
TestNetworkStatusHandler networkStatusHandler = new TestNetworkStatusHandler(false);
client = new TestKeenClientBuilder()
.withHttpHandler(mockHttpHandler)
.withNetworkStatusHandler(networkStatusHandler)
.build();
client.setBaseUrl(null);
client.setDebugMode(true);
client.setDefaultProject(TEST_PROJECT);
RamEventStore store = (RamEventStore) client.getEventStore();
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Mock a server success. This shouldn't get accessed until
// isNetworkConnected() is true. It is here because if the
// isNetworkConnected function doesn't work properly, we should get a
// 200 and clear all events, which would cause the first half of this
// test to fail.
Map<String, Integer> expectedResponse = new HashMap<String, Integer>();
expectedResponse.put(TEST_COLLECTION, 3);
setMockResponse(200, getPostEventsResponse(buildSuccessMap(expectedResponse)));
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
List<Object> handles = handleMap.get(TEST_COLLECTION);
assertEquals(3, handles.size());
// ensure that the events remain if there no network.
networkStatusHandler.setNetworkConnected(false);
// Attempt to send the events.
Exception e = null;
try {
client.sendQueuedEvents();
fail("sendQueueEvents should throw an error when there is no network.");
} catch (Exception ex) {
e = ex;
}
assertNotNull(e);
// Validate that the store still contains all the events.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
handles = handleMap.get(TEST_COLLECTION);
assertEquals(3, handles.size());
// now, ensure that the events get cleared if there is network.
networkStatusHandler.setNetworkConnected(true);
// Actually send the events.
client.sendQueuedEvents();
// Validate that the store no longer contains the events.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(0, handleMap.size());
}
}
| mit |
Wh1spr/Olympians | src/main/java/wh1spr/olympians/zeus/commands/CommandDisableCommand.java | 756 | package wh1spr.olympians.zeus.commands;
import java.util.List;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import wh1spr.olympians.BotControl;
import wh1spr.olympians.command.Command;
import wh1spr.olympians.zeus.Zeus;
public class CommandDisableCommand extends Command {
@Override
public void onCall(JDA jda, Guild guild, TextChannel channel, Member invoker, Message message, List<String> args) {
if (!BotControl.usage.isAdmin(invoker.getUser())) return;
if (args.size() > 0) {
for (String cmd : args) {
Zeus.adminRegistry.removeCommand(cmd);
}
}
}
}
| mit |
CCI-MIT/XCoLab | util/xcolab-utils/src/main/java/org/xcolab/util/http/exceptions/EurekaNotInitializedException.java | 314 | package org.xcolab.util.http.exceptions;
public class EurekaNotInitializedException extends RuntimeException {
public EurekaNotInitializedException() {
super("Eureka-enabled RestTemplate has not been initialized. "
+ "Service discovery does NOT work during startup phase! ");
}
}
| mit |
Pivopil/spring-boot-rest-rxjava | rest/src/main/java/io/github/pivopil/REST_API.java | 333 | package io.github.pivopil;
/**
* Created on 03.06.16.
*/
public class REST_API {
private REST_API() {
}
public static final String ME = "/api/me";
public static final String USERS = "/api/users";
public static final String HEALTH = "/health";
public static final String HEALTH_JSON = "/health.json";
}
| mit |
nolestek/mywodcoach | src/test/java/com/example/activity/MainMovementListActivityTest.java | 2092 | package com.example.activity;
import android.app.ListActivity;
import android.view.View;
import android.widget.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowActivity;
import org.robolectric.shadows.ShadowIntent;
import static org.robolectric.Robolectric.shadowOf;
import static org.robolectric.Robolectric.clickOn;
import android.content.Intent;
import android.app.Activity;
import android.widget.ListView;
import com.example.R;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RunWith(RobolectricTestRunner.class)
public class MainMovementListActivityTest {
private Activity activity;
private ListView movements_listView;
@Before
public void setup(){
activity = Robolectric.buildActivity(MainMovementListActivity.class)
.create().visible()
.get();
movements_listView = (ListView) activity.findViewById(R.id.movement_list);
}
@Test
public void shouldShowAListOfMovements() throws Exception {
movements_listView = (ListView) activity.findViewById(R.id.movement_list);
// ListViews only create as many children as will fit in their bounds, so make it big...
movements_listView.layout(0, 0, 100, 1000);
TextView nameRow = (TextView) movements_listView.getChildAt(0);
assertThat(nameRow.getText().toString(), equalTo("Kipping Pull Ups"));
}
@Test
public void thingsShouldNotBeNull(){
assertNotNull(movements_listView.getChildAt(0));
assertNotNull(movements_listView.getItemIdAtPosition(0));
assertNotNull(activity.findViewById(R.id.movement_list));
}
}
| mit |
swrj/30DaysOfCode | Day_5/Loops.java | 370 | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=1;i<=10;i++)
{
System.out.println(n+" x "+i+" = "+(n*i));
}
}
}
| mit |
ratimid/SoftUni | Java/ProgramingBasics - April 2018/03.SimpleConditionalStatements/src/p12_SpeedInfo.java | 627 | import java.util.Scanner;
public class p12_SpeedInfo {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double speed = Double.parseDouble(console.nextLine());
if(speed <= 10) {
System.out.println("slow");
}
else if(speed <=50) {
System.out.println("average");
}
else if(speed <= 150) {
System.out.println("fast");
}
else if(speed <=1000){
System.out.println("ultra fast");
}
else {
System.out.println("extremely fast");
}
}
}
| mit |
kedarmhaswade/impatiently-j8 | src/main/java/juc/FutureExploration.java | 1910 | package juc;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* <p>
* This class is purely an exploration of a simple {@link Callable} and {@link Future}.
* It tries to explore what happens when the {@link Future#get()} is called, how exactly is
* the caller blocked etc.
* </p>
* Created by kedar on 2/24/17.
*/
public class FutureExploration {
public static void main(String[] args) {
Callable<Long> filesizeTask = () -> {
File f = Paths.get("/tmp", "foobar123").toFile(); // make sure the file doesn't exist
while (!f.exists()) {
System.out.println("sleeping for a few seconds for the file: " +
f.getAbsolutePath() + " to get created ...");
Thread.sleep(5000);
if (Thread.currentThread().isInterrupted())
return 0L;
}
return Files.lines(f.toPath()).mapToLong(String::length).sum();
};
// This task is a short-lived (hopefully), mostly waiting on something to happen,
// so use CachedThreadPool
ExecutorService exec = Executors.newCachedThreadPool();
try {
long size = exec.submit(filesizeTask).get(4_000, TimeUnit.MILLISECONDS); // this current thread (main) is now blocked
// take thread dump at this point and see what's happening and then debug the flow
System.out.println("size of the file: " + size + " bytes");
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
}
}
| mit |
ailyenko/JavaRush | src/com/javarush/test/level07/lesson12/home02/Solution.java | 1159 | package com.javarush.test.level07.lesson12.home02;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/* ะะตัะตััะฐะฒะธัั M ะฟะตัะฒัั
ัััะพะบ ะฒ ะบะพะฝะตั ัะฟะธัะบะฐ
ะะฒะตััะธ ั ะบะปะฐะฒะธะฐัััั 2 ัะธัะปะฐ N ะธ M.
ะะฒะตััะธ N ัััะพะบ ะธ ะทะฐะฟะพะปะฝะธัั ะธะผะธ ัะฟะธัะพะบ.
ะะตัะตััะฐะฒะธัั M ะฟะตัะฒัั
ัััะพะบ ะฒ ะบะพะฝะตั ัะฟะธัะบะฐ.
ะัะฒะตััะธ ัะฟะธัะพะบ ะฝะฐ ัะบัะฐะฝ, ะบะฐะถะดะพะต ะทะฝะฐัะตะฝะธะต ั ะฝะพะฒะพะน ัััะพะบะธ.
*/
class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int m = Integer.parseInt(reader.readLine());
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(reader.readLine());
}
for (int i = 0; i < m; i++) {
list.add(list.get(i));
}
for (int i = 0; i < m; i++) {
list.remove(0);
}
for (String aList : list) {
System.out.println(aList);
}
}
} | mit |
bgithub1/span-java | src/main/java/com/billybyte/spanjava/recordtypes/expanded/SecondCombComm.java | 3725 | package com.billybyte.spanjava.recordtypes.expanded;
import java.util.ArrayList;
import java.util.List;
import com.billybyte.spanjava.recordtypes.expanded.subtypes.TierDayWeekRange;
import com.billybyte.spanjava.recordtypes.expanded.subtypes.TierMonthRange;
public class SecondCombComm {
private final String recordId; // "3 "
private final String combCommCode; // = line.substring(2,8);
private final String intraCommSpreadChargeMethCode; // = line.substring(8,10);
private final List<TierMonthRange> tierMonthRangeList;
private final String initToMaintRatioMember; // = line.substring(68,72);
private final String initToMaintRatioHedger; // = line.substring(72,76);
private final String initToMaintRatioSpec; // = line.substring(76,80);
private final List<TierDayWeekRange> tierDayWeekRangeList;
public SecondCombComm(String line) {
this.recordId = line.substring(0,2);
this.combCommCode = line.substring(2,8);
this.intraCommSpreadChargeMethCode = line.substring(8,10);
this.tierMonthRangeList = new ArrayList<TierMonthRange>();
int tierMonthRefIndex = 10;
this.tierDayWeekRangeList = new ArrayList<TierDayWeekRange>();
String initToMaintRatioMember = null;
String initToMaintRatioHedger = null;
String initToMaintRatioSpec = null;
if(line.length()>68) {
for(int i=0;i<4;i++) {
String tierNumber = line.substring(tierMonthRefIndex,tierMonthRefIndex+2);
String startMonth = line.substring(tierMonthRefIndex+2,tierMonthRefIndex+8);
String endMonth = line.substring(tierMonthRefIndex+8,tierMonthRefIndex+14);
TierMonthRange tierMonthRange = new TierMonthRange(tierNumber, startMonth, endMonth);
tierMonthRangeList.add(tierMonthRange);
tierMonthRefIndex = tierMonthRefIndex+14;
}
initToMaintRatioMember = line.substring(68,72);
initToMaintRatioHedger = line.substring(72,76);
initToMaintRatioSpec = line.substring(76,80);
if(line.length()>80) {
int dayRefIndex = 80;
while(line.length()>=(dayRefIndex+4)) {
String startDayWeekCode = line.substring(dayRefIndex, dayRefIndex+2);
String endDayWeekCode = line.substring(dayRefIndex+2, dayRefIndex+4);
TierDayWeekRange tierDayWeekRange = new TierDayWeekRange(startDayWeekCode, endDayWeekCode);
tierDayWeekRangeList.add(tierDayWeekRange);
dayRefIndex = dayRefIndex+4;
}
}
}
this.initToMaintRatioMember = initToMaintRatioMember;
this.initToMaintRatioHedger = initToMaintRatioHedger;
this.initToMaintRatioSpec = initToMaintRatioSpec;
}
public String toString() {
String ret = recordId+","+combCommCode+","+intraCommSpreadChargeMethCode; //+","+tierNumber1+","+startMonth1+","+endMonth1+","+
for(TierMonthRange range:tierMonthRangeList) {
ret = ret+","+range.toString();
}
ret = ret+","+initToMaintRatioMember+","+initToMaintRatioHedger+","+initToMaintRatioSpec;
for(TierDayWeekRange range:tierDayWeekRangeList) {
ret = ret+","+range.toString();
}
return ret;
}
public String getRecordId() {
return recordId;
}
public String getCombCommCode() {
return combCommCode;
}
public String getIntraCommSpreadChargeMethCode() {
return intraCommSpreadChargeMethCode;
}
public List<TierMonthRange> getTierMonthRangeList() {
return tierMonthRangeList;
}
public String getInitToMaintRatioMember() {
return initToMaintRatioMember;
}
public String getInitToMaintRatioHedger() {
return initToMaintRatioHedger;
}
public String getInitToMaintRatioSpec() {
return initToMaintRatioSpec;
}
public List<TierDayWeekRange> getTierDayWeekRangeList() {
return tierDayWeekRangeList;
}
}
| mit |
NeilSoul/Mooc | app/src/main/java/edu/tsinghua/medialab/mooc/utils/view/observablescrollview/ObservableRecyclerView.java | 17608 | /*
* Copyright 2014 Soichiro Kashima
*
* 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 edu.tsinghua.medialab.mooc.utils.view.observablescrollview;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
/**
* RecyclerView that its scroll position can be observed.
* Before using this, please consider to use the RecyclerView.OnScrollListener
* provided by the support library officially.
*/
public class ObservableRecyclerView extends RecyclerView implements Scrollable {
// Fields that should be saved onSaveInstanceState
private int mPrevFirstVisiblePosition;
private int mPrevFirstVisibleChildHeight = -1;
private int mPrevScrolledChildrenHeight;
private int mPrevScrollY;
private int mScrollY;
private SparseIntArray mChildrenHeights;
// Fields that don't need to be saved onSaveInstanceState
private ObservableScrollViewCallbacks mCallbacks;
private ScrollState mScrollState;
private boolean mFirstScroll;
private boolean mDragging;
private boolean mIntercepted;
private MotionEvent mPrevMoveEvent;
private ViewGroup mTouchInterceptionViewGroup;
public ObservableRecyclerView(Context context) {
super(context);
init();
}
public ObservableRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ObservableRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
mPrevFirstVisiblePosition = ss.prevFirstVisiblePosition;
mPrevFirstVisibleChildHeight = ss.prevFirstVisibleChildHeight;
mPrevScrolledChildrenHeight = ss.prevScrolledChildrenHeight;
mPrevScrollY = ss.prevScrollY;
mScrollY = ss.scrollY;
mChildrenHeights = ss.childrenHeights;
super.onRestoreInstanceState(ss.getSuperState());
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.prevFirstVisiblePosition = mPrevFirstVisiblePosition;
ss.prevFirstVisibleChildHeight = mPrevFirstVisibleChildHeight;
ss.prevScrolledChildrenHeight = mPrevScrolledChildrenHeight;
ss.prevScrollY = mPrevScrollY;
ss.scrollY = mScrollY;
ss.childrenHeights = mChildrenHeights;
return ss;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mCallbacks != null) {
if (getChildCount() > 0) {
int firstVisiblePosition = getChildPosition(getChildAt(0));
int lastVisiblePosition = getChildPosition(getChildAt(getChildCount() - 1));
for (int i = firstVisiblePosition, j = 0; i <= lastVisiblePosition; i++, j++) {
if (mChildrenHeights.indexOfKey(i) < 0 || getChildAt(j).getHeight() != mChildrenHeights.get(i)) {
mChildrenHeights.put(i, getChildAt(j).getHeight());
}
}
View firstVisibleChild = getChildAt(0);
if (firstVisibleChild != null) {
if (mPrevFirstVisiblePosition < firstVisiblePosition) {
// scroll down
int skippedChildrenHeight = 0;
if (firstVisiblePosition - mPrevFirstVisiblePosition != 1) {
for (int i = firstVisiblePosition - 1; i > mPrevFirstVisiblePosition; i--) {
if (0 < mChildrenHeights.indexOfKey(i)) {
skippedChildrenHeight += mChildrenHeights.get(i);
} else {
// Approximate each item's height to the first visible child.
// It may be incorrect, but without this, scrollY will be broken
// when scrolling from the bottom.
skippedChildrenHeight += firstVisibleChild.getHeight();
}
}
}
mPrevScrolledChildrenHeight += mPrevFirstVisibleChildHeight + skippedChildrenHeight;
mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight();
} else if (firstVisiblePosition < mPrevFirstVisiblePosition) {
// scroll up
int skippedChildrenHeight = 0;
if (mPrevFirstVisiblePosition - firstVisiblePosition != 1) {
for (int i = mPrevFirstVisiblePosition - 1; i > firstVisiblePosition; i--) {
if (0 < mChildrenHeights.indexOfKey(i)) {
skippedChildrenHeight += mChildrenHeights.get(i);
} else {
// Approximate each item's height to the first visible child.
// It may be incorrect, but without this, scrollY will be broken
// when scrolling from the bottom.
skippedChildrenHeight += firstVisibleChild.getHeight();
}
}
}
mPrevScrolledChildrenHeight -= firstVisibleChild.getHeight() + skippedChildrenHeight;
mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight();
} else if (firstVisiblePosition == 0) {
mPrevFirstVisibleChildHeight = firstVisibleChild.getHeight();
}
if (mPrevFirstVisibleChildHeight < 0) {
mPrevFirstVisibleChildHeight = 0;
}
mScrollY = mPrevScrolledChildrenHeight - firstVisibleChild.getTop();
mPrevFirstVisiblePosition = firstVisiblePosition;
mCallbacks.onScrollChanged(mScrollY, mFirstScroll, mDragging);
if (mFirstScroll) {
mFirstScroll = false;
}
if (mPrevScrollY < mScrollY) {
//down
mScrollState = ScrollState.UP;
} else if (mScrollY < mPrevScrollY) {
//up
mScrollState = ScrollState.DOWN;
} else {
mScrollState = ScrollState.STOP;
}
mPrevScrollY = mScrollY;
}
}
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mCallbacks != null) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
// Whether or not motion events are consumed by children,
// flag initializations which are related to ACTION_DOWN events should be executed.
// Because if the ACTION_DOWN is consumed by children and only ACTION_MOVEs are
// passed to parent (this view), the flags will be invalid.
// Also, applications might implement initialization codes to onDownMotionEvent,
// so call it here.
mFirstScroll = mDragging = true;
mCallbacks.onDownMotionEvent();
break;
}
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mCallbacks != null) {
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIntercepted = false;
mDragging = false;
mCallbacks.onUpOrCancelMotionEvent(mScrollState);
break;
case MotionEvent.ACTION_MOVE:
if (mPrevMoveEvent == null) {
mPrevMoveEvent = ev;
}
float diffY = ev.getY() - mPrevMoveEvent.getY();
mPrevMoveEvent = MotionEvent.obtainNoHistory(ev);
if (getCurrentScrollY() - diffY <= 0) {
// Can't scroll anymore.
if (mIntercepted) {
// Already dispatched ACTION_DOWN event to parents, so stop here.
return false;
}
// Apps can set the interception target other than the direct parent.
final ViewGroup parent;
if (mTouchInterceptionViewGroup == null) {
parent = (ViewGroup) getParent();
} else {
parent = mTouchInterceptionViewGroup;
}
// Get offset to parents. If the parent is not the direct parent,
// we should aggregate offsets from all of the parents.
float offsetX = 0;
float offsetY = 0;
for (View v = this; v != null && v != parent; v = (View) v.getParent()) {
offsetX += v.getLeft() - v.getScrollX();
offsetY += v.getTop() - v.getScrollY();
}
final MotionEvent event = MotionEvent.obtainNoHistory(ev);
event.offsetLocation(offsetX, offsetY);
if (parent.onInterceptTouchEvent(event)) {
mIntercepted = true;
// If the parent wants to intercept ACTION_MOVE events,
// we pass ACTION_DOWN event to the parent
// as if these touch events just have began now.
event.setAction(MotionEvent.ACTION_DOWN);
// Return this onTouchEvent() first and set ACTION_DOWN event for parent
// to the queue, to keep events sequence.
post(new Runnable() {
@Override
public void run() {
parent.dispatchTouchEvent(event);
}
});
}
return false;
}
break;
}
}
return super.onTouchEvent(ev);
}
@Override
public void setScrollViewCallbacks(ObservableScrollViewCallbacks listener) {
mCallbacks = listener;
}
@Override
public void setTouchInterceptionViewGroup(ViewGroup viewGroup) {
mTouchInterceptionViewGroup = viewGroup;
}
@Override
public void scrollVerticallyTo(int y) {
View firstVisibleChild = getChildAt(0);
if (firstVisibleChild != null) {
int baseHeight = firstVisibleChild.getHeight();
int position = y / baseHeight;
scrollVerticallyToPosition(position);
}
}
/**
* <p>Same as {@linkplain #scrollToPosition(int)} but it scrolls to the position not only make
* the position visible.</p>
* <p>It depends on {@code LayoutManager} how {@linkplain #scrollToPosition(int)} works,
* and currently we know that {@linkplain LinearLayoutManager#scrollToPosition(int)} just
* make the position visible.</p>
* <p>In LinearLayoutManager, scrollToPositionWithOffset() is provided for scrolling to the position.
* This method checks which LayoutManager is set,
* and handles which method should be called for scrolling.</p>
* <p>Other know classes (StaggeredGridLayoutManager and GridLayoutManager) are not tested.</p>
*
* @param position position to scroll
*/
public void scrollVerticallyToPosition(int position) {
LayoutManager lm = getLayoutManager();
if (lm != null && lm instanceof LinearLayoutManager) {
((LinearLayoutManager) lm).scrollToPositionWithOffset(position, 0);
} else {
scrollToPosition(position);
}
}
@Override
public int getCurrentScrollY() {
return mScrollY;
}
private void init() {
mChildrenHeights = new SparseIntArray();
}
/**
* This saved state class is a Parcelable and should not extend
* {@link android.view.View.BaseSavedState} nor {@link android.view.AbsSavedState}
* because its super class AbsSavedState's constructor
* {@link android.view.AbsSavedState#AbsSavedState(Parcel)} currently passes null
* as a class loader to read its superstate from Parcelable.
* This causes {@link android.os.BadParcelableException} when restoring saved states.
* <p/>
* The super class "RecyclerView" is a part of the support library,
* and restoring its saved state requires the class loader that loaded the RecyclerView.
* It seems that the class loader is not required when restoring from RecyclerView itself,
* but it is required when restoring from RecyclerView's subclasses.
*/
static class SavedState implements Parcelable {
public static final SavedState EMPTY_STATE = new SavedState() {
};
int prevFirstVisiblePosition;
int prevFirstVisibleChildHeight = -1;
int prevScrolledChildrenHeight;
int prevScrollY;
int scrollY;
SparseIntArray childrenHeights;
// This keeps the parent(RecyclerView)'s state
Parcelable superState;
/**
* Called by EMPTY_STATE instantiation.
*/
private SavedState() {
superState = null;
}
/**
* Called by onSaveInstanceState.
*/
private SavedState(Parcelable superState) {
this.superState = superState != EMPTY_STATE ? superState : null;
}
/**
* Called by CREATOR.
*/
private SavedState(Parcel in) {
// Parcel 'in' has its parent(RecyclerView)'s saved state.
// To restore it, class loader that loaded RecyclerView is required.
Parcelable superState = in.readParcelable(RecyclerView.class.getClassLoader());
this.superState = superState != null ? superState : EMPTY_STATE;
prevFirstVisiblePosition = in.readInt();
prevFirstVisibleChildHeight = in.readInt();
prevScrolledChildrenHeight = in.readInt();
prevScrollY = in.readInt();
scrollY = in.readInt();
childrenHeights = new SparseIntArray();
final int numOfChildren = in.readInt();
if (0 < numOfChildren) {
for (int i = 0; i < numOfChildren; i++) {
final int key = in.readInt();
final int value = in.readInt();
childrenHeights.put(key, value);
}
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeParcelable(superState, flags);
out.writeInt(prevFirstVisiblePosition);
out.writeInt(prevFirstVisibleChildHeight);
out.writeInt(prevScrolledChildrenHeight);
out.writeInt(prevScrollY);
out.writeInt(scrollY);
final int numOfChildren = childrenHeights == null ? 0 : childrenHeights.size();
out.writeInt(numOfChildren);
if (0 < numOfChildren) {
for (int i = 0; i < numOfChildren; i++) {
out.writeInt(childrenHeights.keyAt(i));
out.writeInt(childrenHeights.valueAt(i));
}
}
}
public Parcelable getSuperState() {
return superState;
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| mit |
normanmaurer/java-memcached-client | src/main/java/net/spy/memcached/protocol/binary/StatsOperationImpl.java | 2290 | /**
* Copyright (C) 2006-2009 Dustin Sallings
*
* 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 DEALING
* IN THE SOFTWARE.
*/
package net.spy.memcached.protocol.binary;
import java.io.IOException;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.StatsOperation;
/**
* A StatsOperationImpl.
*/
public class StatsOperationImpl extends OperationImpl
implements StatsOperation {
private static final byte CMD = 0x10;
private final String key;
public StatsOperationImpl(String arg, StatsOperation.Callback c) {
super(CMD, generateOpaque(), c);
key = (arg == null) ? "" : arg;
}
@Override
public void initialize() {
prepareBuffer(key, 0, EMPTY_BYTES);
}
@Override
protected void finishedPayload(byte[] pl) throws IOException {
if (keyLen > 0) {
final byte[] keyBytes = new byte[keyLen];
final byte[] data = new byte[pl.length - keyLen];
System.arraycopy(pl, 0, keyBytes, 0, keyLen);
System.arraycopy(pl, keyLen, data, 0, pl.length - keyLen);
Callback cb = (Callback) getCallback();
cb.gotStat(new String(keyBytes, "UTF-8"), new String(data, "UTF-8"));
} else {
getCallback().receivedStatus(STATUS_OK);
transitionState(OperationState.COMPLETE);
}
resetInput();
}
}
| mit |
jonbo372/sipstack | sipstack-core/src/main/java/io/sipstack/transport/event/FlowEvent.java | 4578 | package io.sipstack.transport.event;
import io.pkts.packet.sip.SipMessage;
import io.pkts.packet.sip.SipRequest;
import io.pkts.packet.sip.SipResponse;
import io.sipstack.transport.Flow;
import io.sipstack.transport.event.impl.SipRequestBuilderFlowEventImpl;
import io.sipstack.transport.event.impl.SipRequestFlowEventImpl;
import io.sipstack.transport.event.impl.SipResponseBuilderFlowEventImpl;
import io.sipstack.transport.event.impl.SipResponseFlowEventImpl;
/**
* @author jonas@jonasborjesson.com
*/
public interface FlowEvent {
Flow flow();
// =====================================
// === SIP flow builder events
// =====================================
default boolean isSipBuilderFlowEvent() {
return false;
}
default SipBuilderFlowEvent toSipBuilderFlowEvent() {
throw new ClassCastException("Cannot cast " + getClass().getName() + " into a " + SipFlowEvent.class.getName());
}
/*
static SipBuilderFlowEvent create(final Flow flow, final SipMessage.Builder<? extends SipMessage> builder) {
if (builder.isSipRequestBuilder()) {
return create(flow, builder.toSipRequestBuilder());
}
return create(flow, builder.toSipResponseBuilder());
}
*/
// =====================================
// === SIP request builder flow events
// =====================================
default boolean isSipRequestBuilderFlowEvent() {
return false;
}
default SipRequestBuilderFlowEvent toSipRequestBuilderFlowEvent() {
throw new ClassCastException("Cannot cast " + getClass().getName() + " into a " + SipRequestBuilderFlowEvent.class.getName());
}
// =====================================
// === SIP response builder flow events
// =====================================
default boolean isSipResponseBuilderFlowEvent() {
return false;
}
default SipResponseBuilderFlowEvent toSipResponseBuilderFlowEvent() {
throw new ClassCastException("Cannot cast " + getClass().getName() + " into a " + SipResponseBuilderFlowEvent.class.getName());
}
static SipResponseBuilderFlowEvent create(final Flow flow, final SipMessage.Builder<SipResponse> builder) {
return new SipResponseBuilderFlowEventImpl(flow, builder);
}
// =====================================
// === SIP flow events
// =====================================
/**
* Check if this is a Sip Event, which is either a request or response message.
*
* @return
*/
default boolean isSipFlowEvent() {
return false;
}
default SipFlowEvent toSipFlowEvent() {
throw new ClassCastException("Cannot cast " + getClass().getName() + " into a " + SipFlowEvent.class.getName());
}
static SipFlowEvent create(final Flow flow, final SipMessage message) {
if (message.isRequest()) {
return create(flow, message.toRequest());
}
return create(flow, message.toResponse());
}
// =====================================
// === SIP request flow events
// =====================================
default boolean isSipRequestFlowEvent() {
return false;
}
default SipRequestFlowEvent toSipRequestFlowEvent() {
throw new ClassCastException("Cannot cast " + getClass().getName() + " into a " + SipRequestFlowEvent.class.getName());
}
static SipRequestFlowEvent create(final Flow flow, final SipRequest request) {
return new SipRequestFlowEventImpl(flow, request);
}
// =====================================
// === SIP response flow events
// =====================================
default boolean isSipResponseFlowEvent() {
return false;
}
default SipResponseFlowEvent toSipResponseFlowEvent() {
throw new ClassCastException("Cannot cast " + getClass().getName() + " into a " + SipResponseFlowEvent.class.getName());
}
static SipResponseFlowEvent create(final Flow flow, final SipResponse response) {
return new SipResponseFlowEventImpl(flow, response);
}
// =====================================
// === Life-cycle events
// =====================================
default boolean isFlowLifeCycleEvent() {
return false;
}
default FlowLifeCycleEvent toFlowLifeCycleEvent() {
throw new ClassCastException("Cannot cast " + getClass().getName() + " into a " + FlowLifeCycleEvent.class.getName());
}
default boolean isFlowTerminatedEvent() {
return false;
}
}
| mit |
Raenn/SubredditHighlightsWear | wear/src/main/java/com/raenn/subredditimages/ListenerService.java | 2874 | package com.raenn.subredditimages;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.Asset;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataItemAsset;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
public class ListenerService extends WearableListenerService {
private final String TAG = "ListenerService";
public ListenerService() {
Log.i(TAG, "Listener service starting");
}
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.v(TAG, "Received some data");
for(DataEvent event : dataEvents) {
if(event.getType() == DataEvent.TYPE_CHANGED) {
DataMap map = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
Bitmap bmp = loadBitmapFromAsset(map.getAsset("image"));
Intent intent = new Intent("HandlePicture");
intent.putExtra("picture", bmp);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
}
public Bitmap loadBitmapFromAsset(Asset asset) {
if (asset == null) {
throw new IllegalArgumentException("Asset must be non-null");
}
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
ConnectionResult result =
mGoogleApiClient.blockingConnect(10000, TimeUnit.MILLISECONDS);
if (!result.isSuccess()) {
return null;
}
// convert asset into a file descriptor and block until it's ready
InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
mGoogleApiClient, asset).await().getInputStream();
mGoogleApiClient.disconnect();
if (assetInputStream == null) {
Log.w("Bitmap loader", "Requested an unknown Asset.");
return null;
}
// decode the stream into a bitmap
return BitmapFactory.decodeStream(assetInputStream);
}
}
| mit |
jenkinsci/analysis-model | src/main/java/edu/hm/hafner/analysis/IssueParser.java | 4167 | package edu.hm.hafner.analysis;
import java.io.Serializable;
import java.util.Locale;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import edu.umd.cs.findbugs.annotations.CheckForNull;
/**
* Parses a file and returns the issues reported in this file.
*
* @author Ullrich Hafner
*/
public abstract class IssueParser implements Serializable {
private static final long serialVersionUID = 200992696185460268L;
/**
* Parses the specified file for issues.
*
* @param readerFactory
* provides a reader to the reports
*
* @return the issues
* @throws ParsingException
* Signals that during parsing a non recoverable error has been occurred
* @throws ParsingCanceledException
* Signals that the parsing has been aborted by the user
*/
public abstract Report parse(ReaderFactory readerFactory)
throws ParsingException, ParsingCanceledException;
/**
* Parses the specified file for issues. Invokes the parser using {@link #parse(ReaderFactory)} and sets the file
* name of the report.
*
* @param readerFactory
* provides a reader to the reports
*
* @return the issues
* @throws ParsingException
* Signals that during parsing a non recoverable error has been occurred
* @throws ParsingCanceledException
* Signals that the parsing has been aborted by the user
*/
public Report parseFile(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException {
Report report = parse(readerFactory);
report.setOriginReportFile(readerFactory.getFileName());
return report;
}
/**
* Returns whether this parser accepts the specified file as valid input. Parsers may reject a file if it is in the
* wrong format to avoid exceptions during parsing.
*
* @param readerFactory
* provides a reader to the reports
*
* @return {@code true} if this parser accepts this file as valid input, or {@code false} if the file could not be
* parsed by this parser
*/
public boolean accepts(final ReaderFactory readerFactory) {
return true;
}
/**
* Returns whether the specified file is an XML file. This method just checks if the first 10 lines contain the XML
* tag rather than parsing the whole document.
*
* @param readerFactory
* the file to check
*
* @return {@code true} if the file is an XML file, {@code false} otherwise
*/
protected boolean isXmlFile(final ReaderFactory readerFactory) {
try (Stream<String> lines = readerFactory.readStream()) {
return lines.limit(10).anyMatch(line -> line.contains("<?xml"));
}
catch (ParsingException ignored) {
return false;
}
}
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters, ignoring case.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered equal. The comparison is <strong>case insensitive</strong>.</p>
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @param a
* the first CharSequence, may be {@code null}
* @param b
* the second CharSequence, may be {@code null}
*
* @return {@code true} if the CharSequences are equal (case-insensitive), or both {@code null}
*/
public static boolean equalsIgnoreCase(@CheckForNull final String a, @CheckForNull final String b) {
return StringUtils.equals(normalize(a), normalize(b));
}
private static String normalize(@CheckForNull final String input) {
return StringUtils.defaultString(input).toUpperCase(Locale.ENGLISH);
}
}
| mit |
mikehelmick/eaa-samples | src/main/java/eaa/chapter12/foreignkeymapping/DomainObject.java | 588 | package eaa.chapter12.foreignkeymapping;
import java.sql.Connection;
public abstract class DomainObject {
private long id = -1;
public DomainObject() {
id = -1;
}
public DomainObject( long id ) {
this.id = id;
}
public final long getId() {
return id;
}
public final void setId(long id) {
this.id = id;
}
public long nextId( Connection c ) {
return KeyGenerator.getNextId( c, getMapper().table() );
}
public abstract boolean equals( DomainObject o );
public abstract AbstractMapper<DomainObject> getMapper();
public abstract String toString();
}
| mit |
erichsueh336/LIS_project_1b | project_1a/src/com/cs5300/pj1/HelloWorld.java | 36247 | package com.cs5300.pj1;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// For simpleDB connection
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.BatchPutAttributesRequest;
import com.amazonaws.services.simpledb.model.CreateDomainRequest;
import com.amazonaws.services.simpledb.model.DeleteAttributesRequest;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.PutAttributesRequest;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.ReplaceableItem;
import com.amazonaws.services.simpledb.model.SelectRequest;
// Self-defined class
import com.cs5300.pj1.SessionData;
import com.cs5300.pj1.ServerStatus;
/**
* Servlet implementation class HelloWorld
*/
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
// Local Data Table
private static Map<String, SessionData> session_table = new HashMap<String, SessionData>();
private static Map<String, ServerStatus> group_view = new HashMap<String, ServerStatus>();
// Parameters
private static String local_IP = null; // Local IP address
private static String cookie_name = "CS5300PJ1ERIC";// Default cookie name
private static String domain_name = "dbView"; // Name of simpleDB's group view
private static int garbage_collect_period = 600; // Time to run garbage collection again
private static int view_exchange_period = 600; // Time to run view exchange thread again
private static int sess_num = 0; // Part of session ID
private static int sess_timeout_secs = 1800000; // Default session timeout duration
private static int UDP_port = 8888; // Default UDP port
private static int RPC_call_ID = 0; // RPC call ID, increment after each call
private static boolean connectedToDB = false; // Check whether a new booted server has view or not
private static boolean isLocal = true; // True, for local test
/**
* @throws IOException
* @see HttpServlet#HttpServlet()
*/
public HelloWorld() throws IOException {
super();
local_IP = getLocalIP(isLocal);
System.out.println("Local IP = " + local_IP);
// UDP server initialize
startUDPServer(UDP_port);
connectedToDB = getViewFromSimpleDB();
startGarbageCollect(garbage_collect_period);
startViewExchange(view_exchange_period);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Update local server status
group_view.put(local_IP, new ServerStatus("UP", System.currentTimeMillis()) );
// initialization
String cookie_str = "";
String cookie_timeout = "";
String test = "";
// Get cookie from HTTP request
Cookie c = getCookie(request, cookie_name);
if (c == null) {
// No cookie --> first time user
// SessID = < sess_num, SvrIP >
// Cookie value = < SessID, version, < SvrIDprimary, SvrIDbackup > >
String cookie_value = null;
SessionData first_session_data = new SessionData(0, "Hello new user!!", System.currentTimeMillis() + sess_timeout_secs);
// TODO when deploy to EB, uncomment line below
// while (!connectedToDB); // wait until view exchanged
if (connectedToDB == false) { // View not yet retrieved
// create non_replicated session cookie
cookie_value = String.valueOf(sess_num) + "_" + local_IP + "_0_"
+ local_IP + "_0.0.0.0";
} else { // View retrieved
// Randomly choose backup server from group view
String backup_ip = null;
backup_ip = writeDataToBackupServer(first_session_data);
// Construct cookie
if (backup_ip != null) {
cookie_value = String.valueOf(sess_num) + "_" + local_IP + "_0_"
+ local_IP + "_" + backup_ip;
} else {
cookie_value = String.valueOf(sess_num) + "_" + local_IP + "_0_"
+ local_IP + "_0.0.0.0";
}
}
// store new session data into table
session_table.put(String.valueOf(sess_num) + "_" + local_IP, first_session_data);
test = "first time user, on " + local_IP + ", sess_num = " + String.valueOf(sess_num);
sess_num++; // increment session number for future session
Cookie new_cookie = new Cookie(cookie_name, cookie_value); // create cookie
new_cookie.setMaxAge(sess_timeout_secs); // set timeout to one hour
response.addCookie(new_cookie); // add cookie to session_table
// Display on page
cookie_str = session_table.get(cookie_value).getMessage();
cookie_timeout = String.valueOf(session_table.get(cookie_value).getTimestamp());
} else { // returned user
// action control
String act = request.getParameter("act");
String[] cookie_value_token = c.getValue().split("_");
String sessionID = cookie_value_token[0] + "_" + cookie_value_token[1];
int version_number = Integer.parseInt(cookie_value_token[2]);
String primary_server = cookie_value_token[3];
String backup_server = cookie_value_token[4];
SessionData sessionData = null;
// token format: < sess_num, SvrIP, version, SvrIPprimary, SvrIPbackup >
if ( (primary_server.equals(local_IP) || backup_server.equals(local_IP))
&& (version_number == session_table.get(sessionID).getVersion())) {
// local IP address is either primary server or backup server for this session
// and the version number is correct --> session data is in local table
sessionData = session_table.get(sessionID);
}
else { // session data does not exists in local session table
// Perform RPC sessionRead to primary and backup concurrently
sessionData = RPCSessionRead(sessionID, version_number, primary_server, backup_server);
}
if (sessionData == null) {
// TODO sessionData means RPC request failed
// return an HTML page with a message "session timeout or failed"
test = "Error: session timeout or failed!"; // Error occur!
// TODO Delete cookie for the bad session
c.setMaxAge(0); // Terminate the session
response.addCookie(c); // put cookie in response
} else { // sessionData exist
// Increment version number
sessionData.setVersion(sessionData.getVersion() + 1);
boolean isLogout = false;
if (act == null) {
test = "revisit";
c.setMaxAge(sess_timeout_secs); // reset cookie timeout to one hour
sessionData.setTimestamp(System.currentTimeMillis() + sess_timeout_secs);
cookie_str = sessionData.getMessage();
cookie_timeout = String.valueOf(sessionData.getTimestamp());
session_table.put(sessionID, sessionData); // replace old data with same key
}
else if (act.equals("Refresh")) { // Refresh button was pressed
test = "Refresh";
// Redisplay the session message, with an updated session expiration time;
sessionData.setTimestamp(System.currentTimeMillis() + sess_timeout_secs);
c.setMaxAge(sess_timeout_secs); // reset cookie timeout to one hour
session_table.put(sessionID, sessionData); // replace old data with same key
// Display message
cookie_str = sessionData.getMessage();
cookie_timeout = String.valueOf(sessionData.getTimestamp());
}
else if (act.equals("Replace")) { // Replace button was pressed
test = "Replace";
// Replace the message with a new one (that the user typed into an HTML form field)
// and display the (new) message and expiration time;
String message = request.getParameter("message");
final byte[] utf8Bytes = message.getBytes("UTF-8"); // get message byte length
Scanner sc = new Scanner(message);
if (utf8Bytes.length > 512) {
test = "String too long";
}
else if (!sc.hasNext("[A-Za-z0-9\\.-]+")) {
test = "Invalid string! only allow [A-Za-z.-]";
}
else { // error message
// is safe characters and length < 512 bytes
test = "valid replace";
sessionData.setTimestamp(System.currentTimeMillis() + sess_timeout_secs);
sessionData.setMessage(message);
sc.close();
}
c.setMaxAge(sess_timeout_secs); // reset cookie timeout to one hour
session_table.put(sessionID, sessionData); // replace old data with same key
// Display message
cookie_str = sessionData.getMessage();
cookie_timeout = String.valueOf(sessionData.getTimestamp());
}
else if (act.equals("Logout")) { // Logout button was pressed
isLogout = true;
test = "Logout";
session_table.remove(sessionID); // remove cookie information from table
c.setMaxAge(0); // Terminate the session
// Display message
cookie_str = "Goodbye";
cookie_timeout = "Expired";
}
if (!isLogout) {
// TODO RPC, store new session state into remote server
String backup_ip = null;
backup_ip = writeDataToBackupServer(sessionData);
// Construct cookie
if (backup_ip != null) { // Response success
c.setValue(String.valueOf(sess_num) + "_" + local_IP + "_" + sessionData.getVersion()
+ "_" + local_IP + "_" + backup_ip);
} else { // Response fail
c.setValue(String.valueOf(sess_num) + "_" + local_IP + "_" + sessionData.getVersion()
+ "_" + local_IP + "_0.0.0.0");
}
response.addCookie(c); // put cookie in response
}
}
}
// for page display
request.setAttribute("test", test);
request.setAttribute("cookie_str", cookie_str);
request.setAttribute("cookie_timeout", cookie_timeout);
request.getRequestDispatcher("/HelloWorld.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Auto-generated method stub
}
// helper functions
/**
* Get cookie by name from HTTP request
*
* @param request HTTP client request
* @param name cookie name that we want to retrieve
*
* @return cookie which has name = "name", or null if not found
**/
public static Cookie getCookie(HttpServletRequest request, String name) {
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}
// TODO Connect simpleDB to retrieve view
/**
* Connect to SimpleDB server to get membership view
* @throws IOException
**/
public boolean getViewFromSimpleDB() throws IOException {
AWSCredentials credentials=new BasicAWSCredentials("1JgVDeFfZO5dKcVlo4lY3Fbby1bAbq1lOZ759Eqc",
"AKIAJW6MMYVAEV3VWVIQ");
final AmazonSimpleDB sdb = new AmazonSimpleDBClient(credentials);
System.out.println("===========================================");
System.out.println("Getting Started with Amazon SimpleDB");
System.out.println("===========================================\n");
// Get view
System.out.println("Checking if the domain " + domain_name + " exists in your account:\n");
int isExistViews = 0; // domain
for (String domainName : sdb.listDomains().getDomainNames()) {
if (domain_name.equals(domainName)) {
isExistViews = 1;
break;
}
}
if (isExistViews == 0) {
System.out.println("domain " + domain_name + " does not exist in simpleDB.\n");
// Create domain
System.out.println("Creating domain called " + domain_name + ".\n");
sdb.createDomain(new CreateDomainRequest(domain_name));
// Add current server into DB view
List<ReplaceableItem> sampleData = new ArrayList<ReplaceableItem>();
sampleData.add(new ReplaceableItem().withName("view").withAttributes(
new ReplaceableAttribute().withName("viewString")
.withValue(local_IP + "_UP_" + String.valueOf(System.currentTimeMillis()))));
sdb.batchPutAttributes(new BatchPutAttributesRequest(domain_name, sampleData));
// Add current server into local view
group_view.put(local_IP, new ServerStatus("UP", System.currentTimeMillis()) );
} else {
System.out.println("Domain " + domain_name + " exists in simpleDB.\n");
System.out.println("Download view from simpleDB.\n");
// Select data from a domain
// Notice the use of backticks around the domain name in our select expression.
String selectExpression = "select * from `" + domain_name + "`";
System.out.println("Selecting: " + selectExpression + "\n");
SelectRequest selectRequest = new SelectRequest(selectExpression);
// download simpleDB data
String viewString = null;
for (Item item : sdb.select(selectRequest).getItems()) {
if (item.getName().equals("view")) {
for (Attribute attribute : item.getAttributes()) {
viewString = attribute.getValue();
}
}
}
// Add current server into local view
group_view.put(local_IP, new ServerStatus("UP", System.currentTimeMillis()) );
// Format viewString and put view into group_view
mergeViewStringToLocalView(viewString);
// View retrieval success
return true;
}
// fail to get view
return false;
}
/**
* Start scheduled thread for garbage collection.
*
* @param period run thread every "period" seconds
**/
public void startGarbageCollect(int period) {
System.out.println("Start Garbage Collector");
ScheduledExecutorService garbageCollector = Executors.newSingleThreadScheduledExecutor();
garbageCollector.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// Iterate through session table
Iterator<Map.Entry<String, SessionData>> it = session_table.entrySet().iterator();
long currentTime = System.currentTimeMillis();
while (it.hasNext()) {
Map.Entry<String, SessionData> sessData = it.next();
// collect data which has discard time < now
if (sessData.getValue().getTimestamp() < currentTime) {
it.remove();
System.out.println(sessData.getKey() + " = " + sessData.getValue());
}
it.remove(); // avoids a ConcurrentModificationException
}
}
}, 0, period, TimeUnit.SECONDS);
}
/**
* Start scheduled thread for view exchange
*
* @param period run thread every "period" seconds
**/
public void startViewExchange(int period) {
System.out.println("Start View Exchanger");
Thread viewExchangeThread = new Thread() {
public void run() {
try {
Random random = new Random();
while (true) {
List<String> good_server_list = new ArrayList<String>();
for (Map.Entry<String, ServerStatus> entry : group_view.entrySet()) {
if (!entry.getKey().equals(local_IP) && entry.getValue().getStatus().equals("UP")) {
good_server_list.add(entry.getKey());
}
}
good_server_list.add("simpleDB");
int rand = random.nextInt(good_server_list.size());
String randomBackupServerIP = good_server_list.get(rand);
good_server_list.remove(rand); // removed server IP that has been chosen
if (randomBackupServerIP.equals("simpleDB")) {
// Read ViewSDB from SimpleDB.
// Compute a new merged View, Viewm, from ViewSDB and the current View.
// Store Viewm back into SimpleDB.
// Replace the current View with Viewm.
final AmazonSimpleDB sdb = new AmazonSimpleDBClient(new PropertiesCredentials(
HelloWorld.class.getResourceAsStream("AwsCredentials.properties")));
System.out.println("===========================================");
System.out.println("Getting Started with Amazon SimpleDB");
System.out.println("===========================================\n");
// Get view
System.out.println("Domain " + domain_name + " exists in simpleDB.\n");
System.out.println("Download view from simpleDB.\n");
// Select data from a domain
// Notice the use of backticks around the domain name in our select expression.
String selectExpression = "select * from `" + domain_name + "`";
System.out.println("Selecting: " + selectExpression + "\n");
SelectRequest selectRequest = new SelectRequest(selectExpression);
// download simpleDB data and add to local view.
String viewString = null;
for (Item item : sdb.select(selectRequest).getItems()) {
if (item.getName().equals("view")) {
for (Attribute attribute : item.getAttributes()) {
viewString = attribute.getValue();
}
}
}
// Format viewString and put view into group_view
mergeViewStringToLocalView(viewString);
// Put updated view back to DB
ReplaceableAttribute replaceableAttribute = new ReplaceableAttribute()
.withName("viewString").withValue(getLocalViewString()).withReplace(true);
sdb.putAttributes(new PutAttributesRequest()
.withDomainName(domain_name)
.withItemName("view")
.withAttributes(replaceableAttribute));
} else { // normal valid IP address
mergeViewStringToLocalView(RPCViewExchange(randomBackupServerIP));
}
sleep( (view_exchange_period / 2) + random.nextInt(view_exchange_period));
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
viewExchangeThread.start();
}
/**
* Get server local IP from network interface(local test) or terminal command(AWS)
*
* @param isLocal true, if perform local test. false when deployed to AWS
*
* @return local IP address
**/
public String getLocalIP(boolean isLocal) {
if (isLocal == true) {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
InetAddress addr = addresses.nextElement(); // Get first element (mac address)
addr = addresses.nextElement(); // Get second element (ip address)
return addr.getHostAddress();
/*
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ip = addr.getHostAddress();
System.out.println(iface.getDisplayName() + " " + ip);
}
*/
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
// Method #2: Runtime.exec()
else {
try {
String[] cmd = new String[3];
cmd[0] = "/opt/aws/bin/ec2-metadata";
cmd[1] = "--public-ipv4";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null) {
// example output = public-ipv4: ww.xx.yy.zz
return line.substring(13);
}
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
}
catch (Throwable t) {
t.printStackTrace();
}
}
return null;
}
/**
* Start UDP server for RPC
*
* @param port start server on port
* @throws IOException
* @throws SocketException
**/
public void startUDPServer(final int port) throws IOException {
System.out.println("=======================================");
System.out.println(" UDP server started at port " + UDP_port);
System.out.println("=======================================");
Thread UDPthread = new Thread() {
public void run() {
try {
@SuppressWarnings("resource")
DatagramSocket rpcSocket = new DatagramSocket(port);
while(true) {
byte[] inBuf = new byte[1024];
byte[] outBuf = null;
DatagramPacket recvPkt = new DatagramPacket(inBuf, inBuf.length);
rpcSocket.receive(recvPkt);
InetAddress IPAddress = recvPkt.getAddress();
int returnPort = recvPkt.getPort();
String recv_string = new String(recvPkt.getData());
String[] recv_string_token = recv_string.split("_");
int operationCode = Integer.parseInt(recv_string_token[1]);
switch (operationCode) {
case 0: // sessionRead
outBuf = serverSessionRead(recvPkt.getData(), recvPkt.getLength());
break;
case 1: // sessionWrite
outBuf = serverSessionWrite(recvPkt.getData(), recvPkt.getLength());
break;
case 2: // exchangeView
outBuf = serverExchangeView(recvPkt.getData(), recvPkt.getLength());
break;
default: // error occur
System.out.println("receive unknown operation!!!!");
break;
}
DatagramPacket sendPacket = new DatagramPacket(outBuf, outBuf.length, IPAddress, returnPort);
rpcSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
UDPthread.start();
}
/**TODO
* Server RPC to send out session data requested for function RPCSessionRead
*
* @param pktData
* @param pktLen
*
* @return recvStr receive data string
**/
public byte[] serverSessionRead(byte[] pktData, int pktLen) {
// Received data format = callID + operation + sessionID(num+ip)
// output data format = callID + sessionData(ver#_message_timestamp)
String recv_string = new String(pktData);
String[] recv_string_token = recv_string.split("_");
String return_string = recv_string_token[0] + "_"
+ session_table.get(recv_string_token[2] + "_" + recv_string_token[3]).toString();
return return_string.getBytes();
}
/**TODO
* Server RPC to write received session data into server session table
*
* @param pktData
* @param pktLen
*
* @return recvStr receive data string
**/
public byte[] serverSessionWrite(byte[] pktData, int pktLen) {
// Received data format = callID + operation code + sessionID(2) + session data(3)
// output data format = callID
String recv_string = new String(pktData);
String[] recv_string_token = recv_string.split("_");
String sessionID = recv_string_token[2] + "_" + recv_string_token[3];
session_table.put(sessionID, new SessionData(Integer.valueOf(recv_string_token[4]),
recv_string_token[5], Integer.valueOf(recv_string_token[6])));
return recv_string_token[0].getBytes();
}
/**TODO
* Server RPC to return view for function RPCViewExchange
*
* @param pktData
* @param pktLen
*
* @return recvStr receive data string
**/
public byte[] serverExchangeView(byte[] pktData, int pktLen) {
// Received data format = callID + 3 + viewString
// output data format = callID + viewString
String recv_string = new String(pktData);
String[] recv_string_token = recv_string.split("_");
mergeViewStringToLocalView(recv_string_token[2]);
return (recv_string_token[0] + getLocalViewString()).getBytes();
}
/**TODO
* RPC to read session data which is not in local session table
*
* @param sessionID
* @param version_number session data version number
* @param primary_IP session data primary storage
* @param backup_IP session data backup storage
*
* @return recvStr receive data string
* @throws IOException
**/
public SessionData RPCSessionRead(String sessionID, int version_num, String primary_IP, String backup_IP) throws IOException {
DatagramSocket rpcSocket = new DatagramSocket();
byte[] outBuf = new byte[1024];
byte[] inBuf = new byte[1024];
int received_version_num = -1;
int received_call_ID = -1;
int local_call_ID = RPC_call_ID;
SessionData return_data = null;
// Increment call ID for next RPC
RPC_call_ID++;
// message = callID + operation code + sessionID
String message = String.valueOf(local_call_ID) + "_0_" + sessionID;
outBuf = message.getBytes();
// Send to primary server
DatagramPacket sendPkt = new DatagramPacket(outBuf, outBuf.length, InetAddress.getByName(primary_IP), UDP_port);
rpcSocket.send(sendPkt);
// Send to backup server
sendPkt = new DatagramPacket(outBuf, outBuf.length, InetAddress.getByName(backup_IP), UDP_port);
rpcSocket.send(sendPkt);
DatagramPacket recvPkt = new DatagramPacket(inBuf, inBuf.length);
try {
do {
recvPkt.setLength(inBuf.length);
rpcSocket.receive(recvPkt);
String received_string = new String(recvPkt.getData());
String[] received_string_token = received_string.split("_");
// Received data format = callID + sessionData(ver#_message_timestamp)
received_call_ID = Integer.parseInt( received_string_token[0] );
received_version_num = Integer.parseInt( received_string_token[1] );
return_data = new SessionData(received_version_num,
received_string_token[2],
Integer.parseInt( received_string_token[3]) );
} while (received_call_ID != local_call_ID && version_num != received_version_num);
} catch (SocketTimeoutException stoe) {
// RPC timeout, return null string
System.out.println("RPC session read timeout");
recvPkt = null;
} catch(IOException ioe) {
// other error
}
rpcSocket.close();
return return_data;
}
/**TODO
* RPC to read session data which is not in local session table
*
* @param sessionID
*
* @return recvStr receive data string
* @throws IOException
**/
public boolean RPCSessionWrite(String sessionID, String ip, SessionData data) throws IOException {
DatagramSocket rpcSocket = new DatagramSocket();
byte[] outBuf = new byte[1024];
byte[] inBuf = new byte[1024];
String return_string = null;
int received_call_ID = -1;
int local_call_ID = RPC_call_ID;
RPC_call_ID++;
// message = callID + operation code + sessionID + session data
String message = String.valueOf(local_call_ID) + "_1_" + sessionID + "_" + data.toString();
outBuf = message.getBytes();
DatagramPacket sendPkt = new DatagramPacket(outBuf, outBuf.length, InetAddress.getByName(ip), UDP_port);
rpcSocket.send(sendPkt);
DatagramPacket recvPkt = new DatagramPacket(inBuf, inBuf.length);
try {
do {
recvPkt.setLength(inBuf.length);
rpcSocket.receive(recvPkt);
return_string = new String(recvPkt.getData());
received_call_ID = Integer.parseInt( (return_string.split("_"))[0] );
} while (received_call_ID != local_call_ID);
} catch (SocketTimeoutException stoe) {
// timeout
recvPkt = null;
return false;
} catch(IOException ioe) {
// other error
}
rpcSocket.close();
return true;
}
/**
* RPC to exchange view with target server or simpleDB
*
* @param sessionID
*
* @return recvStr receive data string
* @throws IOException
**/
public String RPCViewExchange(String ip) throws IOException {
DatagramSocket rpcSocket = new DatagramSocket();
byte[] outBuf = new byte[1024];
byte[] inBuf = new byte[1024];
String return_string = null;
int received_call_ID = -1;
int local_call_ID = RPC_call_ID;
RPC_call_ID++;
// message = callID + operation code + local viewString
String message = String.valueOf(local_call_ID) + "_2_" + getLocalViewString();
outBuf = message.getBytes();
DatagramPacket sendPkt = new DatagramPacket(outBuf, outBuf.length, InetAddress.getByName(ip), UDP_port);
rpcSocket.send(sendPkt);
DatagramPacket recvPkt = new DatagramPacket(inBuf, inBuf.length);
try {
do {
// received = callID + viewString
recvPkt.setLength(inBuf.length);
rpcSocket.receive(recvPkt);
return_string = new String(recvPkt.getData());
received_call_ID = Integer.parseInt( (return_string.split("_"))[0] );
} while (received_call_ID != local_call_ID);
} catch (SocketTimeoutException stoe) {
// timeout
recvPkt = null;
return null;
} catch(IOException ioe) {
// other error
}
rpcSocket.close();
return (return_string.split("_"))[1];
}
/**
* RPC to exchange view with target server or simpleDB
*
* @param data session data to write to remote server
*
* @return backup_ip null, if no server can be written to
* @throws IOException
**/
public String writeDataToBackupServer(SessionData data) throws IOException {
// Choose available backup server from group view
List<String> good_server_list = new ArrayList<String>();
for (Map.Entry<String, ServerStatus> entry : group_view.entrySet()) {
if (!entry.getKey().equals(local_IP) && entry.getValue().getStatus().equals("UP")) {
good_server_list.add(entry.getKey());
}
}
boolean backup_written = false; // True, if data is wrote to other server by RPC
String backup_ip = null;
while (backup_written) { // Keep trying if data is not written
if (good_server_list.isEmpty()) break; // No available server
Random random = new Random();
int rand = random.nextInt(good_server_list.size());
String randomBackupServerIP = good_server_list.get(rand);
good_server_list.remove(rand); // removed server IP that has been chosen
// Write to backup server
String session_ID = String.valueOf(sess_num) + "_" + local_IP;
if ( RPCSessionWrite(session_ID, randomBackupServerIP, data) ) {
backup_written = true;
backup_ip = randomBackupServerIP;
// Update good server status
group_view.put(backup_ip, new ServerStatus("UP", System.currentTimeMillis()));
break;
};
// Update failed server status
group_view.put(randomBackupServerIP, new ServerStatus("DOWN", System.currentTimeMillis()));
}
return backup_ip;
}
public void mergeViewStringToLocalView(String viewString) {
String[] tokens = viewString.split("_");
int num_views = tokens.length / 3;
for (int i = 0; i < num_views; i++) {
String ip = tokens[i*3];
String status = tokens[i*3+1];
int timeStamp = Integer.valueOf(tokens[i*3+2]);
if (!group_view.containsKey(ip) || group_view.get(ip).getTimeStamp() < timeStamp) {
// Add non-exist or out of date view
group_view.put(ip, new ServerStatus(status, timeStamp));
}
}
}
public String getLocalViewString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, ServerStatus> entry : group_view.entrySet()) {
sb.append(entry.getKey() + "_");
sb.append(entry.getValue().getStatus() + "_");
sb.append(entry.getValue().getTimeStamp() + "_");
}
return sb.toString().substring(0, sb.length()-1);
}
}
| mit |
zhangjikai/algorithm | leetcode/src/main/java/com/zhangjikai/leetcode/AddTwoNumbers2.java | 888 | package com.zhangjikai.leetcode;
/**
* Created by ZhangJikai on 2016/10/18.
*/
public class AddTwoNumbers2 {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode curr = head;
ListNode p = l1, q = l2;
int carry = 0, a, b, c;
while (p != null || q != null) {
a = p != null ? p.val : 0;
b = q != null ? q.val : 0;
c = a + b + carry;
carry = c / 10;
curr.next = new ListNode(c % 10);
curr = curr.next;
if(p != null ) p = p.next;
if(q != null) q = q.next;
}
if(carry == 1) {
curr.next = new ListNode(1);
}
return head.next;
}
}
| mit |
spupyrev/swcv | cloudy/src/knapsack/core/ValueDensity.java | 1344 | package knapsack.core;
/**
* Utility class - it helps with initial sorting in a manner of better cost/weight
* density, it also holds related cost and weight.
*
* @author vasek
*
*/
public class ValueDensity implements Comparable<ValueDensity> {
private int cost;
private int weight;
private int originalIndex;
/**
* Constructor.
*
* @param cost cost related to weight
* @param weight weight related to cost
* @param index index in original data
*/
public ValueDensity(final int cost, final int weight, final int index) {
this.cost = cost;
this.weight = weight;
this.originalIndex = index;
}
/**
* @return cost
*/
public int getCost() {
return cost;
}
/**
* @return weight
*/
public int getWeight() {
return weight;
}
/**
* @return index in original data
*/
public int getOriginalIndex() {
return originalIndex;
}
@Override
public int compareTo(ValueDensity other) {
final double ratio1 = this.getCost() / this.getWeight();
final double ratio2 = other.getCost() / other.getWeight();
if (ratio1 <= ratio2) {
return 1;
} else {
return -1;
}
}
@Override
public String toString() {
return String.valueOf(cost / weight);
}
} | mit |
sibojia/ihomepage | infohub-yt/src/com/renren/api/service/AlbumType.java | 654 | /**
* Autogenerated by renren-api2-generator 2013-07-05 11:01:59
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.renren.api.service;
/**
* ็ธๅ็็ฑปๅใ
*/
public enum AlbumType {
/*
* ๅคดๅ็ธๅ
*/
PORTRAIT,
/*
* APP็ธๅ
*/
APP,
/*
* ๆฎ้็ธๅ
*/
GENERAL,
/*
* ๅฟซ้ไธไผ ็ธๅ
*/
PUBLISHER_SINGLE,
/*
* ๅ
ถไป็ธๅ
*/
OTHER,
/*
* ๆฅๅฟ็ธๅ
*/
BLOG,
/*
* ๅบ็จ็ธๅ
*/
ALL_APP,
/*
* ่ฏญ้ณ็ธๅ
*/
VOICE,
/*
* ๅคงๅคด่ดด็ธๅ
*/
HEADPHOTO,
/*
* ๆดปๅจ็ธๅ
*/
ACTIVE,
/*
* ๆๆบ็ธๅ
*/
MMS;
}
| mit |
TGX-ZQ/Z-Queen | src/main/java/com/tgx/zq/z/queen/io/inf/IRouteLv4.java | 1661 | /*
* MIT License
*
* Copyright (c) 2016~2017 Z-Chess
*
* 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.tgx.zq.z.queen.io.inf;
/**
* @author William.d.zk
*/
public interface IRouteLv4
extends
IRouteLv4Cluster,
IRouteLv4PortChannel
{
default long getPortIdx() {
return -1;
}
default IRouteLv4 setPortIdx(long filter) {
return this;
}
default boolean isCluster() {
return false;
}
default IRouteLv4 setCluster(boolean b) {
return this;
}
default IRouteLv4 duplicate() {
return this;
}
}
| mit |
shanraisshan/EmojiCodeSheet | android/string/People.java | 45868 | /**
* Shayan Rais (http://shanraisshan.com)
* created on 7/26/2016
*/
public class People {
//Row#: 1
public static final String GRINNING_FACE = "๐"; //https://www.emojibase.com/emoji/1f600/grinningface
public static final String GRIMACING_FACE = "๐ฌ"; //https://www.emojibase.com/emoji/1f62c/grimacingface
public static final String GRIMACING_FACE_WITH_SMILE_EYES = "๐"; //https://www.emojibase.com/emoji/1f601/grinningfacewithsmilingeyes
public static final String FACE_WITH_TEAR_OF_JOY = "๐"; //https://www.emojibase.com/emoji/1f602/facewithtearsofjoy
public static final String SMILING_FACE_WITH_OPEN_MOUTH = "๐"; //https://www.emojibase.com/emoji/1f603/smilingfacewithopenmouth
public static final String SMILING_FACE_WITH_OPEN_MOUTH_EYES = "๐"; //https://www.emojibase.com/emoji/1f604/smilingfacewithopenmouthandsmilingeyes
public static final String SMILING_FACE_WITH_OPEN_MOUTH_COLD_SWEAT = "๐
"; //https://www.emojibase.com/emoji/1f605/smilingfacewithopenmouthandcoldsweat
public static final String SMILING_FACE_WITH_OPEN_MOUTH_HAND_TIGHT = "๐"; //https://www.emojibase.com/emoji/1f606/smilingfacewithopenmouthandtightlyclosedeyes
//Row#: 2
public static final String SMILING_FACE_WITH_HALO = "๐"; //https://www.emojibase.com/emoji/1f607/smilingfacewithhalo
public static final String WINKING_FACE = "๐"; //https://www.emojibase.com/emoji/1f609/winkingface
public static final String BLACK_SMILING_FACE = "๐"; //http://emojipedia.org/smiling-face-with-smiling-eyes/
public static final String SLIGHTLY_SMILING_FACE = "๐"; //https://www.emojibase.com/emoji/1f642/slightlysmilingface
public static final String UPSIDE_DOWN_FACE = "๐"; //http://emojipedia.org/upside-down-face/
public static final String WHITE_SMILING_FACE = "โบ"; //https://www.emojibase.com/emoji/263a/whitesmilingface
public static final String FACE_SAVOURING_DELICIOUS_FOOD = "๐"; //https://www.emojibase.com/emoji/1f60b/facesavouringdeliciousfood
public static final String RELIEVED_FACE = "๐"; //https://www.emojibase.com/emoji/1f60c/relievedface
//Row#: 3
public static final String SMILING_FACE_HEART_EYES = "๐"; //https://www.emojibase.com/emoji/1f60d/smilingfacewithheartshapedeyes
public static final String FACE_THROWING_KISS = "๐"; //https://www.emojibase.com/emoji/1f618/facethrowingakiss
public static final String KISSING_FACE = "๐"; //https://www.emojibase.com/emoji/1f617/kissingface
public static final String KISSING_FACE_WITH_SMILE_EYES = "๐"; //https://www.emojibase.com/emoji/1f619/kissingfacewithsmilingeyes
public static final String KISSING_FACE_WITH_CLOSED_EYES = "๐"; //https://www.emojibase.com/emoji/1f61a/kissingfacewithclosedeyes
public static final String FACE_WITH_TONGUE_WINK_EYE = "๐"; //https://www.emojibase.com/emoji/1f61c/facewithstuckouttongueandwinkingeye
public static final String FACE_WITH_TONGUE_CLOSED_EYE = "๐"; //https://www.emojibase.com/emoji/1f61d/facewithstuckouttongueandtightlyclosedeyes
public static final String FACE_WITH_STUCK_OUT_TONGUE = "๐"; //https://www.emojibase.com/emoji/1f61b/facewithstuckouttongue
//Row#: 4
public static final String MONEY_MOUTH_FACE = "๐ค"; //http://emojipedia.org/money-mouth-face/
public static final String NERD_FACE = "๐ค"; //http://emojipedia.org/nerd-face/
public static final String SMILING_FACE_WITH_SUN_GLASS = "๐"; //https://www.emojibase.com/emoji/1f60e/smilingfacewithsunglasses
public static final String HUGGING_FACE = "๐ค"; //http://emojipedia.org/hugging-face/
public static final String SMIRKING_FACE = "๐"; //https://www.emojibase.com/emoji/1f60f/smirkingface
public static final String FACE_WITHOUT_MOUTH = "๐ถ"; //https://www.emojibase.com/emoji/1f636/facewithoutmouth
public static final String NEUTRAL_FACE = "๐"; //https://www.emojibase.com/emoji/1f610/neutralface
public static final String EXPRESSIONLESS_FACE = "๐"; //https://www.emojibase.com/emoji/1f611/expressionlessface
//Row#: 5
public static final String UNAMUSED_FACE = "๐"; //https://www.emojibase.com/emoji/1f612/unamusedface
public static final String FACE_WITH_ROLLING_EYES = "๐"; //http://emojipedia.org/face-with-rolling-eyes/
public static final String THINKING_FACE = "๐ค"; //http://emojipedia.org/thinking-face/
public static final String FLUSHED_FACE = "๐ณ"; //https://www.emojibase.com/emoji/1f633/flushedface
public static final String DISAPPOINTED_FACE = "๐"; //https://www.emojibase.com/emoji/1f61e/disappointedface
public static final String WORRIED_FACE = "๐"; //https://www.emojibase.com/emoji/1f61f/worriedface
public static final String ANGRY_FACE = "๐ "; //https://www.emojibase.com/emoji/1f620/angryface
public static final String POUTING_FACE = "๐ก"; //https://www.emojibase.com/emoji/1f621/poutingface
//Row#: 6
public static final String PENSIVE_FACE = "๐"; //https://www.emojibase.com/emoji/1f614/pensiveface
public static final String CONFUSED_FACE = "๐"; //https://www.emojibase.com/emoji/1f615/confusedface
public static final String SLIGHTLY_FROWNING_FACE = "๐"; //https://www.emojibase.com/emoji/1f641/slightlyfrowningface
public static final String WHITE_FROWNING_FACE = "โน"; //https://www.emojibase.com/emoji/2639/whitefrowningface
public static final String PERSEVERING_FACE = "๐ฃ"; //https://www.emojibase.com/emoji/1f623/perseveringface
public static final String CONFOUNDED_FACE = "๐"; //https://www.emojibase.com/emoji/1f616/confoundedface
public static final String TIRED_FACE = "๐ซ"; //https://www.emojibase.com/emoji/1f62b/tiredface
public static final String WEARY_FACE = "๐ฉ"; //https://www.emojibase.com/emoji/1f629/wearyface
//Row#: 7
public static final String FACE_WITH_LOOK_OF_TRIUMPH = "๐ค"; //https://www.emojibase.com/emoji/1f624/facewithlookoftriumph
public static final String FACE_WITH_OPEN_MOUTH = "๐ฎ"; //https://www.emojibase.com/emoji/1f62e/facewithopenmouth
public static final String FACE_SCREAMING_IN_FEAR = "๐ฑ"; //https://www.emojibase.com/emoji/1f631/facescreaminginfear
public static final String FEARFUL_FACE = "๐จ"; //https://www.emojibase.com/emoji/1f628/fearfulface
public static final String FACE_WITH_OPEN_MOUTH_COLD_SWEAT = "๐ฐ"; //https://www.emojibase.com/emoji/1f630/facewithopenmouthandcoldsweat
public static final String HUSHED_FACE = "๐ฏ"; //https://www.emojibase.com/emoji/1f62f/hushedface
public static final String FROWNING_FACE_WITH_OPEN_MOUTH = "๐ฆ"; //https://www.emojibase.com/emoji/1f626/frowningfacewithopenmouth
public static final String ANGUISHED_FACE = "๐ง"; //https://www.emojibase.com/emoji/1f627/anguishedface
//Row#: 8
public static final String CRYING_FACE = "๐ข"; //https://www.emojibase.com/emoji/1f622/cryingface
public static final String DISAPPOINTED_BUT_RELIEVED_FACE = "๐ฅ"; //https://www.emojibase.com/emoji/1f625/disappointedbutrelievedface
public static final String SLEEPY_FACE = "๐ช"; //https://www.emojibase.com/emoji/1f62a/sleepyface
public static final String FACE_WITH_COLD_SWEAT = "๐"; //https://www.emojibase.com/emoji/1f613/facewithcoldsweat
public static final String LOUDLY_CRYING_FACE = "๐ญ"; //https://www.emojibase.com/emoji/1f62d/loudlycryingface
public static final String DIZZY_FACE = "๐ต"; //https://www.emojibase.com/emoji/1f635/dizzyface
public static final String ASTONISHED_FACE = "๐ฒ"; //https://www.emojibase.com/emoji/1f632/astonishedface
public static final String ZIPPER_MOUTH_FACE = "๐ค"; //http://emojipedia.org/zipper-mouth-face/
//Row#: 9
public static final String FACE_WITH_MEDICAL_MASK = "๐ท"; //https://www.emojibase.com/emoji/1f637/facewithmedicalmask
public static final String FACE_WITH_THERMOMETER = "๐ค"; //http://emojipedia.org/face-with-thermometer/
public static final String FACE_WITH_HEAD_BANDAGE = "๐ค"; //http://emojipedia.org/face-with-head-bandage/
public static final String SLEEPING_FACE = "๐ด"; //https://www.emojibase.com/emoji/1f634/sleepingface
public static final String SLEEPING_SYMBOL = "๐ค"; //https://www.emojibase.com/emoji/1f4a4/sleepingsymbol
public static final String PILE_OF_POO = "๐ฉ"; //https://www.emojibase.com/emoji/1f4a9/pileofpoo
public static final String SMILING_FACE_WITH_HORNS = "๐"; //https://www.emojibase.com/emoji/1f608/smilingfacewithhorns
public static final String IMP = "๐ฟ"; //https://www.emojibase.com/emoji/1f47f/imp
//Row#: 10
public static final String JAPANESE_OGRE = "๐น"; //https://www.emojibase.com/emoji/1f479/japaneseogre
public static final String JAPANESE_GOBLIN = "๐บ"; //https://www.emojibase.com/emoji/1f47a/japanesegoblin
public static final String SKULL = "๐"; //https://www.emojibase.com/emoji/1f480/skull
public static final String GHOST = "๐ป"; //https://www.emojibase.com/emoji/1f47b/ghost
public static final String EXTRA_TERRESTRIAL_ALIEN = "๐ฝ"; //https://www.emojibase.com/emoji/1f47d/extraterrestrialalien
public static final String ROBOT_FACE = "๐ค"; //http://emojipedia.org/robot-face/
public static final String SMILING_CAT_FACE_OPEN_MOUTH = "๐บ"; //https://www.emojibase.com/emoji/1f63a/smilingcatfacewithopenmouth
public static final String GRINNING_CAT_FACE_SMILE_EYES = "๐ธ"; //https://www.emojibase.com/emoji/1f638/grinningcatfacewithsmilingeyes
//Row#: 11
public static final String CAT_FACE_TEARS_OF_JOY = "๐น"; //https://www.emojibase.com/emoji/1f639/catfacewithtearsofjoy
public static final String SMILING_CAT_FACE_HEART_SHAPED_EYES = "๐ป"; //https://www.emojibase.com/emoji/1f63b/smilingcatfacewithheartshapedeyes
public static final String CAT_FACE_WRY_SMILE = "๐ผ"; //https://www.emojibase.com/emoji/1f63c/catfacewithwrysmile
public static final String KISSING_CAT_FACE_CLOSED_EYES = "๐ฝ"; //https://www.emojibase.com/emoji/1f63d/kissingcatfacewithclosedeyes
public static final String WEARY_CAT_FACE = "๐"; //https://www.emojibase.com/emoji/1f640/wearycatface
public static final String CRYING_CAT_FACE = "๐ฟ"; //https://www.emojibase.com/emoji/1f63f/cryingcatface
public static final String POUTING_CAT_FACE = "๐พ"; //https://www.emojibase.com/emoji/1f63e/poutingcatface
public static final String PERSON_BOTH_HAND_CELEBRATION = "๐"; //https://www.emojibase.com/emoji/1f64c/personraisingbothhandsincelebration //http://emojipedia.org/person-raising-both-hands-in-celebration/
public static final String PERSON_BOTH_HAND_CELEBRATION_TYPE_1_2 = "๐๐ป";
public static final String PERSON_BOTH_HAND_CELEBRATION_TYPE_3 = "๐๐ผ";
public static final String PERSON_BOTH_HAND_CELEBRATION_TYPE_4 = "๐๐ฝ";
public static final String PERSON_BOTH_HAND_CELEBRATION_TYPE_5 = "๐๐พ";
public static final String PERSON_BOTH_HAND_CELEBRATION_TYPE_6 = "๐๐ฟ";
//Row#: 12
public static final String CLAPPING_HAND = "๐"; //https://www.emojibase.com/emoji/1f44f/clappinghandssign //http://emojipedia.org/clapping-hands-sign/
public static final String CLAPPING_HAND_TYPE_1_2 = "๐๐ผ";
public static final String CLAPPING_HAND_TYPE_3 = "๐๐ผ";
public static final String CLAPPING_HAND_TYPE_4 = "๐๐ฝ";
public static final String CLAPPING_HAND_TYPE_5 = "๐๐พ";
public static final String CLAPPING_HAND_TYPE_6 = "๐๐ฟ";
public static final String WAVING_HANDS = "๐"; //https://www.emojibase.com/emoji/1f44b/wavinghandsign //http://emojipedia.org/waving-hand-sign/
public static final String WAVING_HANDS_TYPE_1_2 = "๐๐ป";
public static final String WAVING_HANDS_TYPE_3 = "๐๐ผ";
public static final String WAVING_HANDS_TYPE_4 = "๐๐ฝ";
public static final String WAVING_HANDS_TYPE_5 = "๐๐พ";
public static final String WAVING_HANDS_TYPE_6 = "๐๐ฟ";
public static final String THUMBS_UP = "๐"; //https://www.emojibase.com/emoji/1f44d/thumbsupsign //http://emojipedia.org/thumbs-up-sign/
public static final String THUMBS_UP_TYPE_1_2 = "๐๐ป";
public static final String THUMBS_UP_TYPE_3 = "๐๐ผ";
public static final String THUMBS_UP_TYPE_4 = "๐๐ฝ";
public static final String THUMBS_UP_TYPE_5 = "๐๐พ";
public static final String THUMBS_UP_TYPE_6 = "๐๐ฟ";
public static final String THUMBS_DOWN = "๐"; //https://www.emojibase.com/emoji/1f44e/thumbsdownsign //http://emojipedia.org/thumbs-down-sign/
public static final String THUMBS_DOWN_TYPE_1_2 = "๐๐ป";
public static final String THUMBS_DOWN_TYPE_3 = "๐๐ผ";
public static final String THUMBS_DOWN_TYPE_4 = "๐๐ฝ";
public static final String THUMBS_DOWN_TYPE_5 = "๐๐พ";
public static final String THUMBS_DOWN_TYPE_6 = "๐๐ฟ";
public static final String FIST_HAND = "๐"; //https://www.emojibase.com/emoji/1f44a/fistedhandsign //http://emojipedia.org/fisted-hand-sign/
public static final String FIST_HAND_TYPE_1_2 = "๐๐ป";
public static final String FIST_HAND_TYPE_3 = "๐๐ผ";
public static final String FIST_HAND_TYPE_4 = "๐๐ฝ";
public static final String FIST_HAND_TYPE_5 = "๐๐พ";
public static final String FIST_HAND_TYPE_6 = "๐๐ฟ";
public static final String RAISED_FIST = "โ"; //https://www.emojibase.com/emoji/270a/raisedfist //http://emojipedia.org/raised-fist/
public static final String RAISED_FIST_TYPE_1_2 = "โ๐ป";
public static final String RAISED_FIST_TYPE_3 = "โ๐ผ";
public static final String RAISED_FIST_TYPE_4 = "โ๐ฝ";
public static final String RAISED_FIST_TYPE_5 = "โ๐พ";
public static final String RAISED_FIST_TYPE_6 = "โ๐ฟ";
public static final String VICTORY_HAND = "โ"; //https://www.emojibase.com/emoji/270c/victoryhand //http://emojipedia.org/victory-hand/
public static final String VICTORY_HAND_TYPE_1_2 = "โ๐ป";
public static final String VICTORY_HAND_TYPE_3 = "โ๐ผ";
public static final String VICTORY_HAND_TYPE_4 = "โ๐ฝ";
public static final String VICTORY_HAND_TYPE_5 = "โ๐พ";
public static final String VICTORY_HAND_TYPE_6 = "โ๐ฟ";
public static final String OK_HAND = "๐"; //https://www.emojibase.com/emoji/1f44c/okhandsign //http://emojipedia.org/ok-hand-sign/
public static final String OK_HAND_TYPE_1_2 = "๐๐ป";
public static final String OK_HAND_TYPE_3 = "๐๐ผ";
public static final String OK_HAND_TYPE_4 = "๐๐ฝ";
public static final String OK_HAND_TYPE_5 = "๐๐พ";
public static final String OK_HAND_TYPE_6 = "๐๐ฟ";
//Row#: 13
public static final String RAISED_HAND = "โ"; //https://www.emojibase.com/emoji/270b/raisedhand //http://emojipedia.org/raised-hand/
public static final String RAISED_HAND_TYPE_1_2 = "โ๐ป";
public static final String RAISED_HAND_TYPE_3 = "โ๐ผ";
public static final String RAISED_HAND_TYPE_4 = "โ๐ฝ";
public static final String RAISED_HAND_TYPE_5 = "โ๐พ";
public static final String RAISED_HAND_TYPE_6 = "โ๐ฟ";
public static final String OPEN_HAND = "๐"; //https://www.emojibase.com/emoji/1f450/openhandssign //http://emojipedia.org/open-hands-sign/
public static final String OPEN_HAND_TYPE_1_2 = "๐๐ป";
public static final String OPEN_HAND_TYPE_3 = "๐๐ผ";
public static final String OPEN_HAND_TYPE_4 = "๐๐ฝ";
public static final String OPEN_HAND_TYPE_5 = "๐๐พ";
public static final String OPEN_HAND_TYPE_6 = "๐๐ฟ";
public static final String FLEXED_BICEPS = "๐ช"; //https://www.emojibase.com/emoji/1f4aa/flexedbiceps //http://emojipedia.org/flexed-biceps/
public static final String FLEXED_BICEPS_TYPE_1_2 = "๐ช๐ป";
public static final String FLEXED_BICEPS_TYPE_3 = "๐ช๐ผ";
public static final String FLEXED_BICEPS_TYPE_4 = "๐ช๐ฝ";
public static final String FLEXED_BICEPS_TYPE_5 = "๐ช๐พ";
public static final String FLEXED_BICEPS_TYPE_6 = "๐ช๐ฟ";
public static final String FOLDED_HANDS = "๐"; //https://www.emojibase.com/emoji/1f64f/personwithfoldedhands //http://emojipedia.org/person-with-folded-hands/
public static final String FOLDED_HANDS_TYPE_1_2 = "๐๐ป";
public static final String FOLDED_HANDS_TYPE_3 = "๐๐ผ";
public static final String FOLDED_HANDS_TYPE_4 = "๐๐ฝ";
public static final String FOLDED_HANDS_TYPE_5 = "๐๐พ";
public static final String FOLDED_HANDS_TYPE_6 = "๐๐ฟ";
public static final String UP_POINTING_INDEX = "โ"; //https://www.emojibase.com/emoji/261d/whiteuppointingindex //http://emojipedia.org/white-up-pointing-index/
public static final String UP_POINTING_INDEX_TYPE_1_2 = "โ๐ป";
public static final String UP_POINTING_INDEX_TYPE_3 = "โ๐ผ";
public static final String UP_POINTING_INDEX_TYPE_4 = "โ๐ฝ";
public static final String UP_POINTING_INDEX_TYPE_5 = "โ๐พ";
public static final String UP_POINTING_INDEX_TYPE_6 = "โ๐ฟ";
public static final String UP_POINTING_BACKHAND_INDEX = "๐"; //https://www.emojibase.com/emoji/1f446/whiteuppointingbackhandindex //http://emojipedia.org/white-up-pointing-backhand-index/
public static final String UP_POINTING_BACKHAND_INDEX_TYPE_1_2 = "๐๐ป";
public static final String UP_POINTING_BACKHAND_INDEX_TYPE_3 = "๐๐ผ";
public static final String UP_POINTING_BACKHAND_INDEX_TYPE_4 = "๐๐ฝ";
public static final String UP_POINTING_BACKHAND_INDEX_TYPE_5 = "๐๐พ";
public static final String UP_POINTING_BACKHAND_INDEX_TYPE_6 = "๐๐ฟ";
public static final String DOWN_POINTING_BACKHAND_INDEX = "๐"; //https://www.emojibase.com/emoji/1f447/whitedownpointingbackhandindex //http://emojipedia.org/white-down-pointing-backhand-index/
public static final String DOWN_POINTING_BACKHAND_INDEX_TYPE_1_2 = "๐๐ป";
public static final String DOWN_POINTING_BACKHAND_INDEX_TYPE_3 = "๐๐ผ";
public static final String DOWN_POINTING_BACKHAND_INDEX_TYPE_4 = "๐๐ฝ";
public static final String DOWN_POINTING_BACKHAND_INDEX_TYPE_5 = "๐๐พ";
public static final String DOWN_POINTING_BACKHAND_INDEX_TYPE_6 = "๐๐ฟ";
public static final String LEFT_POINTING_BACKHAND_INDEX = "๐"; //https://www.emojibase.com/emoji/1f448/whiteleftpointingbackhandindex //http://emojipedia.org/white-left-pointing-backhand-index/
public static final String LEFT_POINTING_BACKHAND_INDEX_TYPE_1_2 = "๐๐ป";
public static final String LEFT_POINTING_BACKHAND_INDEX_TYPE_3 = "๐๐ผ";
public static final String LEFT_POINTING_BACKHAND_INDEX_TYPE_4 = "๐๐ฝ";
public static final String LEFT_POINTING_BACKHAND_INDEX_TYPE_5 = "๐๐พ";
public static final String LEFT_POINTING_BACKHAND_INDEX_TYPE_6 = "๐๐ฟ";
//Row#: 14
public static final String RIGHT_POINTING_BACKHAND_INDEX = "๐"; //https://www.emojibase.com/emoji/1f449/whiterightpointingbackhandindex //http://emojipedia.org/white-right-pointing-backhand-index/
public static final String RIGHT_POINTING_BACKHAND_INDEX_TYPE_1_2 = "๐๐ป";
public static final String RIGHT_POINTING_BACKHAND_INDEX_TYPE_3 = "๐๐ผ";
public static final String RIGHT_POINTING_BACKHAND_INDEX_TYPE_4 = "๐๐ฝ";
public static final String RIGHT_POINTING_BACKHAND_INDEX_TYPE_5 = "๐๐พ";
public static final String RIGHT_POINTING_BACKHAND_INDEX_TYPE_6 = "๐๐ฟ";
public static final String REVERSE_MIDDLE_FINGER = "๐"; //https://www.emojibase.com/emoji/1f595/reversedhandwithmiddlefingerextended //http://emojipedia.org/reversed-hand-with-middle-finger-extended/
public static final String REVERSE_MIDDLE_FINGER_TYPE_1_2 = "๐๐ป";
public static final String REVERSE_MIDDLE_FINGER_TYPE_3 = "๐๐ผ";
public static final String REVERSE_MIDDLE_FINGER_TYPE_4 = "๐๐ฝ";
public static final String REVERSE_MIDDLE_FINGER_TYPE_5 = "๐๐พ";
public static final String REVERSE_MIDDLE_FINGER_TYPE_6 = "๐๐ฟ";
public static final String RAISED_HAND_FINGERS_SPLAYED = "๐"; //https://www.emojibase.com/emoji/1f590/raisedhandwithfingerssplayed //http://emojipedia.org/raised-hand-with-fingers-splayed/
public static final String RAISED_HAND_FINGERS_SPLAYED_TYPE_1_2 = "๐๐ป";
public static final String RAISED_HAND_FINGERS_SPLAYED_TYPE_3 = "๐๐ผ";
public static final String RAISED_HAND_FINGERS_SPLAYED_TYPE_4 = "๐๐ฝ";
public static final String RAISED_HAND_FINGERS_SPLAYED_TYPE_5 = "๐๐พ";
public static final String RAISED_HAND_FINGERS_SPLAYED_TYPE_6 = "๐๐ฟ";
public static final String SIGN_OF_HORN = "๐ค"; //http://emojipedia.org/sign-of-the-horns/
public static final String SIGN_OF_HORN_TYPE_1_2 = "๐ค๐ป";
public static final String SIGN_OF_HORN_TYPE_3 = "๐ค๐ผ";
public static final String SIGN_OF_HORN_TYPE_4 = "๐ค๐ฝ";
public static final String SIGN_OF_HORN_TYPE_5 = "๐ค๐พ";
public static final String SIGN_OF_HORN_TYPE_6 = "๐ค๐ฟ";
public static final String RAISED_HAND_PART_BETWEEN_MIDDLE_RING = "๐"; //https://www.emojibase.com/emoji/1f596/raisedhandwithpartbetweenmiddleandringfingers //http://emojipedia.org/raised-hand-with-part-between-middle-and-ring-fingers/
public static final String RAISED_HAND_PART_BETWEEN_MIDDLE_RING_TYPE_1_2 = "๐๐ป";
public static final String RAISED_HAND_PART_BETWEEN_MIDDLE_RING_TYPE_3 = "๐๐ผ";
public static final String RAISED_HAND_PART_BETWEEN_MIDDLE_RING_TYPE_4 = "๐๐ฝ";
public static final String RAISED_HAND_PART_BETWEEN_MIDDLE_RING_TYPE_5 = "๐๐พ";
public static final String RAISED_HAND_PART_BETWEEN_MIDDLE_RING_TYPE_6 = "๐๐ฟ";
public static final String WRITING_HAND = "โ"; //https://www.emojibase.com/emoji/270d/writinghand //http://emojipedia.org/writing-hand/
public static final String WRITING_HAND_TYPE_1_2 = "โ๐ป";
public static final String WRITING_HAND_TYPE_3 = "โ๐ผ";
public static final String WRITING_HAND_TYPE_4 = "โ๐ฝ";
public static final String WRITING_HAND_TYPE_5 = "โ๐พ";
public static final String WRITING_HAND_TYPE_6 = "โ๐ฟ";
public static final String NAIL_POLISH = "๐
"; //https://www.emojibase.com/emoji/1f485/nailpolish //http://emojipedia.org/nail-polish/
public static final String NAIL_POLISH_TYPE_1_2 = "๐
๐ป";
public static final String NAIL_POLISH_TYPE_3 = "๐
๐ผ";
public static final String NAIL_POLISH_TYPE_4 = "๐
๐ฝ";
public static final String NAIL_POLISH_TYPE_5 = "๐
๐พ";
public static final String NAIL_POLISH_TYPE_6 = "๐
๐ฟ";
public static final String MOUTH = "๐"; //https://www.emojibase.com/emoji/1f444/mouth
//Row#: 15
public static final String TONGUE = "๐
"; //https://www.emojibase.com/emoji/1f445/tongue
public static final String EAR = "๐"; //https://www.emojibase.com/emoji/1f442/ear //http://emojipedia.org/ear/
public static final String EAR_TYPE_1_2 = "๐๐ป";
public static final String EAR_TYPE_3 = "๐๐ผ";
public static final String EAR_TYPE_4 = "๐๐ฝ";
public static final String EAR_TYPE_5 = "๐๐พ";
public static final String EAR_TYPE_6 = "๐๐ฟ";
public static final String NOSE = "๐"; //https://www.emojibase.com/emoji/1f443/nose //http://emojipedia.org/nose/
public static final String NOSE_TYPE_1_2 = "๐๐ป";
public static final String NOSE_TYPE_3 = "๐๐ผ";
public static final String NOSE_TYPE_4 = "๐๐ฝ";
public static final String NOSE_TYPE_5 = "๐๐พ";
public static final String NOSE_TYPE_6 = "๐๐ฟ";
public static final String EYE = "๐"; //https://www.emojibase.com/emoji/1f441/eye
public static final String EYES = "๐"; //https://www.emojibase.com/emoji/1f440/eyes
public static final String BUST_IN_SILHOUETTE = "๐ค"; //https://www.emojibase.com/emoji/1f464/bustinsilhouette
public static final String BUSTS_IN_SILHOUETTE = "๐ฅ"; //https://www.emojibase.com/emoji/1f465/bustsinsilhouette
public static final String SPEAKING_HEAD_IN_SILHOUETTE = "๐ฃ"; //https://www.emojibase.com/emoji/1f5e3/speakingheadinsilhouette
//Row#: 16
public static final String BABY = "๐ถ"; //https://www.emojibase.com/emoji/1f476/baby //http://emojipedia.org/baby/
public static final String BABY_TYPE_1_2 = "๐ถ๐ป";
public static final String BABY_TYPE_3 = "๐ถ๐ผ";
public static final String BABY_TYPE_4 = "๐ถ๐ฝ";
public static final String BABY_TYPE_5 = "๐ถ๐พ";
public static final String BABY_TYPE_6 = "๐ถ๐ฟ";
public static final String BOY = "๐ฆ"; //https://www.emojibase.com/emoji/1f466/boy //http://emojipedia.org/boy/
public static final String BOY_TYPE_1_2 = "๐ฆ๐ป";
public static final String BOY_TYPE_3 = "๐ฆ๐ผ";
public static final String BOY_TYPE_4 = "๐ฆ๐ฝ";
public static final String BOY_TYPE_5 = "๐ฆ๐พ";
public static final String BOY_TYPE_6 = "๐ฆ๐ฟ";
public static final String GIRL = "๐ง"; //https://www.emojibase.com/emoji/1f467/girl //http://emojipedia.org/girl/
public static final String GIRL_TYPE_1_2 = "๐ง๐ป";
public static final String GIRL_TYPE_3 = "๐ง๐ผ";
public static final String GIRL_TYPE_4 = "๐ง๐ฝ";
public static final String GIRL_TYPE_5 = "๐ง๐พ";
public static final String GIRL_TYPE_6 = "๐ง๐ฟ";
public static final String MAN = "๐จ"; //https://www.emojibase.com/emoji/1f468/man //http://emojipedia.org/man/
public static final String MAN_TYPE_1_2 = "๐จ๐ป";
public static final String MAN_TYPE_3 = "๐จ๐ผ";
public static final String MAN_TYPE_4 = "๐จ๐ฝ";
public static final String MAN_TYPE_5 = "๐จ๐พ";
public static final String MAN_TYPE_6 = "๐จ๐ฟ";
public static final String WOMEN = "๐ฉ"; //https://www.emojibase.com/emoji/1f469/woman //http://emojipedia.org/woman/
public static final String WOMEN_TYPE_1_2 = "๐ฉ๐ป";
public static final String WOMEN_TYPE_3 = "๐ฉ๐ผ";
public static final String WOMEN_TYPE_4 = "๐ฉ๐ฝ";
public static final String WOMEN_TYPE_5 = "๐ฉ๐พ";
public static final String WOMEN_TYPE_6 = "๐ฉ๐ฟ";
public static final String PERSON_WITH_BLOND_HAIR = "๐ฑ"; //https://www.emojibase.com/emoji/1f471/personwithblondhair //http://emojipedia.org/person-with-blond-hair/
public static final String PERSON_WITH_BLOND_HAIR_TYPE_1_2 = "๐ฑ๐ป";
public static final String PERSON_WITH_BLOND_HAIR_TYPE_3 = "๐ฑ๐ผ";
public static final String PERSON_WITH_BLOND_HAIR_TYPE_4 = "๐ฑ๐ฝ";
public static final String PERSON_WITH_BLOND_HAIR_TYPE_5 = "๐ฑ๐พ";
public static final String PERSON_WITH_BLOND_HAIR_TYPE_6 = "๐ฑ๐ฟ";
public static final String OLDER_MAN = "๐ด"; //https://www.emojibase.com/emoji/1f474/olderman //http://emojipedia.org/older-man/
public static final String OLDER_MAN_TYPE_1_2 = "๐ด๐ป";
public static final String OLDER_MAN_TYPE_3 = "๐ด๐ผ";
public static final String OLDER_MAN_TYPE_4 = "๐ด๐ฝ";
public static final String OLDER_MAN_TYPE_5 = "๐ด๐พ";
public static final String OLDER_MAN_TYPE_6 = "๐ด๐ฟ";
public static final String OLDER_WOMEN = "๐ต"; //https://www.emojibase.com/emoji/1f475/olderwoman //http://emojipedia.org/older-woman/
public static final String OLDER_WOMEN_TYPE_1_2 = "๐ต๐ป";
public static final String OLDER_WOMEN_TYPE_3 = "๐ต๐ผ";
public static final String OLDER_WOMEN_TYPE_4 = "๐ต๐ฝ";
public static final String OLDER_WOMEN_TYPE_5 = "๐ต๐พ";
public static final String OLDER_WOMEN_TYPE_6 = "๐ต๐ฟ";
//Row#: 17
public static final String MAN_WITH_GUA_PI_MAO = "๐ฒ"; //https://www.emojibase.com/emoji/1f472/manwithguapimao //http://emojipedia.org/man-with-gua-pi-mao/
public static final String MAN_WITH_GUA_PI_MAO_TYPE_1_2 = "๐ฒ๐ผ";
public static final String MAN_WITH_GUA_PI_MAO_TYPE_3 = "๐ฒ๐ผ";
public static final String MAN_WITH_GUA_PI_MAO_TYPE_4 = "๐ฒ๐ฝ";
public static final String MAN_WITH_GUA_PI_MAO_TYPE_5 = "๐ฒ๐พ";
public static final String MAN_WITH_GUA_PI_MAO_TYPE_6 = "๐ฒ๐ฟ";
public static final String MAN_WITH_TURBAN = "๐ณ"; //https://www.emojibase.com/emoji/1f473/manwithturban //http://emojipedia.org/man-with-turban/
public static final String MAN_WITH_TURBAN_TYPE_1_2 = "๐ณ๐ป";
public static final String MAN_WITH_TURBAN_TYPE_3 = "๐ณ๐ผ";
public static final String MAN_WITH_TURBAN_TYPE_4 = "๐ณ๐ฝ";
public static final String MAN_WITH_TURBAN_TYPE_5 = "๐ณ๐พ";
public static final String MAN_WITH_TURBAN_TYPE_6 = "๐ณ๐ฟ";
public static final String POLICE_OFFICER = "๐ฎ"; //https://www.emojibase.com/emoji/1f46e/policeofficer //http://emojipedia.org/police-officer/
public static final String POLICE_OFFICER_TYPE_1_2 = "๐ฎ๐ป";
public static final String POLICE_OFFICER_TYPE_3 = "๐ฎ๐ผ";
public static final String POLICE_OFFICER_TYPE_4 = "๐ฎ๐ฝ";
public static final String POLICE_OFFICER_TYPE_5 = "๐ฎ๐พ";
public static final String POLICE_OFFICER_TYPE_6 = "๐ฎ๐ฟ";
public static final String CONSTRUCTION_WORKER = "๐ท"; //https://www.emojibase.com/emoji/1f477/constructionworker //http://emojipedia.org/construction-worker/
public static final String CONSTRUCTION_WORKER_TYPE_1_2 = "๐ท๐ป";
public static final String CONSTRUCTION_WORKER_TYPE_3 = "๐ท๐ผ";
public static final String CONSTRUCTION_WORKER_TYPE_4 = "๐ท๐ฝ";
public static final String CONSTRUCTION_WORKER_TYPE_5 = "๐ท๐พ";
public static final String CONSTRUCTION_WORKER_TYPE_6 = "๐ท๐ฟ";
public static final String GUARDS_MAN = "๐"; //https://www.emojibase.com/emoji/1f482/guardsman //http://emojipedia.org/guardsman/
public static final String GUARDS_MAN_TYPE_1_2 = "๐๐ป";
public static final String GUARDS_MAN_TYPE_3 = "๐๐ผ";
public static final String GUARDS_MAN_TYPE_4 = "๐๐ฝ";
public static final String GUARDS_MAN_TYPE_5 = "๐๐พ";
public static final String GUARDS_MAN_TYPE_6 = "๐๐ฟ";
public static final String SPY = "๐ต"; //https://www.emojibase.com/emoji/1f575/sleuthorspy
public static final String FATHER_CHRISTMAS = "๐
"; //https://www.emojibase.com/emoji/1f385/fatherchristmas //http://emojipedia.org/father-christmas/
public static final String FATHER_CHRISTMAS_TYPE_1_2 = "๐
๐ป";
public static final String FATHER_CHRISTMAS_TYPE_3 = "๐
๐ผ";
public static final String FATHER_CHRISTMAS_TYPE_4 = "๐
๐ฝ";
public static final String FATHER_CHRISTMAS_TYPE_5 = "๐
๐พ";
public static final String FATHER_CHRISTMAS_TYPE_6 = "๐
๐ฟ";
public static final String BABY_ANGEL = "๐ผ"; //https://www.emojibase.com/emoji/1f47c/babyangel //http://emojipedia.org/baby-angel/
public static final String BABY_ANGEL_TYPE_1_2 = "๐ผ๐ป";
public static final String BABY_ANGEL_TYPE_3 = "๐ผ๐ผ";
public static final String BABY_ANGEL_TYPE_4 = "๐ผ๐ฝ";
public static final String BABY_ANGEL_TYPE_5 = "๐ผ๐พ";
public static final String BABY_ANGEL_TYPE_6 = "๐ผ๐ฟ";
//Row#: 18
public static final String PRINCESS = "๐ธ"; //https://www.emojibase.com/emoji/1f478/princess //http://emojipedia.org/princess/
public static final String PRINCESS_TYPE_1_2 = "๐ธ๐ป";
public static final String PRINCESS_TYPE_3 = "๐ธ๐ผ";
public static final String PRINCESS_TYPE_4 = "๐ธ๐ฝ";
public static final String PRINCESS_TYPE_5 = "๐ธ๐พ";
public static final String PRINCESS_TYPE_6 = "๐ธ๐ฟ";
public static final String BRIDE_WITH_VEIL = "๐ฐ"; //https://www.emojibase.com/emoji/1f470/bridewithveil //http://emojipedia.org/bride-with-veil/
public static final String BRIDE_WITH_VEIL_TYPE_1_2 = "๐ฐ๐ป";
public static final String BRIDE_WITH_VEIL_TYPE_3 = "๐ฐ๐ผ";
public static final String BRIDE_WITH_VEIL_TYPE_4 = "๐ฐ๐ฝ";
public static final String BRIDE_WITH_VEIL_TYPE_5 = "๐ฐ๐พ";
public static final String BRIDE_WITH_VEIL_TYPE_6 = "๐ฐ๐ฟ";
public static final String PEDESTRIAN = "๐ถ"; //https://www.emojibase.com/emoji/1f6b6/pedestrian //http://emojipedia.org/pedestrian/
public static final String PEDESTRIAN_TYPE_1_2 = "๐ถ๐ป";
public static final String PEDESTRIAN_TYPE_3 = "๐ถ๐ผ";
public static final String PEDESTRIAN_TYPE_4 = "๐ถ๐ฝ";
public static final String PEDESTRIAN_TYPE_5 = "๐ถ๐พ";
public static final String PEDESTRIAN_TYPE_6 = "๐ถ๐ฟ";
public static final String RUNNER = "๐"; //https://www.emojibase.com/emoji/1f3c3/runner //http://emojipedia.org/runner/
public static final String RUNNER_TYPE_1_2 = "๐๐ป";
public static final String RUNNER_TYPE_3 = "๐๐ผ";
public static final String RUNNER_TYPE_4 = "๐๐ฝ";
public static final String RUNNER_TYPE_5 = "๐๐พ";
public static final String RUNNER_TYPE_6 = "๐๐ฟ";
public static final String DANCER = "๐"; //https://www.emojibase.com/emoji/1f483/dancer //http://emojipedia.org/dancer/
public static final String DANCER_TYPE_1_2 = "๐๐ป";
public static final String DANCER_TYPE_3 = "๐๐ผ";
public static final String DANCER_TYPE_4 = "๐๐ฝ";
public static final String DANCER_TYPE_5 = "๐๐พ";
public static final String DANCER_TYPE_6 = "๐๐ฟ";
public static final String WOMEN_WITH_BUNNY_YEARS = "๐ฏ"; //https://www.emojibase.com/emoji/1f46f/womanwithbunnyears
public static final String MAN_WOMEN_HOLDING_HANDS = "๐ซ"; //https://www.emojibase.com/emoji/1f46b/manandwomanholdinghands
public static final String TWO_MAN_HOLDING_HANDS = "๐ฌ"; //https://www.emojibase.com/emoji/1f46c/twomenholdinghands
//Row#: 19
public static final String TWO_WOMEN_HOLDING_HANDS = "๐ญ"; //https://www.emojibase.com/emoji/1f46d/twowomenholdinghands
public static final String PERSON_BOWING_DEEPLY = "๐"; //https://www.emojibase.com/emoji/1f647/personbowingdeeply //http://emojipedia.org/person-bowing-deeply/
public static final String PERSON_BOWING_DEEPLY_TYPE_1_2 = "๐๐ป";
public static final String PERSON_BOWING_DEEPLY_TYPE_3 = "๐๐ผ";
public static final String PERSON_BOWING_DEEPLY_TYPE_4 = "๐๐ฝ";
public static final String PERSON_BOWING_DEEPLY_TYPE_5 = "๐๐พ";
public static final String PERSON_BOWING_DEEPLY_TYPE_6 = "๐๐ฟ";
public static final String INFORMATION_DESK_PERSON = "๐"; //https://www.emojibase.com/emoji/1f481/informationdeskperson //http://emojipedia.org/information-desk-person/
public static final String INFORMATION_DESK_PERSON_TYPE_1_2 = "๐๐ป";
public static final String INFORMATION_DESK_PERSON_TYPE_3 = "๐๐ผ";
public static final String INFORMATION_DESK_PERSON_TYPE_4 = "๐๐ฝ";
public static final String INFORMATION_DESK_PERSON_TYPE_5 = "๐๐พ";
public static final String INFORMATION_DESK_PERSON_TYPE_6 = "๐๐ฟ";
public static final String FACE_WITH_NO_GOOD_GESTURE = "๐
"; //https://www.emojibase.com/emoji/1f645/facewithnogoodgesture //http://emojipedia.org/face-with-no-good-gesture/
public static final String FACE_WITH_NO_GOOD_GESTURE_TYPE_1_2 = "๐
๐ป";
public static final String FACE_WITH_NO_GOOD_GESTURE_TYPE_3 = "๐
๐ผ";
public static final String FACE_WITH_NO_GOOD_GESTURE_TYPE_4 = "๐
๐ฝ";
public static final String FACE_WITH_NO_GOOD_GESTURE_TYPE_5 = "๐
๐พ";
public static final String FACE_WITH_NO_GOOD_GESTURE_TYPE_6 = "๐
๐ฟ";
public static final String FACE_WITH_OK_GESTURE = "๐"; //https://www.emojibase.com/emoji/1f646/facewithokgesture //http://emojipedia.org/face-with-ok-gesture/
public static final String FACE_WITH_OK_GESTURE_TYPE_1_2 = "๐๐ป";
public static final String FACE_WITH_OK_GESTURE_TYPE_3 = "๐๐ผ";
public static final String FACE_WITH_OK_GESTURE_TYPE_4 = "๐๐ฝ";
public static final String FACE_WITH_OK_GESTURE_TYPE_5 = "๐๐พ";
public static final String FACE_WITH_OK_GESTURE_TYPE_6 = "๐๐ฟ";
public static final String HAPPY_PERSON_RAISE_ONE_HAND = "๐"; //https://www.emojibase.com/emoji/1f64b/happypersonraisingonehand //http://emojipedia.org/happy-person-raising-one-hand/
public static final String HAPPY_PERSON_RAISE_ONE_HAND_TYPE_1_2 = "๐๐ป";
public static final String HAPPY_PERSON_RAISE_ONE_HAND_TYPE_3 = "๐๐ผ";
public static final String HAPPY_PERSON_RAISE_ONE_HAND_TYPE_4 = "๐๐ฝ";
public static final String HAPPY_PERSON_RAISE_ONE_HAND_TYPE_5 = "๐๐พ";
public static final String HAPPY_PERSON_RAISE_ONE_HAND_TYPE_6 = "๐๐ฟ";
public static final String PERSON_WITH_POUTING_FACE = "๐"; //https://www.emojibase.com/emoji/1f64e/personwithpoutingface //http://emojipedia.org/person-with-pouting-face/
public static final String PERSON_WITH_POUTING_FACE_TYPE_1_2 = "๐๐ป";
public static final String PERSON_WITH_POUTING_FACE_TYPE_3 = "๐๐ผ";
public static final String PERSON_WITH_POUTING_FACE_TYPE_4 = "๐๐ฝ";
public static final String PERSON_WITH_POUTING_FACE_TYPE_5 = "๐๐พ";
public static final String PERSON_WITH_POUTING_FACE_TYPE_6 = "๐๐ฟ";
public static final String PERSON_FROWNING = "๐"; //https://www.emojibase.com/emoji/1f64d/personfrowning //http://emojipedia.org/person-frowning/
public static final String PERSON_FROWNING_TYPE_1_2 = "๐๐ป";
public static final String PERSON_FROWNING_TYPE_3 = "๐๐ผ";
public static final String PERSON_FROWNING_TYPE_4 = "๐๐ฝ";
public static final String PERSON_FROWNING_TYPE_5 = "๐๐พ";
public static final String PERSON_FROWNING_TYPE_6 = "๐๐ฟ";
//Row#: 20
public static final String HAIRCUT = "๐"; //https://www.emojibase.com/emoji/1f487/haircut //http://emojipedia.org/haircut/
public static final String HAIRCUT_TYPE_1_2 = "๐๐ป";
public static final String HAIRCUT_TYPE_3 = "๐๐ผ";
public static final String HAIRCUT_TYPE_4 = "๐๐ฝ";
public static final String HAIRCUT_TYPE_5 = "๐๐พ";
public static final String HAIRCUT_TYPE_6 = "๐๐ฟ";
public static final String FACE_MASSAGE = "๐"; //https://www.emojibase.com/emoji/1f486/facemassage //http://emojipedia.org/face-massage/
public static final String FACE_MASSAGE_TYPE_1_2 = "๐๐ป";
public static final String FACE_MASSAGE_TYPE_3 = "๐๐ป";
public static final String FACE_MASSAGE_TYPE_4 = "๐๐ฝ";
public static final String FACE_MASSAGE_TYPE_5 = "๐๐พ";
public static final String FACE_MASSAGE_TYPE_6 = "๐๐ฟ";
public static final String COUPLE_WITH_HEART = "๐"; //https://www.emojibase.com/emoji/1f491/couplewithheart
public static final String COUPLE_WITH_HEART_WOMAN = "๐ฉโโค๏ธโ๐ฉ"; //http://emojipedia.org/couple-with-heart-woman-woman/
public static final String COUPLE_WITH_HEART_MAN = "๐จโโค๏ธโ๐จ"; //http://emojipedia.org/couple-with-heart-man-man/
public static final String KISS = "๐"; //https://www.emojibase.com/emoji/1f48f/kiss
public static final String KISS_WOMAN = "๐ฉโโค๏ธโ๐โ๐ฉ"; //http://emojipedia.org/kiss-woman-woman/
public static final String KISS_MAN = "๐จโโค๏ธโ๐โ๐จ"; //http://emojipedia.org/kiss-man-man/
//Row#: 21
public static final String FAMILY = "๐ช"; //https://www.emojibase.com/emoji/1f46a/family
public static final String FAMILY_MAN_WOMEN_GIRL = "๐จโ๐ฉโ๐ง"; //http://emojipedia.org/family-man-woman-girl/
public static final String FAMILY_MAN_WOMEN_GIRL_BOY = "๐จโ๐ฉโ๐งโ๐ฆ"; //http://emojipedia.org/family-man-woman-girl-boy/
public static final String FAMILY_MAN_WOMEN_BOY_BOY = "๐จโ๐ฉโ๐ฆโ๐ฆ"; //http://emojipedia.org/family-man-woman-boy-boy/
public static final String FAMILY_MAN_WOMEN_GIRL_GIRL = "๐จโ๐ฉโ๐งโ๐ง"; //http://emojipedia.org/family-man-woman-girl-girl/
public static final String FAMILY_WOMAN_WOMEN_BOY = "๐ฉโ๐ฉโ๐ฆ"; //http://emojipedia.org/family-woman-woman-boy/
public static final String FAMILY_WOMAN_WOMEN_GIRL = "๐ฉโ๐ฉโ๐ง"; //http://emojipedia.org/family-woman-woman-girl/
public static final String FAMILY_WOMAN_WOMEN_GIRL_BOY = "๐ฉโ๐ฉโ๐งโ๐ฆ"; //http://emojipedia.org/family-woman-woman-girl-boy/
//Row#: 22
public static final String FAMILY_WOMAN_WOMEN_BOY_BOY = "๐ฉโ๐ฉโ๐ฆโ๐ฆ"; //http://emojipedia.org/family-woman-woman-boy-boy/
public static final String FAMILY_WOMAN_WOMEN_GIRL_GIRL = "๐ฉโ๐ฉโ๐งโ๐ง"; //http://emojipedia.org/family-woman-woman-girl-girl/
public static final String FAMILY_MAN_MAN_BOY = "๐จโ๐จโ๐ฆ"; //http://emojipedia.org/family-man-man-boy/
public static final String FAMILY_MAN_MAN_GIRL = "๐จโ๐จโ๐ง"; //http://emojipedia.org/family-man-man-girl/
public static final String FAMILY_MAN_MAN_GIRL_BOY = "๐จโ๐จโ๐งโ๐ฆ"; //http://emojipedia.org/family-man-man-girl-boy/
public static final String FAMILY_MAN_MAN_BOY_BOY = "๐จโ๐จโ๐ฆโ๐ฆ"; //http://emojipedia.org/family-man-man-boy-boy/
public static final String FAMILY_MAN_MAN_GIRL_GIRL = "๐จโ๐จโ๐งโ๐ง"; //http://emojipedia.org/family-man-man-girl-girl/
public static final String WOMAN_CLOTHES = "๐"; //https://www.emojibase.com/emoji/1f45a/womansclothes
//Row#: 23
public static final String T_SHIRT = "๐"; //https://www.emojibase.com/emoji/1f455/tshirt
public static final String JEANS = "๐"; //https://www.emojibase.com/emoji/1f456/jeans
public static final String NECKTIE = "๐"; //https://www.emojibase.com/emoji/1f454/necktie
public static final String DRESS = "๐"; //https://www.emojibase.com/emoji/1f457/dress
public static final String BIKINI = "๐"; //https://www.emojibase.com/emoji/1f459/bikini
public static final String KIMONO = "๐"; //https://www.emojibase.com/emoji/1f458/kimono
public static final String LIPSTICK = "๐"; //https://www.emojibase.com/emoji/1f484/lipstick
public static final String KISS_MARK = "๐"; //https://www.emojibase.com/emoji/1f48b/kissmark
//Row#: 24
public static final String FOOTPRINTS = "๐ฃ"; //https://www.emojibase.com/emoji/1f463/footprints
public static final String HIGH_HEELED_SHOE = "๐ "; //https://www.emojibase.com/emoji/1f460/highheeledshoe
public static final String WOMAN_SANDAL = "๐ก"; //https://www.emojibase.com/emoji/1f461/womanssandal
public static final String WOMAN_BOOTS = "๐ข"; //https://www.emojibase.com/emoji/1f462/womansboots
public static final String MAN_SHOE = "๐"; //https://www.emojibase.com/emoji/1f45e/mansshoe
public static final String ATHLETIC_SHOE = "๐"; //https://www.emojibase.com/emoji/1f45f/athleticshoe
public static final String WOMAN_HAT = "๐"; //https://www.emojibase.com/emoji/1f452/womanshat
public static final String TOP_HAT = "๐ฉ"; //https://www.emojibase.com/emoji/1f3a9/tophat
//Row#: 25
public static final String GRADUATION_CAP = "๐"; //https://www.emojibase.com/emoji/1f393/graduationcap
public static final String CROWN = "๐"; //https://www.emojibase.com/emoji/1f451/crown
public static final String HELMET_WITH_WHITE_CROSS = "โ"; //https://www.emojibase.com/emoji/26d1/helmetwithwhitecross
public static final String SCHOOL_SATCHEL = "๐"; //https://www.emojibase.com/emoji/1f392/schoolsatchel
public static final String POUCH = "๐"; //https://www.emojibase.com/emoji/1f45d/pouch
public static final String PURSE = "๐"; //https://www.emojibase.com/emoji/1f45b/purse
public static final String HANDBAG = "๐"; //https://www.emojibase.com/emoji/1f45c/handbag
public static final String BRIEFCASE = "๐ผ"; //https://www.emojibase.com/emoji/1f4bc/briefcase
//Row#: 26
public static final String EYE_GLASSES = "๐"; //https://www.emojibase.com/emoji/1f453/eyeglasses
public static final String DARK_SUN_GLASSES = "๐ถ"; //https://www.emojibase.com/emoji/1f576/darksunglasses
public static final String RING = "๐"; //https://www.emojibase.com/emoji/1f48d/ring
public static final String CLOSED_UMBRELLA = "๐"; //https://www.emojibase.com/emoji/1f302/closedumbrella
}
| mit |
PenguinSquad/Harvest-Festival | src/main/java/joshie/harvest/shops/purchasable/PurchasableTrade.java | 1674 | package joshie.harvest.shops.purchasable;
import joshie.harvest.animals.item.ItemAnimalProduct.Sizeable;
import joshie.harvest.api.shops.IRequirement;
import joshie.harvest.core.helpers.SpawnItemHelper;
import joshie.harvest.core.helpers.StackHelper;
import joshie.harvest.shops.requirement.RequirementSizeable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
public class PurchasableTrade extends PurchasableMaterials {
private RequirementSizeable requirement;
private ItemStack purchased;
private ItemStack large;
private ItemStack medium;
private ItemStack small;
public static int ticker;
public PurchasableTrade(ItemStack stack, Sizeable sizeable) {
super(0, stack);
this.requirement = new RequirementSizeable(this, sizeable);
this.requirements = new IRequirement[] { requirement };
this.large = StackHelper.toStack(stack, 3);
this.medium = StackHelper.toStack(stack, 2);
this.small = StackHelper.toStack(stack, 1);
}
@Override
public ItemStack getDisplayStack() {
ticker++;
int num = ticker %1800;
if (num < 600) return small;
else if (num < 1200) return medium;
else return large;
}
@Override
protected ItemStack getPurchasedStack() {
return purchased;
}
@Override
public void onPurchased(EntityPlayer player) {
purchased = this.stack.copy();
int amount = requirement.getPurchased(player);
if (amount != 0) {
purchased.stackSize = amount;
SpawnItemHelper.addToPlayerInventory(player, purchased);
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/security/azure-resourcemanager-security/src/main/java/com/azure/resourcemanager/security/fluent/models/AdaptiveApplicationControlGroupsInner.java | 1698 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.security.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Represents a list of machine groups and set of rules that are recommended by Azure Security Center to be allowed. */
@Fluent
public final class AdaptiveApplicationControlGroupsInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(AdaptiveApplicationControlGroupsInner.class);
/*
* The value property.
*/
@JsonProperty(value = "value")
private List<AdaptiveApplicationControlGroupInner> value;
/**
* Get the value property: The value property.
*
* @return the value value.
*/
public List<AdaptiveApplicationControlGroupInner> value() {
return this.value;
}
/**
* Set the value property: The value property.
*
* @param value the value value to set.
* @return the AdaptiveApplicationControlGroupsInner object itself.
*/
public AdaptiveApplicationControlGroupsInner withValue(List<AdaptiveApplicationControlGroupInner> value) {
this.value = value;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() != null) {
value().forEach(e -> e.validate());
}
}
}
| mit |
mojtaba-khallash/JHazm | JHazm/src/main/java/jhazm/reader/BijankhanReader.java | 4863 | package jhazm.reader;
import com.infomancers.collections.yield.Yielder;
import edu.stanford.nlp.ling.TaggedWord;
import jhazm.Normalizer;
import jhazm.tokenizer.WordTokenizer;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
/**
* interfaces Bijankhan Corpus (http://ece.ut.ac.ir/dbrg/bijankhan/Corpus/BijanKhan_Corpus_Processed.zip) that
* you must download and extract it.
*
* @author Mojtaba Khallash
*/
public class BijankhanReader {
//
// Fields
//
private final String[] punctuation = new String[] { "#", "*", ".", "ุ", "!" };
private String bijankhanFile;
private boolean joinedVerbParts;
private String posMap;
private Normalizer normalizer;
private WordTokenizer tokenizer;
//
// Constructors
//
public BijankhanReader() throws IOException {
this("resources/corpora/bijankhan.txt", true, "resources/data/posMaps.dat");
}
public BijankhanReader(boolean joinedVerbParts) throws IOException {
this("resources/corpora/bijankhan.txt", joinedVerbParts, "resources/data/posMaps.dat");
}
public BijankhanReader(String posMap) throws IOException {
this("resources/corpora/bijankhan.txt", true, posMap);
}
public BijankhanReader(boolean joinedVerbParts, String posMap)
throws IOException {
this("resources/corpora/bijankhan.txt", joinedVerbParts, posMap);
}
public BijankhanReader(String bijankhanFile, boolean joinedVerbParts, String posMap)
throws IOException {
this.bijankhanFile = bijankhanFile;
this.joinedVerbParts = joinedVerbParts;
this.posMap = posMap;
this.normalizer = new Normalizer(true, false, true);
this.tokenizer = new WordTokenizer();
}
//
// API
//
public Iterable<List<TaggedWord>> getSentences() {
return new YieldSentence();
}
//
// Helper
//
private String getBijankhanFile() {
return bijankhanFile;
}
private boolean isJoinedVerbParts() {
return joinedVerbParts;
}
private HashMap getPosMap() throws IOException {
if (this.posMap != null) {
HashMap mapper = new HashMap();
for (String line : Files.readAllLines(Paths.get(this.posMap), Charset.forName("UTF8"))) {
String[] parts = line.split(",");
mapper.put(parts[0], parts[1]);
}
return mapper;
}
else
return null;
}
private Normalizer getNormalizer() {
return normalizer;
}
class YieldSentence extends Yielder<List<TaggedWord>> {
private BufferedReader br;
public YieldSentence() {
try {
FileInputStream fstream = new FileInputStream(getBijankhanFile());
DataInputStream in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF8")));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
protected void yieldNextCore() {
try {
HashMap mapper = getPosMap();
List<TaggedWord> sentence = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.trim().split(" +");
if (parts.length == 2) {
String word = parts[0];
String tag = parts[1];
if (!(word.equals("#") || word.equals("*"))) {
word = getNormalizer().run(word);
if (word.isEmpty())
word = "_";
sentence.add(new TaggedWord(word, tag));
}
if (tag.equals("DELM") && Arrays.asList(punctuation).contains(word)) {
if (!sentence.isEmpty()) {
if (isJoinedVerbParts())
sentence = PeykareReader.joinVerbParts(sentence);
if (mapper != null) {
for (TaggedWord tword : sentence) {
tword.setTag(mapper.get(tword.tag()).toString());
}
}
yieldReturn(sentence);
return;
}
}
}
}
br.close();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
} | mit |
DDoS/JICI | src/test/java/ca/sapon/jici/test/LexerTest.java | 10195 | /*
* This file is part of JICI, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/>
*
* 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 ca.sapon.jici.test;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import ca.sapon.jici.lexer.Keyword;
import ca.sapon.jici.lexer.Lexer;
import ca.sapon.jici.lexer.LexerException;
import ca.sapon.jici.lexer.Symbol;
import ca.sapon.jici.lexer.Token;
import ca.sapon.jici.lexer.TokenGroup;
import ca.sapon.jici.lexer.TokenID;
public class LexerTest {
@Test
public void testLexEmpty() {
Assert.assertEquals(0, Lexer.lex("").size());
}
@Test
public void testLexSpaces() {
Assert.assertEquals(0, Lexer.lex(" \t\f").size());
}
@Test
public void testLexLineTerminators() {
Assert.assertEquals(0, Lexer.lex("\r\n").size());
}
@Test
public void testLexIdentifier() {
testLex(TokenID.IDENTIFIER, "t");
testLex(TokenID.IDENTIFIER, "test");
testLex(TokenID.IDENTIFIER, "_");
testLex(TokenID.IDENTIFIER, "_t");
testLex(TokenID.IDENTIFIER, "_test");
testLex(TokenID.IDENTIFIER, "te_st");
testLex(TokenID.IDENTIFIER, "test_");
testLex(TokenID.IDENTIFIER, "t_");
testLex(TokenID.IDENTIFIER, "$");
testLex(TokenID.IDENTIFIER, "$t");
testLex(TokenID.IDENTIFIER, "$test");
testLex(TokenID.IDENTIFIER, "te$st");
testLex(TokenID.IDENTIFIER, "test$");
testLex(TokenID.IDENTIFIER, "t$");
testLex(TokenID.IDENTIFIER, "t1");
testLex(TokenID.IDENTIFIER, "_1");
testLex(TokenID.IDENTIFIER, "$1");
testLex(TokenID.IDENTIFIER, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$");
}
@Test
public void testLexKeyword() {
for (Keyword keyword : Keyword.all()) {
testLex(keyword.getID(), keyword.getSource());
}
}
@Test
public void testLexSymbol() {
for (Symbol symbol : Symbol.all()) {
if (symbol.getGroup() != TokenGroup.COMMENT_DELIMITER) {
testLex(symbol.getID(), symbol.getSource());
}
}
}
@Test
public void testLexBooleanLiteral() {
testLex(TokenID.LITERAL_TRUE, "true");
testLex(TokenID.LITERAL_FALSE, "false");
}
@Test
public void testLexCharacterLiteral() {
testLex(TokenID.LITERAL_CHARACTER, "'a'");
testLex(TokenID.LITERAL_CHARACTER, "'\\''");
testLex(TokenID.LITERAL_CHARACTER, "'\\\\'");
testLex(TokenID.LITERAL_CHARACTER, "'\\n'");
testLex(TokenID.LITERAL_CHARACTER, "'\\u0061'");
}
@Test
public void testLexStringLiteral() {
testLex(TokenID.LITERAL_STRING, "\"\"");
testLex(TokenID.LITERAL_STRING, "\"t\"");
testLex(TokenID.LITERAL_STRING, "\"test\"");
testLex(TokenID.LITERAL_STRING, "\"this is a test\"");
testLex(TokenID.LITERAL_STRING, "\"\\\"\"");
testLex(TokenID.LITERAL_STRING, "\"\\\\\"");
testLex(TokenID.LITERAL_STRING, "\"\\n\"");
}
@Test
public void testLexNullLiteral() {
testLex(TokenID.LITERAL_NULL, "null");
}
@Test
public void testLexDoubleLiteral() {
testLex(TokenID.LITERAL_DOUBLE, "1.");
testLex(TokenID.LITERAL_DOUBLE, "1.0");
testLex(TokenID.LITERAL_DOUBLE, ".1");
testLex(TokenID.LITERAL_DOUBLE, "1d");
testLex(TokenID.LITERAL_DOUBLE, "1.d");
testLex(TokenID.LITERAL_DOUBLE, "1.0d");
testLex(TokenID.LITERAL_DOUBLE, ".1d");
testLex(TokenID.LITERAL_DOUBLE, "1e2");
testLex(TokenID.LITERAL_DOUBLE, "1.e2");
testLex(TokenID.LITERAL_DOUBLE, "1.0e2");
testLex(TokenID.LITERAL_DOUBLE, ".1e2");
testLex(TokenID.LITERAL_DOUBLE, "1e2d");
testLex(TokenID.LITERAL_DOUBLE, "1.e2d");
testLex(TokenID.LITERAL_DOUBLE, "1.0e2d");
testLex(TokenID.LITERAL_DOUBLE, ".1e2d");
testLex(TokenID.LITERAL_DOUBLE, "1e-2");
testLex(TokenID.LITERAL_DOUBLE, "1.e-2");
testLex(TokenID.LITERAL_DOUBLE, "1.0e-2");
testLex(TokenID.LITERAL_DOUBLE, ".1e-2");
testLex(TokenID.LITERAL_DOUBLE, "1e-2d");
testLex(TokenID.LITERAL_DOUBLE, "1.e-2d");
testLex(TokenID.LITERAL_DOUBLE, "1.0e-2d");
testLex(TokenID.LITERAL_DOUBLE, ".1e-2d");
testLex(TokenID.LITERAL_DOUBLE, "0x1p2");
testLex(TokenID.LITERAL_DOUBLE, "0x1.p2");
testLex(TokenID.LITERAL_DOUBLE, "0x.fp2");
testLex(TokenID.LITERAL_DOUBLE, "0x1.fp2");
testLex(TokenID.LITERAL_DOUBLE, "0x1p2d");
testLex(TokenID.LITERAL_DOUBLE, "0x1.p2d");
testLex(TokenID.LITERAL_DOUBLE, "0x.fp2d");
testLex(TokenID.LITERAL_DOUBLE, "0x1.fp2d");
testLex(TokenID.LITERAL_DOUBLE, "1D");
testLex(TokenID.LITERAL_DOUBLE, "1E2");
testLex(TokenID.LITERAL_DOUBLE, "1E2D");
testLex(TokenID.LITERAL_DOUBLE, "0X1P2");
testLex(TokenID.LITERAL_DOUBLE, "0X1P2D");
testLex(TokenID.LITERAL_DOUBLE, "1234567890d");
}
@Test
public void testLexFloatLiteral() {
testLex(TokenID.LITERAL_FLOAT, "1f");
testLex(TokenID.LITERAL_FLOAT, "1.f");
testLex(TokenID.LITERAL_FLOAT, "1.0f");
testLex(TokenID.LITERAL_FLOAT, ".1f");
testLex(TokenID.LITERAL_FLOAT, "1e2f");
testLex(TokenID.LITERAL_FLOAT, "1.e2f");
testLex(TokenID.LITERAL_FLOAT, "1.0e2f");
testLex(TokenID.LITERAL_FLOAT, ".1e2f");
testLex(TokenID.LITERAL_FLOAT, "1e-2f");
testLex(TokenID.LITERAL_FLOAT, "1.e-2f");
testLex(TokenID.LITERAL_FLOAT, "1.0e-2f");
testLex(TokenID.LITERAL_FLOAT, ".1e-2f");
testLex(TokenID.LITERAL_FLOAT, "0x1p2f");
testLex(TokenID.LITERAL_FLOAT, "0x1.p2f");
testLex(TokenID.LITERAL_FLOAT, "0x.fp2f");
testLex(TokenID.LITERAL_FLOAT, "0x1.fp2f");
testLex(TokenID.LITERAL_FLOAT, "1F");
testLex(TokenID.LITERAL_FLOAT, "1E2F");
testLex(TokenID.LITERAL_FLOAT, "0X1P2F");
testLex(TokenID.LITERAL_FLOAT, "1234567890f");
}
@Test
public void testLexIntLiteral() {
testLex(TokenID.LITERAL_INT, "1");
testLex(TokenID.LITERAL_INT, "0x1");
testLex(TokenID.LITERAL_INT, "0X1F");
testLex(TokenID.LITERAL_INT, "0b1");
testLex(TokenID.LITERAL_INT, "0B11");
testLex(TokenID.LITERAL_INT, "01");
testLex(TokenID.LITERAL_INT, "017");
testLex(TokenID.LITERAL_INT, "1234567890");
}
@Test
public void testLexLongLiteral() {
testLex(TokenID.LITERAL_LONG, "1l");
testLex(TokenID.LITERAL_LONG, "0x1l");
testLex(TokenID.LITERAL_LONG, "0X1Fl");
testLex(TokenID.LITERAL_LONG, "0b1l");
testLex(TokenID.LITERAL_LONG, "0B11l");
testLex(TokenID.LITERAL_LONG, "01l");
testLex(TokenID.LITERAL_LONG, "017l");
testLex(TokenID.LITERAL_LONG, "1L");
testLex(TokenID.LITERAL_LONG, "0X1L");
testLex(TokenID.LITERAL_LONG, "0B1L");
testLex(TokenID.LITERAL_LONG, "017L");
testLex(TokenID.LITERAL_LONG, "1234567890l");
}
@Test
public void testLexComments() {
Assert.assertEquals(0, Lexer.lex("//abcd").size());
Assert.assertEquals(0, Lexer.lex("///abcd").size());
Assert.assertEquals(0, Lexer.lex("//abcd\n").size());
Assert.assertEquals(0, Lexer.lex("//abcd\r").size());
Assert.assertEquals(0, Lexer.lex("//abcd\r\n").size());
Assert.assertEquals(0, Lexer.lex("/*abcd").size());
Assert.assertEquals(0, Lexer.lex("/*abcd*/").size());
assertEquals(TokenID.IDENTIFIER, "a", Lexer.lex("//0\na"));
assertEquals(TokenID.IDENTIFIER, "a", Lexer.lex("//0\ra"));
assertEquals(TokenID.IDENTIFIER, "a", Lexer.lex("//0\r\na"));
assertEquals(TokenID.IDENTIFIER, "a", Lexer.lex("/*0*/a"));
assertEquals(TokenID.IDENTIFIER, "a", Lexer.lex("///*\na"));
assertEquals(TokenID.IDENTIFIER, "a", Lexer.lex("/*//*/a"));
}
@Test
public void testLexUnknownCharacter() {
try {
testLex(null, "#");
Assert.fail();
} catch (LexerException ignored) {
}
try {
testLex(null, "te#st");
Assert.fail();
} catch (LexerException ignored) {
}
}
private void testLex(TokenID expectedID, String source) {
assertEquals(expectedID, source, Lexer.lex(source));
}
private void assertEquals(TokenID expectedID, String expectedSource, List<Token> actual) {
Assert.assertEquals("Expected one token, got many", 1, actual.size());
assertEquals(expectedID, expectedSource, actual.get(0));
}
private void assertEquals(TokenID expectedID, String expectedSource, Token actual) {
Assert.assertEquals("Expected ID didn't match actual ID", expectedID, actual.getID());
Assert.assertEquals("Expected source didn't match actual source", expectedSource, actual.getSource());
}
}
| mit |
InnovateUKGitHub/innovation-funding-service | common/ifs-commons/src/test/java/org/innovateuk/ifs/util/MapFunctionsTest.java | 4041 | package org.innovateuk.ifs.util;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap;
import static org.innovateuk.ifs.util.MapFunctions.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests around helper utilities related to Maps
*/
public class MapFunctionsTest {
@Test
public void testAsMap() {
Map<Long, String> map = asMap(1L, "String 1", 2L, "String 2");
assertEquals(2, map.size());
assertTrue(map.containsKey(1L));
assertTrue(map.containsKey(2L));
assertEquals("String 1", map.get(1L));
assertEquals("String 2", map.get(2L));
}
@Test(expected = IllegalArgumentException.class)
public void testAsMapWithUnevenNamesAndValues() {
asMap(1L, "String 1", 2L);
}
@Test
public void testAsMapEmptyNameValuePairs() {
Map<Long, String> map = asMap();
assertTrue(map.isEmpty());
}
@Test
public void testGetSortedGroupingCounts() {
List<SortGroupTest> groupable = simpleMap(asList("string 1", "string 1", "string 2", "string 2", "string 2", "string 2", "string 3"), SortGroupTest::new);
Map<String, Integer> groupedCountedAndSorted = MapFunctions.getSortedGroupingCounts(groupable, SortGroupTest::getValue);
assertEquals(3, groupedCountedAndSorted.size());
assertEquals(Integer.valueOf(4), groupedCountedAndSorted.get("string 2"));
assertEquals(Integer.valueOf(2), groupedCountedAndSorted.get("string 1"));
assertEquals(Integer.valueOf(1), groupedCountedAndSorted.get("string 3"));
}
@Test
public void testGetSortedGroupingCountsNullSafe() {
Map<String, Integer> groupedCountedAndSorted = MapFunctions.getSortedGroupingCounts(null, SortGroupTest::getValue);
assertEquals(0, groupedCountedAndSorted.size());
}
@Test
public void testCombineMaps() {
Map<Long, String> map1 = asMap(1L, "1", 2L, "2");
Map<Long, String> map2 = asMap(3L, "3");
assertEquals(asMap(1L, "1", 2L, "2", 3L, "3"), combineMaps(map1, map2));
}
@Test
public void testCombineMapsWithDuplicateKeys() {
Map<Long, String> map1 = asMap(1L, "1", 2L, "2");
Map<Long, String> map2 = asMap(2L, "overridden", 3L, "3");
assertEquals(asMap(1L, "1", 2L, "overridden", 3L, "3"), combineMaps(map1, map2));
}
@Test
public void testCombineMapsNullSafe() {
assertEquals(emptyMap(), combineMaps(null, null));
assertEquals(asMap(1L, "1"), combineMaps(asMap(1L, "1"), null));
assertEquals(asMap(1L, "1"), combineMaps(null, asMap(1L, "1")));
}
@Test
public void testSimplePartition() {
Map<Long, String> map1 = asMap(1L, "1", 2L, "2", 3L, "3");
Pair<Map<Long, String>, Map<Long, String>> result = simplePartition(map1, longStringEntry -> longStringEntry.getKey().equals(2L));
assertEquals(asMap(2L, "2"), result.getLeft());
assertEquals(asMap(1L, "1", 3L, "3"), result.getRight());
Pair<Map<Long, String>, Map<Long, String>> result2 = simplePartition(map1, longStringEntry -> longStringEntry.getValue().equals("3"));
assertEquals(asMap(3L, "3"), result2.getLeft());
assertEquals(asMap(1L, "1", 2L, "2"), result2.getRight());
Pair<Map<Long, String>, Map<Long, String>> result3 = simplePartition(map1, longStringEntry -> longStringEntry.getValue().equals("4"));
assertEquals(emptyMap(), result3.getLeft());
assertEquals(asMap(1L, "1", 2L, "2", 3L, "3"), result3.getRight());
}
private class SortGroupTest {
private String value;
private SortGroupTest(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
| mit |