repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
datasift/datasift-java | src/test/java/com/datasift/client/mock/datasift/MockODPApi.java | 886 | package com.datasift.client.mock.datasift;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashMap;
import java.util.Map;
@Path("/")
public class MockODPApi {
Map<String, String> headers = new HashMap<>();
private long accepted;
private long totalMessageBytes;
@POST
@Path("testsource")
public Map<String, Object> batch() {
Map<String, Object> map = new HashMap<>();
map.put("accepted", accepted);
map.put("total_message_bytes", totalMessageBytes);
return map;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public void setAccepted(long accepted) {
this.accepted = accepted;
}
public void setTotalMessageBytes(long totalMessageBytes) {
this.totalMessageBytes = totalMessageBytes;
}
}
| mit |
xieweiAlex/Leetcode_solutions | June/week1/LinkedListReverse2nd.java | 1719 | package June.week1;
/**
* Created by Alex_Xie on 03/06/2017.
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
https://leetcode.com/problems/reverse-linked-list-ii/#/description
*/
public class LinkedListReverse2nd {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode reverseBetween1(ListNode head, int m, int n) {
if (head == null) return null;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
ListNode start = pre.next;
ListNode then = start.next;
while (head != null) {
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
ListNode start = pre.next;
ListNode then = start.next;
for (int i = 0; i < n - m; i++) {
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}
}
| mit |
AbigailBuccaneer/intellij-avro | src/main/java/claims/bold/intellij/avro/idl/lexer/AvroIdlLexer.java | 210 | package claims.bold.intellij.avro.idl.lexer;
import com.intellij.lexer.FlexAdapter;
public class AvroIdlLexer extends FlexAdapter {
public AvroIdlLexer() {
super(new _AvroIdlLexer(null));
}
}
| mit |
evdubs/XChange | xchange-gateio/src/test/java/org/knowm/xchange/gateio/dto/trade/GateioTradeJsonTest.java | 3039 | package org.knowm.xchange.gateio.dto.trade;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.gateio.dto.GateioOrderType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class GateioTradeJsonTest {
@Test
public void testDeserializeOrderList() throws IOException {
// Read in the JSON from the example resources
InputStream is = GateioTradeJsonTest.class.getResourceAsStream("/trade/example-order-list-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
GateioOpenOrders openOrders = mapper.readValue(is, GateioOpenOrders.class);
assertThat(openOrders.isResult()).isTrue();
assertThat(openOrders.getMessage()).isEqualTo("Success");
List<GateioOpenOrder> openOrderList = openOrders.getOrders();
Assertions.assertThat(openOrderList).hasSize(2);
GateioOpenOrder openOrder = openOrderList.get(0);
assertThat(openOrder.getId()).isEqualTo("3");
assertThat(openOrder.getCurrencyPair().split("_")[0]).isEqualTo("eth");
assertThat(openOrder.getCurrencyPair().split("_")[1]).isEqualTo("btc");
assertThat(openOrder.getAmount()).isEqualTo(new BigDecimal("100000"));
}
@Test
public void testDeserializeOrderResult() throws IOException {
// Read in the JSON from the example resources
InputStream is = GateioTradeJsonTest.class.getResourceAsStream("/trade/example-order-result-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
GateioPlaceOrderReturn orderReturn = mapper.readValue(is, GateioPlaceOrderReturn.class);
assertThat(orderReturn.isResult()).isTrue();
assertThat(orderReturn.getMessage()).isEqualTo("Success");
assertThat(orderReturn.getOrderId()).isEqualTo("123456");
}
@Test
public void testDeserializeOrderStatus() throws IOException {
// Read in the JSON from the example resources
InputStream is = GateioTradeJsonTest.class.getResourceAsStream("/trade/example-order-status-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
GateioOrderStatus orderStatus = mapper.readValue(is, GateioOrderStatus.class);
assertThat(orderStatus.isResult()).isTrue();
assertThat(orderStatus.getMessage()).isEqualTo("Success");
assertThat(orderStatus.getId()).isEqualTo("12942570");
assertThat(orderStatus.getStatus()).isEqualTo("open");
assertThat(orderStatus.getCurrencyPair()).isEqualTo(CurrencyPair.LTC_BTC);
assertThat(orderStatus.getType()).isEqualTo(GateioOrderType.SELL);
assertThat(orderStatus.getRate()).isEqualTo("0.0265");
assertThat(orderStatus.getAmount()).isEqualTo("0.384");
assertThat(orderStatus.getInitialRate()).isEqualTo("0.0265");
assertThat(orderStatus.getInitialAmount()).isEqualTo("0.384");
}
}
| mit |
baloomba/WSVolley | src/main/java/fr/baloomba/wsvolley/WSResponseListener.java | 432 | package fr.baloomba.wsvolley;
import com.android.volley.NetworkResponse;
import com.android.volley.VolleyError;
public interface WSResponseListener<T> {
public T parseResponse(NetworkResponse networkResponse);
public void onResponse(T response);
public void onErrorResponse(VolleyError error);
public void onDownloadProgress(long current, long total);
public void onUploadProgress(long current, long total);
}
| mit |
XHao/server | src/main/java/io/xhao/server/http/NioServer.java | 3374 | package io.xhao.server.http;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import io.xhao.server.config.ServerConfig;
import lombok.RequiredArgsConstructor;
public class NioServer {
@SuppressWarnings("unused")
public void main(ServerConfig config) {
ExecutorService execPool = null;
ExecutorService ioPool = null;
ServerSocketChannel server = null;
try {
Selector selector = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new InetSocketAddress(config.getPort()));
server.register(selector, SelectionKey.OP_ACCEPT);
ioPool = new ThreadPoolExecutor(config.getIoThreads(), config.getIoThreads(), 0L, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(config.getQueue()));
execPool = new ThreadPoolExecutor(config.getCoreThreadSize(), config.getMaxThreadSize(), 0L,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(config.getQueue()));
// main thread
new Acceptor(selector, ioPool, execPool).run();
} catch (IOException e) {
System.err.println(e.getMessage());
if (server != null) {
try {
server.close();
} catch (IOException e1) {
System.err.println(e1.getMessage());
}
}
if (ioPool != null) {
ioPool.shutdown();
}
if (execPool != null) {
execPool.shutdown();
}
// 等待资源回收
try {
Thread.sleep(5000L);
} catch (InterruptedException ee) {
}
System.exit(0);
}
}
@RequiredArgsConstructor
private static class Acceptor implements Runnable {
private final Selector selector;
private final ExecutorService io;
private final ExecutorService exec;
@Override
public void run() {
while (true) {
try {
// Wait for an event
int readys = selector.select();
if (readys == 0)
continue;
// Get list of selection keys with pending events
Set<SelectionKey> selected = selector.selectedKeys();
Iterator<SelectionKey> it = selected.iterator();
while (it.hasNext()) {
SelectionKey selKey = it.next();
if (!selKey.isValid())
continue;
if (selKey.isReadable()) {
selKey.interestOps(0);
io.execute(new NioReadHandler(selKey, exec));
} else if (selKey.isAcceptable()) {
SocketChannel channel = ((ServerSocketChannel) selKey.channel()).accept();
if (channel != null) {
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ, new HashMap<String, Object>());
channel.socket().setTcpNoDelay(true);
channel.socket().setSoLinger(false, 0);
channel.socket().setKeepAlive(true);
} else {
System.err.println("No Connection");
}
} else if (selKey.isWritable()) {
selKey.interestOps(0);
io.execute(new NioWriteHandler(selKey));
}
}
selected.clear();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
} | mit |
rwaldron/es6draft | src/main/java/com/github/anba/es6draft/regexp/CaseFoldData.java | 12695 | /**
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.regexp;
/**
* Additional case fold support class
*/
final class CaseFoldData {
private CaseFoldData() {
}
/**
* Is {@code codePoint} a code point which is applicable for case folding
*/
public static boolean caseFoldType(int codePoint) {
switch (Character.getType(codePoint)) {
case Character.UPPERCASE_LETTER:
case Character.LOWERCASE_LETTER:
case Character.TITLECASE_LETTER:
case Character.NON_SPACING_MARK:
case Character.LETTER_NUMBER:
case Character.OTHER_SYMBOL:
return true;
default:
return false;
}
}
/**
* Tests whether or not the case fold is applicable for non-unicode case fold per [21.2.2.8.2]
*/
public static final boolean isValidCaseFold(int codePoint, int toUpper, int toLower) {
// 21.2.2.8.2: Canonicalize Abstract Operation
// Conditions:
// - simple or common case folding mapping available: toUpper != toLower
// - exclude case folding from non-ASCII to ASCII: codePoint <= 0x7f || toUpper > 0x7f
// - restrict case folding to basic plane: toUpper <= 0xffff
return toUpper != toLower && (codePoint <= 0x7f || toUpper > 0x7f) && toUpper <= 0xffff;
}
/**
* Returns {@code true} if {@code ToUpper(codePoint) == ToUpper(ToLower(codePoint))}
*/
public static boolean isValidToLower(int codePoint) {
switch (codePoint) {
case 0x0130:
case 0x03f4:
case 0x1e9e:
case 0x2126:
case 0x212a:
case 0x212b:
return false;
default:
return true;
}
}
/*
* !Generated method!
*/
public static final int caseFold1(int codePoint) {
switch (codePoint) {
case 0x00b5:
return 0x03bc;
case 0x01c4:
case 0x01c6:
return 0x01c5;
case 0x01c7:
case 0x01c9:
return 0x01c8;
case 0x01ca:
case 0x01cc:
return 0x01cb;
case 0x01f1:
case 0x01f3:
return 0x01f2;
case 0x0345:
return 0x03b9;
case 0x0392:
case 0x03b2:
return 0x03d0;
case 0x0395:
case 0x03b5:
return 0x03f5;
case 0x0398:
case 0x03b8:
return 0x03d1;
case 0x0399:
case 0x03b9:
case 0x1fbe:
return 0x0345;
case 0x039a:
case 0x03ba:
return 0x03f0;
case 0x039c:
case 0x03bc:
return 0x00b5;
case 0x03a0:
case 0x03c0:
return 0x03d6;
case 0x03a1:
case 0x03c1:
return 0x03f1;
case 0x03a3:
case 0x03c3:
return 0x03c2;
case 0x03a6:
case 0x03c6:
return 0x03d5;
case 0x03c2:
return 0x03c3;
case 0x03d0:
return 0x03b2;
case 0x03d1:
return 0x03b8;
case 0x03d5:
return 0x03c6;
case 0x03d6:
return 0x03c0;
case 0x03f0:
return 0x03ba;
case 0x03f1:
return 0x03c1;
case 0x03f5:
return 0x03b5;
case 0x1e60:
case 0x1e61:
return 0x1e9b;
case 0x1e9b:
return 0x1e61;
default:
return -1;
}
}
/*
* !Generated method!
*/
public static final int caseFold2(int codePoint) {
switch (codePoint) {
case 0x0345:
case 0x0399:
case 0x03b9:
return 0x1fbe;
case 0x1fbe:
return 0x03b9;
default:
return -1;
}
}
public static final boolean hasAdditionalUnicodeCaseFold(int codePoint) {
// special case for sharp-s, `/\xdf/ui.test("\u1e9e")` does not work in Java out-of-the-box,
// also see CaseFoldDataGenerator#findSpecialUnicodeCaseFold()
return codePoint == 0x00df;
}
public static final void appendCaseInsensitiveUnicode(RegExpParser parser, int codePoint) {
assert hasAdditionalUnicodeCaseFold(codePoint);
parser.appendCharacter(0x00df);
parser.appendCharacter(0x1e9e);
}
/*
* !Generated method!
*/
public static final void appendCaseInsensitiveUnicodeRange(RegExpParser parser, int startChar,
int endChar) {
// Type 1
if (startChar <= 0x00b5
&& 0x00b5 <= endChar
&& !((startChar <= 0x039c && 0x039c <= endChar) || (startChar <= 0x03bc && 0x03bc <= endChar))) {
parser.appendCharacter(0x039c);
parser.appendCharacter(0x03bc);
}
if (startChar <= 0x0131
&& 0x0131 <= endChar
&& !((startChar <= 0x0049 && 0x0049 <= endChar) || (startChar <= 0x0069 && 0x0069 <= endChar))) {
parser.appendCharacter(0x0049);
parser.appendCharacter(0x0069);
}
if (startChar <= 0x017f
&& 0x017f <= endChar
&& !((startChar <= 0x0053 && 0x0053 <= endChar) || (startChar <= 0x0073 && 0x0073 <= endChar))) {
parser.appendCharacter(0x0053);
parser.appendCharacter(0x0073);
}
if (startChar <= 0x01c5
&& 0x01c5 <= endChar
&& !((startChar <= 0x01c4 && 0x01c4 <= endChar) || (startChar <= 0x01c6 && 0x01c6 <= endChar))) {
parser.appendCharacter(0x01c4);
parser.appendCharacter(0x01c6);
}
if (startChar <= 0x01c8
&& 0x01c8 <= endChar
&& !((startChar <= 0x01c7 && 0x01c7 <= endChar) || (startChar <= 0x01c9 && 0x01c9 <= endChar))) {
parser.appendCharacter(0x01c7);
parser.appendCharacter(0x01c9);
}
if (startChar <= 0x01cb
&& 0x01cb <= endChar
&& !((startChar <= 0x01ca && 0x01ca <= endChar) || (startChar <= 0x01cc && 0x01cc <= endChar))) {
parser.appendCharacter(0x01ca);
parser.appendCharacter(0x01cc);
}
if (startChar <= 0x01f2
&& 0x01f2 <= endChar
&& !((startChar <= 0x01f1 && 0x01f1 <= endChar) || (startChar <= 0x01f3 && 0x01f3 <= endChar))) {
parser.appendCharacter(0x01f1);
parser.appendCharacter(0x01f3);
}
if (startChar <= 0x0345
&& 0x0345 <= endChar
&& !((startChar <= 0x0399 && 0x0399 <= endChar) || (startChar <= 0x03b9 && 0x03b9 <= endChar))) {
parser.appendCharacter(0x0399);
parser.appendCharacter(0x03b9);
}
if (startChar <= 0x03c2
&& 0x03c2 <= endChar
&& !((startChar <= 0x03a3 && 0x03a3 <= endChar) || (startChar <= 0x03c3 && 0x03c3 <= endChar))) {
parser.appendCharacter(0x03a3);
parser.appendCharacter(0x03c3);
}
if (startChar <= 0x03d0
&& 0x03d0 <= endChar
&& !((startChar <= 0x0392 && 0x0392 <= endChar) || (startChar <= 0x03b2 && 0x03b2 <= endChar))) {
parser.appendCharacter(0x0392);
parser.appendCharacter(0x03b2);
}
if (startChar <= 0x03d1
&& 0x03d1 <= endChar
&& !((startChar <= 0x0398 && 0x0398 <= endChar) || (startChar <= 0x03b8 && 0x03b8 <= endChar))) {
parser.appendCharacter(0x0398);
parser.appendCharacter(0x03b8);
}
if (startChar <= 0x03d5
&& 0x03d5 <= endChar
&& !((startChar <= 0x03a6 && 0x03a6 <= endChar) || (startChar <= 0x03c6 && 0x03c6 <= endChar))) {
parser.appendCharacter(0x03a6);
parser.appendCharacter(0x03c6);
}
if (startChar <= 0x03d6
&& 0x03d6 <= endChar
&& !((startChar <= 0x03a0 && 0x03a0 <= endChar) || (startChar <= 0x03c0 && 0x03c0 <= endChar))) {
parser.appendCharacter(0x03a0);
parser.appendCharacter(0x03c0);
}
if (startChar <= 0x03f0
&& 0x03f0 <= endChar
&& !((startChar <= 0x039a && 0x039a <= endChar) || (startChar <= 0x03ba && 0x03ba <= endChar))) {
parser.appendCharacter(0x039a);
parser.appendCharacter(0x03ba);
}
if (startChar <= 0x03f1
&& 0x03f1 <= endChar
&& !((startChar <= 0x03a1 && 0x03a1 <= endChar) || (startChar <= 0x03c1 && 0x03c1 <= endChar))) {
parser.appendCharacter(0x03a1);
parser.appendCharacter(0x03c1);
}
if (startChar <= 0x03f5
&& 0x03f5 <= endChar
&& !((startChar <= 0x0395 && 0x0395 <= endChar) || (startChar <= 0x03b5 && 0x03b5 <= endChar))) {
parser.appendCharacter(0x0395);
parser.appendCharacter(0x03b5);
}
if (startChar <= 0x1e9b
&& 0x1e9b <= endChar
&& !((startChar <= 0x1e60 && 0x1e60 <= endChar) || (startChar <= 0x1e61 && 0x1e61 <= endChar))) {
parser.appendCharacter(0x1e60);
parser.appendCharacter(0x1e61);
}
if (startChar <= 0x1fbe
&& 0x1fbe <= endChar
&& !((startChar <= 0x0399 && 0x0399 <= endChar) || (startChar <= 0x03b9 && 0x03b9 <= endChar))) {
parser.appendCharacter(0x0399);
parser.appendCharacter(0x03b9);
}
// Type 2
if (startChar <= 0x0130
&& 0x0130 <= endChar
&& !((startChar <= 0x0049 && 0x0049 <= endChar) || (startChar <= 0x0069 && 0x0069 <= endChar))) {
parser.appendCharacter(0x0049);
parser.appendCharacter(0x0069);
}
if (startChar <= 0x0049
&& 0x0049 <= endChar
&& !((startChar <= 0x0130 && 0x0130 <= endChar) || (startChar <= 0x0069 && 0x0069 <= endChar))) {
parser.appendCharacter(0x0130);
}
if (startChar <= 0x03f4
&& 0x03f4 <= endChar
&& !((startChar <= 0x0398 && 0x0398 <= endChar) || (startChar <= 0x03b8 && 0x03b8 <= endChar))) {
parser.appendCharacter(0x0398);
parser.appendCharacter(0x03b8);
}
if (startChar <= 0x0398
&& 0x0398 <= endChar
&& !((startChar <= 0x03f4 && 0x03f4 <= endChar) || (startChar <= 0x03b8 && 0x03b8 <= endChar))) {
parser.appendCharacter(0x03f4);
}
if (startChar <= 0x2126
&& 0x2126 <= endChar
&& !((startChar <= 0x03a9 && 0x03a9 <= endChar) || (startChar <= 0x03c9 && 0x03c9 <= endChar))) {
parser.appendCharacter(0x03a9);
parser.appendCharacter(0x03c9);
}
if (startChar <= 0x03a9
&& 0x03a9 <= endChar
&& !((startChar <= 0x2126 && 0x2126 <= endChar) || (startChar <= 0x03c9 && 0x03c9 <= endChar))) {
parser.appendCharacter(0x2126);
}
if (startChar <= 0x212a
&& 0x212a <= endChar
&& !((startChar <= 0x004b && 0x004b <= endChar) || (startChar <= 0x006b && 0x006b <= endChar))) {
parser.appendCharacter(0x004b);
parser.appendCharacter(0x006b);
}
if (startChar <= 0x004b
&& 0x004b <= endChar
&& !((startChar <= 0x212a && 0x212a <= endChar) || (startChar <= 0x006b && 0x006b <= endChar))) {
parser.appendCharacter(0x212a);
}
if (startChar <= 0x212b
&& 0x212b <= endChar
&& !((startChar <= 0x00c5 && 0x00c5 <= endChar) || (startChar <= 0x00e5 && 0x00e5 <= endChar))) {
parser.appendCharacter(0x00c5);
parser.appendCharacter(0x00e5);
}
if (startChar <= 0x00c5
&& 0x00c5 <= endChar
&& !((startChar <= 0x212b && 0x212b <= endChar) || (startChar <= 0x00e5 && 0x00e5 <= endChar))) {
parser.appendCharacter(0x212b);
}
// Type 3
if (startChar <= 0x1e9e && 0x1e9e <= endChar && !(startChar <= 0x00df && 0x00df <= endChar)) {
parser.appendCharacter(0x00df);
}
if (startChar <= 0x00df && 0x00df <= endChar && !(startChar <= 0x1e9e && 0x1e9e <= endChar)) {
parser.appendCharacter(0x1e9e);
}
}
}
| mit |
ysaak/leekwars | src/main/java/ysaak/leekwars/cmdline/dao/TournamentDao.java | 815 | package ysaak.leekwars.cmdline.dao;
import com.fasterxml.jackson.core.type.TypeReference;
import ysaak.leekwars.cmdline.data.tournament.Tournament;
import ysaak.leekwars.cmdline.exception.RequestFailedException;
import ysaak.leekwars.cmdline.rest.GenericResponse;
import ysaak.leekwars.cmdline.rest.RestClient;
import java.util.HashMap;
import java.util.Map;
/**
* Leek API
*/
public final class TournamentDao {
private TournamentDao() {}
public static Tournament get(String tournamentId) throws RequestFailedException {
final Map<String, String> parameters = new HashMap<>();
parameters.put("tournament_id", tournamentId);
return RestClient.getInstance().get("tournament/get/{tournament_id}/{token}", parameters, new TypeReference<GenericResponse<Tournament>>() {});
}
}
| mit |
jklingsporn/vertx-jooq | vertx-jooq-generate/src/test/java/generated/rx/reactive/guice/tables/daos/SomethingwithoutjsonDao.java | 3168 | /*
* This file is generated by jOOQ.
*/
package generated.rx.reactive.guice.tables.daos;
import generated.rx.reactive.guice.tables.Somethingwithoutjson;
import generated.rx.reactive.guice.tables.records.SomethingwithoutjsonRecord;
import io.github.jklingsporn.vertx.jooq.shared.reactive.AbstractReactiveVertxDAO;
import java.util.Collection;
import org.jooq.Configuration;
import java.util.List;
import io.reactivex.Single;
import java.util.Optional;
import io.github.jklingsporn.vertx.jooq.rx.reactivepg.ReactiveRXQueryExecutor;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
@javax.inject.Singleton
public class SomethingwithoutjsonDao extends AbstractReactiveVertxDAO<SomethingwithoutjsonRecord, generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson, Integer, Single<List<generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson>>, Single<Optional<generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson>>, Single<Integer>, Single<Integer>> implements io.github.jklingsporn.vertx.jooq.rx.VertxDAO<SomethingwithoutjsonRecord,generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson,Integer> {
@javax.inject.Inject
/**
* @param configuration The Configuration used for rendering and query
* execution.
* @param vertx the vertx instance
*/
public SomethingwithoutjsonDao(Configuration configuration, io.vertx.reactivex.sqlclient.SqlClient delegate) {
super(Somethingwithoutjson.SOMETHINGWITHOUTJSON, generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson.class, new ReactiveRXQueryExecutor<SomethingwithoutjsonRecord,generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson,Integer>(configuration,delegate,generated.rx.reactive.guice.tables.mappers.RowMappers.getSomethingwithoutjsonMapper()));
}
@Override
protected Integer getId(generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson object) {
return object.getSomeid();
}
/**
* Find records that have <code>someString IN (values)</code> asynchronously
*/
public Single<List<generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson>> findManyBySomestring(Collection<String> values) {
return findManyByCondition(Somethingwithoutjson.SOMETHINGWITHOUTJSON.SOMESTRING.in(values));
}
/**
* Find records that have <code>someString IN (values)</code> asynchronously
* limited by the given limit
*/
public Single<List<generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson>> findManyBySomestring(Collection<String> values, int limit) {
return findManyByCondition(Somethingwithoutjson.SOMETHINGWITHOUTJSON.SOMESTRING.in(values),limit);
}
@Override
public ReactiveRXQueryExecutor<SomethingwithoutjsonRecord,generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson,Integer> queryExecutor(){
return (ReactiveRXQueryExecutor<SomethingwithoutjsonRecord,generated.rx.reactive.guice.tables.pojos.Somethingwithoutjson,Integer>) super.queryExecutor();
}
}
| mit |
phenelle/AnnonceAPI | lib/src/test/java/com/cubitux/controller/UserCtrlTest.java | 4208 | package com.cubitux.controller;
import com.cubitux.model.Role;
import com.cubitux.model.User;
import com.cubitux.model.exception.AccountNotActivatedException;
import com.cubitux.model.exception.LoginInUseException;
import com.cubitux.model.exception.LoginOrPasswordException;
import com.cubitux.utils.DateUtil;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
/**
* This class will test the User Controller
*
* @created by pierre on 2016-05-13.
*/
public class UserCtrlTest extends TestCase {
/**
* Object that is tested
*/
private UserCtrl controller = new UserCtrl();
/**
* Required to test the controller
*/
private User admin = new User();
private User user = new User();
@Before
public void setUp() {
// Create a new Annonce and populate fields
System.out.println("@Before - setUp");
admin.setLogin("admin@localhost");
admin.setPassword("12345");
user.setLogin("user1");
user.setPassword("123");
}
@Test
public void testLogout() throws Exception {
System.out.println("@Test - testAuthenticate");
// Verify authenticate method
admin = UserCtrl.authenticate(admin.getLogin(), admin.getPassword());
assertTrue("admin not logged", admin.isLogged());
assertNotNull("admin has no session", admin.getSession());
// Store session
String session = admin.getSession();
// Force logout
admin = UserCtrl.logout(session);
assertFalse("admin is still logged", admin.isLogged());
assertNull("admin still have session", admin.getSession());
// Verify session have been removed
admin = UserCtrl.isAuthenticate(session);
assertFalse("admin session is still active", admin.isLogged());
}
@Test
public void testCheckEmail() throws Exception {
try {
UserCtrl.checkEmailAvailable("admin@localhost");
} catch (Exception e) {
assertSame("Wrong exception was thrown", e.getClass(), LoginInUseException.class);
}
UserCtrl.checkEmailAvailable("toto@localhost");
}
@Test
public void testAuthenticate() throws Exception {
System.out.println("@Test - testAuthenticate");
// Verify authenticate method
admin = UserCtrl.authenticate(admin.getLogin(), admin.getPassword());
assertTrue("admin not logged", admin.isLogged());
assertNotNull("admin has no session", admin.getSession());
assertEquals("firstname is incorrect", "Mr", admin.getFirstName());
assertEquals("lastname is incorrect", "Admin", admin.getLastName());
assertEquals("email is incorrect", "admin@localhost", admin.getEmail());
assertEquals("address is incorrect", "1 rue du petit chemin", admin.getAddress());
assertEquals("creation date is incorrect", DateUtil.dateToString(admin.getCreated()), "2016-06-16 10:44:57");
assertEquals("city is incorrect", admin.getCity(), "Paris");
assertEquals("country is incorrect", admin.getCountry(), "France");
assertEquals("role is incorrect", admin.getRole(), Role.Administrator);
try {
user = UserCtrl.authenticate(user.getLogin(), user.getPassword());
} catch (Exception e) {
assertSame("Wrong exception was thrown", e.getClass(), AccountNotActivatedException.class);
}
// Verify isAuthenticate method
String session = admin.getSession();
admin = UserCtrl.isAuthenticate(session);
assertTrue("user should be authenticate with this session id", admin.isLogged());
// Verify user is not auth if password is incorrect
try {
String login = admin.getLogin();
String password = "567";
admin = new User();
admin = UserCtrl.authenticate(login, password);
} catch (Exception e) {
assertSame("Wrong exception was thrown", e.getClass(), LoginOrPasswordException.class);
}
assertNull("session is not empty", admin.getSession());
assertFalse("user is logged...", admin.isLogged());
}
}
| mit |
andyjko/whyline | edu/cmu/hcii/whyline/bytecode/IF_ICMPLT.java | 366 | package edu.cmu.hcii.whyline.bytecode;
/**
* @author Andrew J. Ko
*
*/
public final class IF_ICMPLT extends CompareIntegersBranch {
public IF_ICMPLT(CodeAttribute method, int offset) {
super(method, offset);
}
public final int getOpcode() { return 161; }
public int byteLength() { return 3; }
public String getReadableDescription() { return "<"; }
}
| mit |
alexxstst/JSocketServer | src/main/java/com/alexxst/socketserver/protocol/impl/JsonMessage.java | 204 | package com.alexxst.socketserver.protocol.impl;
import com.alexxst.socketserver.protocol.RawSocketCommand;
/**
* Created by alexxst.st on 03.04.2017.
*/
class JsonMessage extends RawSocketCommand {
}
| mit |
iMartinezMateu/gamecraft | gamecraft-gateway/src/test/java/com/gamecraft/cucumber/stepdefs/StepDefs.java | 504 | package com.gamecraft.cucumber.stepdefs;
import com.gamecraft.GamecraftgatewayApp;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.boot.test.context.SpringBootTest;
@WebAppConfiguration
@SpringBootTest
@ContextConfiguration(classes = GamecraftgatewayApp.class)
public abstract class StepDefs {
protected ResultActions actions;
}
| mit |
OptimalPayments/Java_SDK | NetBanxSDK/src/main/java/com/optimalpayments/common/Locale.java | 1469 | /*
* Copyright (c) 2014 Optimal Payments
*
* 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.optimalpayments.common;
import com.google.gson.annotations.SerializedName;
// TODO: Auto-generated Javadoc
/**
* Used by ShippingDetails.
*/
public enum Locale {
/** The en us. */
@SerializedName("en_US")
EN_US,
/** The en gb. */
@SerializedName("en_GB")
EN_GB,
/** The fr ca. */
@SerializedName("fr_CA")
FR_CA
}
| mit |
ligoj/plugin-prov | src/main/java/org/ligoj/app/plugin/prov/NetworkVo.java | 542 | /*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.app.plugin.prov;
import javax.validation.constraints.NotNull;
import org.ligoj.app.plugin.prov.model.ResourceType;
import lombok.Getter;
import lombok.Setter;
/**
*
* Network object for edition.
*/
@Getter
@Setter
public class NetworkVo extends AbstractNetworkVo {
/**
* The related peer resource identifier.
*/
@NotNull
private Integer peer;
/**
* The peer resource type.
*/
@NotNull
private ResourceType peerType;
}
| mit |
BitLimit/Tweaks | src/main/java/com/bitlimit/Tweaks/TweaksCommandExecutor.java | 6881 | package com.bitlimit.Tweaks;
import org.bukkit.ChatColor;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.command.*;
import org.bukkit.configuration.file.FileConfiguration;
public class TweaksCommandExecutor implements CommandExecutor {
private final Tweaks plugin;
public TweaksCommandExecutor(Tweaks plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
/* /tweaks tnt enable
/tweaks tnt disable
/tweaks weather enable
/tweaks weather disable
/tweaks slimes enable
/tweaks slimes disable
*/
if (sender.hasPermission("tweaks.*")) {
FileConfiguration config = this.plugin.getConfig();
if (args.length > 1) {
boolean validParameter = isValidBooleanInput(args[1]);
if (!validParameter && !args[1].toLowerCase().equals("location")) {
sender.sendMessage(ChatColor.RED + "Invalid second parameter: expected *able and its past participle, or standard YES/NO (capitalization agnostic).");
return false;
}
boolean newValue = parsedBooleanInput(args[1]);
String modified = args[0].toLowerCase();
if (modified.equals("tnt") || modified.equals("weather") || modified.equals("slimes"))
{
config.getConfigurationSection(modified).set("enabled", newValue);
}
else if (args[0].toLowerCase().equals("spawnitems"))
{
if (args[1].toLowerCase().equals("location")) {
try {
ConfigurationSection section = null;
ConfigurationSection spawnItemsSection = config.getConfigurationSection("spawnItems");
if (spawnItemsSection.contains("location"))
{
section = spawnItemsSection.getConfigurationSection("location");
}
else
{
section = spawnItemsSection.createSection("location");
}
if (sender instanceof Player)
{
Player player = (Player)sender;
this.putLocationInSection(player.getLocation(), section);
sender.sendMessage(ChatColor.GREEN + "Location set successfully.");
} else {
sender.sendMessage(ChatColor.RED + "Sender must be player.");
}
return true;
} catch (Exception e) {
}
} else {
config.getConfigurationSection("spawnItems").set("enabled", newValue);
}
} else {
sender.sendMessage(ChatColor.RED + "Invalid parameter. Expected TNT, weather, or slimes.");
return false;
}
String argument = args[0];
if (argument.equals("tnt")) {
argument = "TNT";
} else {
argument = capitalizedString(argument);
}
String newValueString = newValue ? "enabled" : "disabled";
sender.sendMessage(ChatColor.AQUA + argument + " tweaks are now " + ChatColor.GOLD + newValueString +ChatColor.AQUA + ".");
} else if (args.length == 1) {
String argument = args[0];
if (argument.equals("tnt") || argument.equals("weather") || argument.equals("slimes") || argument.equals("spawnItems"))
{
boolean enabled = config.getConfigurationSection(argument).getBoolean("enabled");
if (argument.equals("tnt")) {
argument = "TNT";
}
else if (argument.equals("spawnItems"))
{
argument = "Item-spawning";
}
else {
argument = capitalizedString(argument);
}
if (enabled) {
sender.sendMessage(ChatColor.AQUA + argument + ChatColor.GREEN + " tweaks are currently enabled.");
} else {
sender.sendMessage(ChatColor.AQUA + argument + ChatColor.RED + " tweaks are currently disabled.");
}
} else {
sender.sendMessage(ChatColor.AQUA + "Valid parameters: TNT, weather, slimes, or spawnItems to query state, optionally, followed by \"enabled\" or \"disabled\" to set.");
}
} else {
sender.sendMessage(ChatColor.AQUA + "Valid parameters: TNT, weather, slimes, or spawnItems to query state, optionally, followed by \"enabled\" or \"disabled\" to set.");
}
// Save
this.plugin.saveConfig();
} else {
sender.sendMessage(ChatColor.RED + "You don't have permission to execute this command.");
}
return false;
}
private boolean isValidBooleanInput(String string) {
return string.equals("enable") || string.equals("enabled") || string.equals("true") || string.equals("YES") || string.equals("yes") || string.equals("disable") || string.equals("disabled") || string.equals("false") || string.equals("NO") || string.equals("no");
}
private boolean parsedBooleanInput(String string) {
if (string.equals("enable") || string.equals("enabled") || string.equals("true") || string.equals("YES") || string.equals("yes")) {
return true;
} else if (string.equals("disable") || string.equals("disabled") || string.equals("false") || string.equals("NO") || string.equals("no")) {
return false;
}
return false;
}
private String capitalizedString(String string)
{
return Character.toUpperCase(string.charAt(0)) + string.substring(1);
}
public void putLocationInSection(Location location, ConfigurationSection configurationSection) {
configurationSection.set("world", location.getWorld().getName());
configurationSection.set("x", location.getX());
configurationSection.set("y", location.getY());
configurationSection.set("z", location.getZ());
configurationSection.set("yaw", location.getYaw());
configurationSection.set("pitch", location.getPitch());
}
}
| mit |
SuperSpyTX/MCLib | src/se/jkrau/mclib/craft/Craft.java | 556 | package se.jkrau.mclib.craft;
/**
* The artisan's blank canvas for injecting code.
* This class is used by the {@link se.jkrau.mclib.loader.Loader} to process classes, to make changes, etc.
*
* @author Joe
*/
public interface Craft {
/**
* The method that processes classes going through the {@link se.jkrau.mclib.loader.Loader}
*
* @param in The bytecode going in.
* @param className The class name going in.
* @return The bytecode with all the modifications.
*/
public abstract byte[] process(byte[] in, String className);
}
| mit |
eballerini/dictionary | src/main/java/org/dictionary/service/DefaultWordSearchService.java | 1638 | package org.dictionary.service;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.dictionary.domain.Word;
import org.dictionary.repository.WordRepositoryCustom;
import org.dictionary.repository.search.WordSearchRepository;
import org.dictionary.util.DictionaryConstants;
import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
@Named
public class DefaultWordSearchService implements WordSearchService {
private final Logger log = LoggerFactory.getLogger(DefaultWordSearchService.class);
@Inject
private WordSearchRepository wordSearchRepository;
@Inject
private WordRepositoryCustom wordRepositoryCustom;
public DefaultWordSearchService() {
}
@Override
@Transactional(readOnly = false)
public void indexWords(long startIndex) {
long id = startIndex;
int numResults = DictionaryConstants.PAGE_SIZE;
while (numResults >= DictionaryConstants.PAGE_SIZE) {
List<Word> words = wordRepositoryCustom.load(id, DictionaryConstants.PAGE_SIZE);
numResults = words.size();
if (!words.isEmpty()) {
// this works but is not efficient - we should try to load the
// tags along with the words
words.stream().forEach(w -> Hibernate.initialize(w.getTags()));
wordSearchRepository.save(words);
id = words.get(numResults - 1).getId() + 1;
log.debug("indexed {} words", numResults);
}
}
}
}
| mit |
NucleusPowered/Nucleus | nucleus-core/src/main/java/io/github/nucleuspowered/nucleus/core/services/impl/timing/DummyTimingsService.java | 745 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.core.services.impl.timing;
import io.github.nucleuspowered.nucleus.core.services.interfaces.ITimingsService;
public final class DummyTimingsService implements ITimingsService {
final static class Holding {
final static ITiming DUMMY = new ITiming() {
@Override
public ITiming start() {
return this;
}
@Override
public void stop() {
}
};
}
@Override
public ITiming of(final String name) {
return Holding.DUMMY;
}
}
| mit |
ieatbedrock/Bedrocks-AE2-addons | src/main/scala/extracells/integration/waila/IWailaTile.java | 348 | package extracells.integration.waila;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.List;
public interface IWailaTile {
public List<String> getWailaBody(List<String> list, NBTTagCompound tag,
ForgeDirection side);
public NBTTagCompound getWailaTag(NBTTagCompound tag);
}
| mit |
teamIndexZero/index_zero_trafficsystem | simulator/src/main/java/kcl/teamIndexZero/traffic/simulator/data/links/JunctionLink.java | 3497 | package kcl.teamIndexZero.traffic.simulator.data.links;
import kcl.teamIndexZero.traffic.log.Logger;
import kcl.teamIndexZero.traffic.log.Logger_Interface;
import kcl.teamIndexZero.traffic.simulator.data.ID;
import kcl.teamIndexZero.traffic.simulator.data.SimulationTick;
import kcl.teamIndexZero.traffic.simulator.data.features.Feature;
import kcl.teamIndexZero.traffic.simulator.data.features.Junction;
import kcl.teamIndexZero.traffic.simulator.data.features.Road;
import kcl.teamIndexZero.traffic.simulator.data.features.TrafficGenerator;
import kcl.teamIndexZero.traffic.simulator.data.geo.GeoPoint;
import kcl.teamIndexZero.traffic.simulator.exceptions.JunctionPathException;
import java.util.ArrayList;
import java.util.List;
/**
* Special Lane level link for Junction enabling access to Junction's behaviour
* Note: use *only* for Junctions!
*/
public class JunctionLink extends Link {
private static Logger_Interface LOG = Logger.getLoggerInstance(JunctionLink.class.getSimpleName());
private Junction junction;
private Feature feature;
public enum LinkType {
OUTFLOW,
INFLOW,
}
private LinkType type;
/**
* Constructor
*
* @param id Link ID tag
* @param road Lane's Road that connected to the link
* @param junction Junction the link belongs to
* @param point Geo point
* @param type Type of junction link
*/
public JunctionLink(ID id, Road road, Junction junction, GeoPoint point, JunctionLink.LinkType type) {
super(id, point);
this.feature = road;
this.junction = junction;
this.type = type;
}
/**
* Constructor
*
* @param id Link ID tag
* @param trafficGenerator Traffic generator that is connected to the link
* @param junction Junction the link belongs to
* @param point Geo point
* @param type Type of junction link
*/
public JunctionLink(ID id, TrafficGenerator trafficGenerator, Junction junction, GeoPoint point, JunctionLink.LinkType type) {
super(id, point);
this.feature = trafficGenerator;
this.junction = junction;
this.type = type;
}
/**
* gets the possible exit links on a junction
*
* @return exit links
*/
public List<Link> getLinks() {
try {
return junction.getNextLinks(super.getID());
} catch (JunctionPathException e) {
LOG.log_Fatal("No exit link from the junction were found! i.e.: Car is stuck!");
return new ArrayList<>();
}
}
/**
* Gets the ID tag of the road the lane belongs to
*
* @return Parent road ID tag
*/
public ID getRoadID() {
return this.feature.getID();
}
/**
* Gets the ID tag of the junction
*
* @return Junction ID tag
*/
public ID getJunctionID() {
return this.junction.getID();
}
/**
* Checks if the link is an outflow link
*
* @return is Outflow state
*/
public boolean isOutflowLink() {
return this.type == LinkType.OUTFLOW;
}
/**
* Checks if the link is an inflow link
*
* @return is Inflow state
*/
public boolean isInflowLink() {
return this.type == LinkType.INFLOW;
}
/**
* {@inheritDoc}
*/
@Override
public void tick(SimulationTick tick) {
super.tick(tick);
}
}
| mit |
jericks/geometrycommands | src/test/java/org/geometrycommands/CountGeometriesCommandTest.java | 1511 | package org.geometrycommands;
import org.geometrycommands.CountGeometriesCommand.CountGeometryOptions;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The CountGeometriesCommand UnitTest
* @author Jared Erickson
*/
public class CountGeometriesCommandTest extends BaseTest {
@Test
public void execute() throws Exception {
String inputGeometry = "MULTIPOINT ((0 0), (0 10), (10 10), (10 0), (0 0))";
CountGeometryOptions options = new CountGeometryOptions();
options.setGeometry(inputGeometry);
Reader reader = new StringReader(inputGeometry);
StringWriter writer = new StringWriter();
CountGeometriesCommand command = new CountGeometriesCommand();
command.execute(options, reader, writer);
assertEquals("5", writer.getBuffer().toString());
}
@Test
public void run() throws Exception {
// Geometry from options
String result = runApp(new String[]{
"count",
"-g", "MULTIPOINT ((0 0), (0 10), (10 10), (10 0), (0 0))"
}, null);
assertEquals(5, Integer.parseInt(result));
// Geometry from input stream
result = runApp(new String[]{
"count"
}, "MULTIPOINT ((0 0), (0 10), (10 10), (10 0), (0 0))");
assertEquals(5, Integer.parseInt(result));
}
}
| mit |
dvt32/cpp-journey | Java/CodeForces/Police Recruits.java | 670 | // http://codeforces.com/problemset/problem/427/A
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int n = read.nextInt();
int numberOfAvailableOfficers = 0;
int numberOfUntreatedCrimes = 0;
for (int i = 0; i < n; ++i) {
int number = read.nextInt();
if (number > 0) {
numberOfAvailableOfficers += number;
}
else {
if (numberOfAvailableOfficers > 0) {
numberOfAvailableOfficers--;
}
else {
numberOfUntreatedCrimes++;
}
}
}
System.out.println( numberOfUntreatedCrimes );
// Close scanner
read.close();
}
}
| mit |
alexyz/sysmips | src/sys/ui/LogsTableModel.java | 2298 | package sys.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import sys.util.Log;
public class LogsTableModel extends AbstractTableModel {
private final List<Log> logs = new ArrayList<>();
private final List<Log> viewlogs = new ArrayList<>();
private String filter;
private boolean conj;
public void addLogs (Log[] a) {
if (logs.size() > 10000) {
logs.subList(0, 1000).clear();
}
// int i = logs.size();
logs.addAll(Arrays.asList(a));
setFilter(filter, conj);
}
public void setFilter (String filter, boolean conj) {
this.filter = filter;
this.conj = conj;
viewlogs.clear();
if (filter != null && filter.length() > 0) {
String[] a = filter.split(" +");
for (Log l : logs) {
boolean x;
if (conj) {
x = true;
for (String t : a) {
if (t.length() > 0 && !(l.msg.contains(t) || l.name.contains(t))) {
x = false;
break;
}
}
} else {
x = false;
for (String t : a) {
if (t.length() > 0 && (l.msg.contains(t) || l.name.contains(t))) {
x = true;
break;
}
}
}
if (x) {
viewlogs.add(l);
}
}
} else {
viewlogs.addAll(logs);
}
fireTableDataChanged();
// fireTableRowsInserted(i, this.logs.size() - 1);
}
@Override
public int getRowCount () {
return viewlogs.size();
}
@Override
public int getColumnCount () {
return 5;
}
@Override
public String getColumnName (int col) {
switch (col) {
case 0:
return "Cycle";
case 1:
return "Mode";
case 2:
return "Name";
case 3:
return "Message";
case 4:
return "Name";
default:
throw new RuntimeException();
}
}
public Log getRow (int row) {
return viewlogs.get(row);
}
@Override
public Object getValueAt (int row, int col) {
Log l = viewlogs.get(row);
switch (col) {
case 0:
return Long.valueOf(l.cycle);
case 1:
return (l.km ? "K" : "") + (l.ie ? "I" : "") + (l.ex ? "X" : "");
case 2:
return l.name;
case 3:
return l.msg;
case 4:
return l.sym;
default:
throw new RuntimeException();
}
}
}
| mit |
cloudbansal/02242 | eclipse_project/src/dk/dtu/imm/pa/analyzer/objects/collections/IntervalAnalysisSet.java | 2498 | package dk.dtu.imm.pa.analyzer.objects.collections;
import java.util.ArrayList;
public class IntervalAnalysisSet extends ArrayList<IntervalAnalysis> {
/**
*
*/
private static final long serialVersionUID = 1L;
public IntervalAnalysisSet(IntervalAnalysisSet ias){
super(ias);
}
public IntervalAnalysisSet(){
super();
}
public boolean contains(IntervalAnalysisSet ias){
boolean result = true;
for(IntervalAnalysis ia : ias){
if(!this.contains(ia)){
result = false;
}
}
return result;
}
public boolean contains(IntervalAnalysis ia){
boolean result = false;
for(IntervalAnalysis ourIa : this){
if(ourIa.contains(ia)){
result = true;
}
}
return result;
}
// public IntervalAnalysisSet addition(IntervalAnalysisSet ias){
// IntervalAnalysisSet newIntervalAnalysisSet = new IntervalAnalysisSet(this);
//
// for (IntervalAnalysis ia : ias){
// this.add(ia);
// }
//
// return newIntervalAnalysisSet;
// }
//
// public IntervalAnalysisSet removal(IntervalAnalysisSet ias){
// IntervalAnalysisSet newIntervalAnalysisSet = new IntervalAnalysisSet(this);
//
// for (IntervalAnalysis ia : ias){
// this.remove(this.getByName(ia.getName()));
// }
//
// return newIntervalAnalysisSet;
// }
public IntervalAnalysisSet addition(IntervalAnalysisSet intervalAnalysisSet){
IntervalAnalysisSet newIntervalAnalysisSet = new IntervalAnalysisSet(this);
for(IntervalAnalysis is : intervalAnalysisSet) {
if(newIntervalAnalysisSet.containsVariableName(is.getName())){
newIntervalAnalysisSet.getByVariableName(is.getName()).add(is);
} else {
newIntervalAnalysisSet.add(is);
}
}
return newIntervalAnalysisSet;
}
public IntervalAnalysisSet removal(IntervalAnalysisSet intervalAnalysisSet){
IntervalAnalysisSet newIntervalAnalysisSet = new IntervalAnalysisSet(this);
for(IntervalAnalysis is : intervalAnalysisSet) {
if(newIntervalAnalysisSet.containsVariableName(is.getName())){
IntervalAnalysis temp = newIntervalAnalysisSet.getByVariableName(is.getName());
temp.substract(is);
}
}
return newIntervalAnalysisSet;
}
public IntervalAnalysis getByVariableName(String name){
for(IntervalAnalysis ia : this){
if(ia.getName().equals(name)){
return ia;
}
}
return null;
}
public boolean containsVariableName(String name){
for(IntervalAnalysis ia : this) {
if(ia.getName().equals(name)){
return true;
}
}
return false;
}
}
| mit |
jstoecker/jgl | src/jgl/shading/Material.java | 436 | /*******************************************************************************
* Copyright (C) 2013 Justin Stoecker. The MIT License.
*******************************************************************************/
package jgl.shading;
import javax.media.opengl.GL;
/**
* Describes surface properties used for shading.
*/
public interface Material {
void enable(GL gl);
void disable(GL gl);
void dispose(GL gl);
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/AzureFirewallFqdnTagsClientImpl.java | 13307 | // 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.implementation;
import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.network.fluent.AzureFirewallFqdnTagsClient;
import com.azure.resourcemanager.network.fluent.models.AzureFirewallFqdnTagInner;
import com.azure.resourcemanager.network.models.AzureFirewallFqdnTagListResult;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in AzureFirewallFqdnTagsClient. */
public final class AzureFirewallFqdnTagsClientImpl implements AzureFirewallFqdnTagsClient {
private final ClientLogger logger = new ClientLogger(AzureFirewallFqdnTagsClientImpl.class);
/** The proxy service used to perform REST calls. */
private final AzureFirewallFqdnTagsService service;
/** The service client containing this operation class. */
private final NetworkManagementClientImpl client;
/**
* Initializes an instance of AzureFirewallFqdnTagsClientImpl.
*
* @param client the instance of the service client containing this operation class.
*/
AzureFirewallFqdnTagsClientImpl(NetworkManagementClientImpl client) {
this.service =
RestProxy
.create(AzureFirewallFqdnTagsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
this.client = client;
}
/**
* The interface defining all the services for NetworkManagementClientAzureFirewallFqdnTags to be used by the proxy
* service to perform REST calls.
*/
@Host("{$host}")
@ServiceInterface(name = "NetworkManagementCli")
private interface AzureFirewallFqdnTagsService {
@Headers({"Content-Type: application/json"})
@Get("/subscriptions/{subscriptionId}/providers/Microsoft.Network/azureFirewallFqdnTags")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<AzureFirewallFqdnTagListResult>> list(
@HostParam("$host") String endpoint,
@QueryParam("api-version") String apiVersion,
@PathParam("subscriptionId") String subscriptionId,
@HeaderParam("Accept") String accept,
Context context);
@Headers({"Content-Type: application/json"})
@Get("{nextLink}")
@ExpectedResponses({200})
@UnexpectedResponseExceptionType(ManagementException.class)
Mono<Response<AzureFirewallFqdnTagListResult>> listAllNext(
@PathParam(value = "nextLink", encoded = true) String nextLink,
@HostParam("$host") String endpoint,
@HeaderParam("Accept") String accept,
Context context);
}
/**
* Gets all the Azure Firewall FQDN Tags in a subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewall FQDN Tags in a subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallFqdnTagInner>> listSinglePageAsync() {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2018-11-01";
final String accept = "application/json";
return FluxUtil
.withContext(
context ->
service
.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), accept, context))
.<PagedResponse<AzureFirewallFqdnTagInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Gets all the Azure Firewall FQDN Tags in a subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewall FQDN Tags in a subscription.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallFqdnTagInner>> listSinglePageAsync(Context context) {
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
if (this.client.getSubscriptionId() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getSubscriptionId() is required and cannot be null."));
}
final String apiVersion = "2018-11-01";
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.list(this.client.getEndpoint(), apiVersion, this.client.getSubscriptionId(), accept, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
/**
* Gets all the Azure Firewall FQDN Tags in a subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewall FQDN Tags in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedFlux<AzureFirewallFqdnTagInner> listAsync() {
return new PagedFlux<>(() -> listSinglePageAsync(), nextLink -> listAllNextSinglePageAsync(nextLink));
}
/**
* Gets all the Azure Firewall FQDN Tags in a subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewall FQDN Tags in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
private PagedFlux<AzureFirewallFqdnTagInner> listAsync(Context context) {
return new PagedFlux<>(
() -> listSinglePageAsync(context), nextLink -> listAllNextSinglePageAsync(nextLink, context));
}
/**
* Gets all the Azure Firewall FQDN Tags in a subscription.
*
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewall FQDN Tags in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<AzureFirewallFqdnTagInner> list() {
return new PagedIterable<>(listAsync());
}
/**
* Gets all the Azure Firewall FQDN Tags in a subscription.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return all the Azure Firewall FQDN Tags in a subscription.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<AzureFirewallFqdnTagInner> list(Context context) {
return new PagedIterable<>(listAsync(context));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewallFqdnTags API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallFqdnTagInner>> listAllNextSinglePageAsync(String nextLink) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
return FluxUtil
.withContext(context -> service.listAllNext(nextLink, this.client.getEndpoint(), accept, context))
.<PagedResponse<AzureFirewallFqdnTagInner>>map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null))
.contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
}
/**
* Get the next page of items.
*
* @param nextLink The nextLink parameter.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response for ListAzureFirewallFqdnTags API service call.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<PagedResponse<AzureFirewallFqdnTagInner>> listAllNextSinglePageAsync(
String nextLink, Context context) {
if (nextLink == null) {
return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null."));
}
if (this.client.getEndpoint() == null) {
return Mono
.error(
new IllegalArgumentException(
"Parameter this.client.getEndpoint() is required and cannot be null."));
}
final String accept = "application/json";
context = this.client.mergeContext(context);
return service
.listAllNext(nextLink, this.client.getEndpoint(), accept, context)
.map(
res ->
new PagedResponseBase<>(
res.getRequest(),
res.getStatusCode(),
res.getHeaders(),
res.getValue().value(),
res.getValue().nextLink(),
null));
}
}
| mit |
weiFans/Keekan | src/com/keekan/serve/impl/AttestInfoServeImpl.java | 1385 | package com.keekan.serve.impl;
import com.keekan.bean.AttestInfoBean;
import com.keekan.dao.AttestInfoDao;
import com.keekan.serve.AttestInfoServe;
/**
* @author KEEKAN.10000
* @version 1.0 <br>
* Copyright (C), 2012-, keekan.com <br>
* This program is protected by copyright laws. <br>
* Program Name: KEEKAN<br>
* Class Name: 验证信息的Serve接口实现 <br>
*/
public class AttestInfoServeImpl implements AttestInfoServe {
private AttestInfoDao attestInfoDao;
/**
* 添加验证信息
*/
public Integer addAlbumCover(Integer keeno, Integer groupId, Integer friendKeeno, String remarkInfo, String attestInfo, String infoStatus, String infoDate) throws Exception {
try {
AttestInfoBean a = new AttestInfoBean();
a.setKeeno(keeno);
a.setGroupId(groupId);
a.setFriendKeeno(friendKeeno);
a.setRemarkInfo(remarkInfo);
a.setAttestInfo(attestInfo);
a.setInfoStatus(infoStatus);
a.setInfoDate(infoDate);
attestInfoDao.addAlbumCover(a);
return a.getInfoId();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("添加验证信息时出现异常");
}
}
public void setAttestInfoDao(AttestInfoDao attestInfoDao) {
this.attestInfoDao = attestInfoDao;
}
public AttestInfoDao getAttestInfoDao() {
return attestInfoDao;
}
}
| mit |
Azure/azure-sdk-for-java | sdk/datafactory/azure-resourcemanager-datafactory/src/main/java/com/azure/resourcemanager/datafactory/fluent/models/ScheduleTriggerTypeProperties.java | 1945 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.datafactory.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.datafactory.models.ScheduleTriggerRecurrence;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Schedule Trigger properties. */
@Fluent
public final class ScheduleTriggerTypeProperties {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ScheduleTriggerTypeProperties.class);
/*
* Recurrence schedule configuration.
*/
@JsonProperty(value = "recurrence", required = true)
private ScheduleTriggerRecurrence recurrence;
/**
* Get the recurrence property: Recurrence schedule configuration.
*
* @return the recurrence value.
*/
public ScheduleTriggerRecurrence recurrence() {
return this.recurrence;
}
/**
* Set the recurrence property: Recurrence schedule configuration.
*
* @param recurrence the recurrence value to set.
* @return the ScheduleTriggerTypeProperties object itself.
*/
public ScheduleTriggerTypeProperties withRecurrence(ScheduleTriggerRecurrence recurrence) {
this.recurrence = recurrence;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (recurrence() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property recurrence in model ScheduleTriggerTypeProperties"));
} else {
recurrence().validate();
}
}
}
| mit |
jas777/OnTheRails | src/main/java/io/github/jas777/ontherails/proxy/CommonProxy.java | 108 | package io.github.jas777.ontherails.proxy;
//Changed
public interface CommonProxy {
void preInit();
}
| mit |
jhsx/hacklang-idea | gen/io/github/josehsantos/hack/lang/psi/HackParenthesizedExpression.java | 3262 | // This is a generated file. Not intended for manual editing.
package io.github.josehsantos.hack.lang.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface HackParenthesizedExpression extends HackExpression {
@Nullable
HackAdditiveConcatenationExpression getAdditiveConcatenationExpression();
@Nullable
HackArrayAccessExpression getArrayAccessExpression();
@Nullable
HackArrayLiteralExpression getArrayLiteralExpression();
@Nullable
HackAssignmentExpression getAssignmentExpression();
@Nullable
HackBackticksExpression getBackticksExpression();
@Nullable
HackBitwiseExpression getBitwiseExpression();
@Nullable
HackCallableFunctionCallExpression getCallableFunctionCallExpression();
@Nullable
HackCastExpression getCastExpression();
@Nullable
HackCloneExpression getCloneExpression();
@Nullable
HackClosureExpression getClosureExpression();
@Nullable
HackCollectionLiteralExpression getCollectionLiteralExpression();
@Nullable
HackComparativeExpression getComparativeExpression();
@Nullable
HackDynamicVariableExpression getDynamicVariableExpression();
@Nullable
HackEmptyExpression getEmptyExpression();
@Nullable
HackEspecialParenthesisedExpression getEspecialParenthesisedExpression();
@Nullable
HackEvalExpression getEvalExpression();
@Nullable
HackExitExpression getExitExpression();
@Nullable
HackFunctionCallExpression getFunctionCallExpression();
@Nullable
HackIncludeExpression getIncludeExpression();
@Nullable
HackInstanceofExpression getInstanceofExpression();
@Nullable
HackIssetExpression getIssetExpression();
@Nullable
HackLambdaExpression getLambdaExpression();
@Nullable
HackListAssignmentExpression getListAssignmentExpression();
@Nullable
HackLogicalExpression getLogicalExpression();
@Nullable
HackMapArrayLiteralExpression getMapArrayLiteralExpression();
@Nullable
HackMemberVariableExpression getMemberVariableExpression();
@Nullable
HackMethodCallExpression getMethodCallExpression();
@Nullable
HackMultiplicativeExpression getMultiplicativeExpression();
@Nullable
HackNewExpression getNewExpression();
@Nullable
HackParenthesizedExpression getParenthesizedExpression();
@Nullable
HackPrefixOperator getPrefixOperator();
@Nullable
HackPrintExpression getPrintExpression();
@Nullable
HackRequireExpression getRequireExpression();
@Nullable
HackScalarExpression getScalarExpression();
@Nullable
HackShapeLiteralExpression getShapeLiteralExpression();
@Nullable
HackShiftExpression getShiftExpression();
@Nullable
HackStaticClassVariableExpression getStaticClassVariableExpression();
@Nullable
HackStaticMethodCallExpression getStaticMethodCallExpression();
@Nullable
HackSuffixOperator getSuffixOperator();
@Nullable
HackTernaryExpression getTernaryExpression();
@Nullable
HackTupleExpression getTupleExpression();
@Nullable
HackVArrayLiteralExpression getVArrayLiteralExpression();
@Nullable
HackVariableExpression getVariableExpression();
@Nullable
HackVariableNameHolder getVariableNameHolder();
@Nullable
HackXhpExpression getXhpExpression();
}
| mit |
kwizzad/kwizzad-android | sdk/src/main/java/com/kwizzad/model/IComponent.java | 60 | package com.kwizzad.model;
public interface IComponent {
}
| mit |
mahadirz/UnitenInfo | app/src/main/java/my/madet/adapter/NavDrawerListAdapter.java | 3375 | /*
* The MIT License (MIT)
* Copyright (c) 2014 Mahadir Ahmad
*
* 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.
*
*
*/
/**
* Drawer Navigation adapters
*
* @author Mahadir Ahmad
* @version 1.0
*
*/
package my.madet.adapter;
import java.util.ArrayList;
import my.madet.model.NavDrawerItem;
import my.madet.uniteninfo.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
@Override
public int getCount() {
return navDrawerItems.size();
}
@Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
| mit |
xtuhcy/gecco | src/main/java/com/geccocrawler/gecco/downloader/DefaultDownloaderFactory.java | 417 | package com.geccocrawler.gecco.downloader;
import org.reflections.Reflections;
/**
* 下载器工厂类
*
* @author huchengyi
*
*/
public class DefaultDownloaderFactory extends DownloaderFactory {
public DefaultDownloaderFactory(Reflections reflections) {
super(reflections);
}
protected Object createDownloader(Class<?> downloaderClass) throws Exception {
return downloaderClass.newInstance();
}
}
| mit |
nicksellen/reka | reka-core/src/main/java/reka/flow/FlowSegment.java | 846 | package reka.flow;
import java.util.Collection;
import reka.data.Data;
import reka.flow.ops.RouteKey;
public interface FlowSegment {
// not optional!
Collection<FlowSegment> sources();
Collection<FlowSegment> destinations();
Collection<FlowConnection> connections();
Collection<FlowSegment> segments();
boolean isNode();
default boolean isNewContext() {
return false;
}
Data meta();
// all optional (well, should be)
RouteKey key();
String label();
FlowNode node();
default FlowSegment withNewContext() {
return new FlowSegmentProxy(this){
@Override
public boolean isNewContext() {
return true;
}
};
}
default FlowSegment clearNewContext() {
return new FlowSegmentProxy(this){
@Override
public boolean isNewContext() {
return false;
}
};
}
} | mit |
Trinion/Java-GoodGame-Api-Wrapper | src/test/java/ru/maximkulikov/goodgame/api/PlayerResourseTesting.java | 1873 | package ru.maximkulikov.goodgame.api;
import org.junit.Test;
import ru.maximkulikov.goodgame.api.handlers.PlayerResponseHandler;
import ru.maximkulikov.goodgame.api.models.Player;
import static org.junit.Assert.assertEquals;
/**
* Java-GoodGame-Api-Wrapper
* Created by maxim on 02.06.2017.
*/
public class PlayerResourseTesting {
private static final GoodGame gg = GoodGameTest.getGg();
private static final String CHANNELID = "36229";
@Test
public void getPlayerTest() {
final Object o = new Object();
final boolean[] lock = new boolean[1];
lock[0] = false;
final Player[] p = new Player[1];
gg.player().getPlayer(CHANNELID, new PlayerResponseHandler() {
@Override
public void onFailure(int statusCode, String statusMessage, String errorMessage) {
lock[0] = true;
synchronized (o) {
o.notifyAll();
}
}
@Override
public void onFailure(Throwable throwable) {
lock[0] = true;
synchronized (o) {
o.notifyAll();
}
}
@Override
public void onSuccess(Player player) {
p[0] = player;
lock[0] = true;
synchronized (o) {
o.notifyAll();
}
}
});
synchronized (o) {
while (!lock[0]) {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
assertEquals("36229", p[0].getChannelId());
assertEquals("Trinion", p[0].getChannelKey());
assertEquals("1494338668", p[0].getChannelStart());
}
}
| mit |
mmmce1994/wallet98 | app/src/main/java/com/platform/APIClient.java | 25123 | package com.platform;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.util.Log;
import com.utabitwallet.BuildConfig;
import com.utabitwallet.presenter.activities.MainActivity;
import com.utabitwallet.tools.crypto.Base58;
import com.utabitwallet.tools.manager.SharedPreferencesManager;
import com.utabitwallet.tools.crypto.CryptoHelper;
import com.utabitwallet.tools.security.KeyStoreManager;
import com.utabitwallet.tools.util.Utils;
import com.utabitwallet.wallet.BRWalletManager;
import com.jniwrappers.BRKey;
import com.platform.kvstore.RemoteKVStore;
import com.platform.kvstore.ReplicatedKVStore;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import io.sigpipe.jbsdiff.InvalidHeaderException;
import io.sigpipe.jbsdiff.ui.FileUI;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSink;
import static com.utabitwallet.tools.util.BRCompressor.gZipExtract;
/**
* BreadWallet
* <p/>
* Created by Mihail Gutan on <mihail@breadwallet.com> 9/29/16.
* Copyright (c) 2016 breadwallet LLC
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p/>
* 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.
*/
public class APIClient {
public static final String TAG = APIClient.class.getName();
// proto is the transport protocol to use for talking to the API (either http or https)
private static final String PROTO = "https";
// host is the server(s) on which the API is hosted
private static final String HOST = "api.breadwallet.com";
// convenience getter for the API endpoint
public static final String BASE_URL = PROTO + "://" + HOST;
//feePerKb url
private static final String FEE_PER_KB_URL = "/v1/fee-per-kb";
//token
private static final String TOKEN = "/token";
//me
private static final String ME = "/me";
//singleton instance
private static APIClient ourInstance;
private static final String GET = "GET";
private static final String POST = "POST";
public static final String BUNDLES = "bundles";
// public static final String BREAD_BUY = "bread-buy-staging";
public static String BREAD_BUY = "bread-buy-staging";
public static String bundlesFileName = String.format("/%s", BUNDLES);
public static String bundleFileName = String.format("/%s/%s.tar", BUNDLES, BREAD_BUY);
public static String extractedFolder = String.format("%s-extracted", BREAD_BUY);
public static HTTPServer server;
private Activity ctx;
public enum FeatureFlags {
BUY_BITCOIN("buy-bitcoin"),
EARLY_ACCESS("early-access");
private final String text;
/**
* @param text
*/
private FeatureFlags(final String text) {
this.text = text;
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return text;
}
}
public static synchronized APIClient getInstance(Activity context) {
if (ourInstance == null) ourInstance = new APIClient(context);
return ourInstance;
}
private APIClient(Activity context) {
ctx = context;
if (0 != (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) {
BREAD_BUY = "bread-buy-staging";
}
}
private APIClient() {
}
//returns the fee per kb or 0 if something went wrong
public long feePerKb() {
try {
String strUtl = BASE_URL + FEE_PER_KB_URL;
Request request = new Request.Builder().url(strUtl).get().build();
String body = null;
try {
Response response = sendRequest(request, false, 0);
body = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject object = null;
object = new JSONObject(body);
return (long) object.getInt("fee_per_kb");
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
public Response buyBitcoinMe() {
if (ctx == null) ctx = MainActivity.app;
if (ctx == null) return null;
String strUtl = BASE_URL + ME;
Request request = new Request.Builder()
.url(strUtl)
.get()
.build();
String response = null;
Response res = null;
try {
res = sendRequest(request, true, 0);
response = res.body().string();
if (response.isEmpty()) {
res = sendRequest(request, true, 0);
response = res.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
if (response == null) throw new NullPointerException();
return res;
}
public String getToken() {
if (ctx == null) ctx = MainActivity.app;
if (ctx == null) return null;
try {
String strUtl = BASE_URL + TOKEN;
JSONObject requestMessageJSON = new JSONObject();
String base58PubKey = BRWalletManager.getAuthPublicKeyForAPI(KeyStoreManager.getAuthKey(ctx));
requestMessageJSON.put("pubKey", base58PubKey);
requestMessageJSON.put("deviceID", SharedPreferencesManager.getDeviceId(ctx));
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, requestMessageJSON.toString());
Request request = new Request.Builder()
.url(strUtl)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.post(requestBody).build();
String strResponse = null;
Response response;
try {
response = sendRequest(request, false, 0);
if (response != null)
strResponse = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
if (Utils.isNullOrEmpty(strResponse)) {
Log.e(TAG, "getToken: retrieving token failed");
return null;
}
JSONObject obj = null;
obj = new JSONObject(strResponse);
String token = obj.getString("token");
KeyStoreManager.putToken(token.getBytes(), ctx);
return token;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String createRequest(String reqMethod, String base58Body, String contentType, String dateHeader, String url) {
return (reqMethod == null ? "" : reqMethod) + "\n" +
(base58Body == null ? "" : base58Body) + "\n" +
(contentType == null ? "" : contentType) + "\n" +
(dateHeader == null ? "" : dateHeader) + "\n" +
(url == null ? "" : url);
}
public String signRequest(String request) {
byte[] doubleSha256 = CryptoHelper.doubleSha256(request.getBytes(StandardCharsets.UTF_8));
BRKey key = new BRKey(KeyStoreManager.getAuthKey(ctx));
byte[] signedBytes = key.compactSign(doubleSha256);
return Base58.encode(signedBytes);
}
public Response sendRequest(Request locRequest, boolean needsAuth, int retryCount) {
if (retryCount > 1)
throw new RuntimeException("sendRequest: Warning retryCount is: " + retryCount);
boolean isTestVersion = BREAD_BUY.equalsIgnoreCase("bread-buy-staging");
boolean isTestNet = BuildConfig.BITCOIN_TESTNET;
Request request = locRequest.newBuilder().header("X-Testflight", isTestVersion ? "1" : "0").header("X-Bitcoin-Testnet", isTestNet ? "1" : "0").build();
if (needsAuth) {
Request.Builder modifiedRequest = request.newBuilder();
String base58Body = "";
RequestBody body = request.body();
try {
if (body != null && body.contentLength() != 0) {
BufferedSink sink = new Buffer();
try {
body.writeTo(sink);
} catch (IOException e) {
e.printStackTrace();
}
String bodyString = sink.buffer().readUtf8();
base58Body = CryptoHelper.base58ofSha256(bodyString.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
SimpleDateFormat sdf =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String httpDate = sdf.format(new Date());
request = modifiedRequest.header("Date", httpDate.substring(0, httpDate.length() - 6)).build();
String queryString = request.url().encodedQuery();
String requestString = createRequest(request.method(), base58Body,
request.header("Content-Type"), request.header("Date"), request.url().encodedPath()
+ ((queryString != null && !queryString.isEmpty()) ? ("?" + queryString) : ""));
String signedRequest = signRequest(requestString);
String token = new String(KeyStoreManager.getToken(ctx));
if (token.isEmpty()) token = getToken();
if (token == null || token.isEmpty()) {
Log.e(TAG, "sendRequest: failed to retrieve token");
return null;
}
String authValue = "bread " + token + ":" + signedRequest;
// Log.e(TAG, "sendRequest: authValue: " + authValue);
modifiedRequest = request.newBuilder();
request = modifiedRequest.header("Authorization", authValue).build();
}
Response response = null;
byte[] data = new byte[0];
try {
OkHttpClient client = new OkHttpClient.Builder().followRedirects(false)/*.addInterceptor(new LoggingInterceptor())*/.build();
// Log.e(TAG, "sendRequest: before executing the request: " + request.headers().toString());
response = client.newCall(request).execute();
try {
data = response.body().bytes();
} catch (IOException e) {
e.printStackTrace();
}
if (!response.isSuccessful())
Log.e(TAG, "sendRequest: " + String.format(Locale.getDefault(), "url (%s), code (%d), mess (%s), body (%s)",
request.url(), response.code(), response.message(), new String(data)));
if (response.isRedirect()) {
String newLocation = request.url().scheme() + "://" + request.url().host() + response.header("location");
Uri newUri = Uri.parse(newLocation);
if (newUri == null) {
Log.e(TAG, "sendRequest: redirect uri is null");
} else if (!newUri.getHost().equalsIgnoreCase(HOST) || !newUri.getScheme().equalsIgnoreCase(PROTO)) {
Log.e(TAG, "sendRequest: WARNING: redirect is NOT safe: " + newLocation);
} else {
Log.w(TAG, "redirecting: " + request.url() + " >>> " + newLocation);
return sendRequest(new Request.Builder().url(newLocation).get().build(), needsAuth, 0);
}
return new Response.Builder().code(500).request(request).body(ResponseBody.create(null, new byte[0])).protocol(Protocol.HTTP_1_1).build();
}
} catch (IOException e) {
e.printStackTrace();
return new Response.Builder().code(599).request(request).body(ResponseBody.create(null, new byte[0])).protocol(Protocol.HTTP_1_1).build();
}
if (response.header("content-encoding") != null && response.header("content-encoding").equalsIgnoreCase("gzip")) {
Log.d(TAG, "sendRequest: the content is gzip, unzipping");
byte[] decompressed = gZipExtract(data);
ResponseBody postReqBody = ResponseBody.create(null, decompressed);
return response.newBuilder().body(postReqBody).build();
}
ResponseBody postReqBody = ResponseBody.create(null, data);
if (needsAuth && isBreadChallenge(response)) {
Log.e(TAG, "sendRequest: got authentication challenge from API - will attempt to get token");
getToken();
if (retryCount < 1) {
sendRequest(request, true, retryCount + 1);
}
}
return response.newBuilder().body(postReqBody).build();
}
public void updateBundle() {
File bundleFile = new File(ctx.getFilesDir().getAbsolutePath() + bundleFileName);
if (bundleFile.exists()) {
Log.d(TAG, "updateBundle: exists");
byte[] bFile = new byte[0];
try {
bFile = IOUtils.toByteArray(new FileInputStream(bundleFile));
} catch (IOException e) {
e.printStackTrace();
}
String latestVersion = getLatestVersion();
String currentTarVersion = null;
byte[] hash = CryptoHelper.sha256(bFile);
currentTarVersion = Utils.bytesToHex(hash);
Log.e(TAG, "updateBundle: version of the current tar: " + currentTarVersion);
if (latestVersion != null) {
if (latestVersion.equals(currentTarVersion)) {
Log.d(TAG, "updateBundle: have the latest version");
tryExtractTar(bundleFile);
} else {
Log.d(TAG, "updateBundle: don't have the most recent version, download diff");
downloadDiff(bundleFile, currentTarVersion);
tryExtractTar(bundleFile);
}
} else {
Log.d(TAG, "updateBundle: latestVersion is null");
}
} else {
Log.d(TAG, "updateBundle: bundle doesn't exist, downloading new copy");
long startTime = System.currentTimeMillis();
Request request = new Request.Builder()
.url(String.format("%s/assets/bundles/%s/download", BASE_URL, BREAD_BUY))
.get().build();
Response response = null;
response = sendRequest(request, false, 0);
Log.d(TAG, "updateBundle: Downloaded, took: " + (System.currentTimeMillis() - startTime));
writeBundleToFile(response, bundleFile);
tryExtractTar(bundleFile);
}
}
public String getLatestVersion() {
String latestVersion = null;
String response = null;
try {
response = sendRequest(new Request.Builder()
.get()
.url(String.format("%s/assets/bundles/%s/versions", BASE_URL, BREAD_BUY))
.build(), false, 0).body().string();
} catch (IOException e) {
e.printStackTrace();
}
String respBody;
respBody = response;
try {
JSONObject versionsJson = new JSONObject(respBody);
JSONArray jsonArray = versionsJson.getJSONArray("versions");
if (jsonArray.length() == 0) return null;
latestVersion = (String) jsonArray.get(jsonArray.length() - 1);
} catch (JSONException e) {
e.printStackTrace();
}
return latestVersion;
}
public void downloadDiff(File bundleFile, String currentTarVersion) {
Request diffRequest = new Request.Builder()
.url(String.format("%s/assets/bundles/%s/diff/%s", BASE_URL, BREAD_BUY, currentTarVersion))
.get().build();
Response diffResponse = sendRequest(diffRequest, false, 0);
File patchFile = null;
File tempFile = null;
byte[] patchBytes = null;
try {
patchFile = new File(String.format("/%s/%s.diff", BUNDLES, "patch"));
patchBytes = diffResponse.body().bytes();
FileUtils.writeByteArrayToFile(patchFile, patchBytes);
String compression = System.getProperty("jbsdiff.compressor", "tar");
compression = compression.toLowerCase();
tempFile = new File(String.format("/%s/%s.tar", BUNDLES, "temp"));
FileUI.diff(bundleFile, tempFile, patchFile, compression);
byte[] updatedBundleBytes = IOUtils.toByteArray(new FileInputStream(tempFile));
FileUtils.writeByteArrayToFile(bundleFile, updatedBundleBytes);
} catch (IOException | InvalidHeaderException | CompressorException | NullPointerException e) {
e.printStackTrace();
} finally {
if (patchFile != null)
patchFile.delete();
if (tempFile != null)
tempFile.delete();
}
}
public byte[] writeBundleToFile(Response response, File bundleFile) {
byte[] bodyBytes;
FileOutputStream fileOutputStream = null;
assert (response != null);
try {
if (response == null) {
Log.e(TAG, "writeBundleToFile: WARNING, response is null");
return null;
}
bodyBytes = response.body().bytes();
FileUtils.writeByteArrayToFile(bundleFile, bodyBytes);
return bodyBytes;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public boolean tryExtractTar(File inputFile) {
String extractFolderName = MainActivity.app.getFilesDir().getAbsolutePath() + bundlesFileName + "/" + extractedFolder;
boolean result = false;
TarArchiveInputStream debInputStream = null;
try {
final InputStream is = new FileInputStream(inputFile);
debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
TarArchiveEntry entry = null;
while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
final String outPutFileName = entry.getName().replace("./", "");
final File outputFile = new File(extractFolderName, outPutFileName);
if (!entry.isDirectory()) {
FileUtils.writeByteArrayToFile(outputFile, org.apache.commons.compress.utils.IOUtils.toByteArray(debInputStream));
}
}
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (debInputStream != null)
debInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public void updateFeatureFlag() {
String furl = "/me/features";
Request req = new Request.Builder()
.url(buildUrl(furl))
.get().build();
Response res = sendRequest(req, true, 0);
if (res == null) {
Log.e(TAG, "updateFeatureFlag: error fetching features");
return;
}
if (!res.isSuccessful()) {
Log.e(TAG, "updateFeatureFlag: request was unsuccessful: " + res.code() + ":" + res.message());
return;
}
try {
String j = res.body().string();
if (j.isEmpty()) {
Log.e(TAG, "updateFeatureFlag: JSON empty");
return;
}
JSONArray arr = new JSONArray(j);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
String name = obj.getString("name");
String description = obj.getString("description");
boolean selected = obj.getBoolean("selected");
boolean enabled = obj.getBoolean("enabled");
SharedPreferencesManager.putFeatureEnabled(ctx, enabled, name);
} catch (Exception e) {
Log.e(TAG, "malformed feature at position: " + i + ", whole json: " + j, e);
}
}
} catch (IOException | JSONException e) {
Log.e(TAG, "updateFeatureFlag: failed to pull up features");
e.printStackTrace();
}
}
public boolean isBreadChallenge(Response resp) {
String challenge = resp.header("www-authenticate");
return challenge != null && challenge.startsWith("bread");
}
public boolean isFeatureEnabled(String feature) {
return SharedPreferencesManager.getFeatureEnabled(ctx, feature);
}
public String buildUrl(String path) {
return BASE_URL + path;
}
private class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d(TAG, String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d(TAG, String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
public void updatePlatform() {
if (BuildConfig.DEBUG) {
final long startTime = System.currentTimeMillis();
Log.d(TAG, "updatePlatform: updating platform...");
new Thread(new Runnable() {
@Override
public void run() {
APIClient apiClient = APIClient.getInstance(ctx);
apiClient.updateBundle(); //bread-buy-staging
apiClient.updateFeatureFlag();
apiClient.syncKvStore();
long endTime = System.currentTimeMillis();
Log.e(TAG, "updatePlatform: DONE in " + (endTime - startTime) + "ms");
}
}).start();
}
}
public void syncKvStore() {
final APIClient client = this;
final long startTime = System.currentTimeMillis();
Log.d(TAG, "syncKvStore: DEBUG, syncing kv store...");
//sync the kv stores
RemoteKVStore remoteKVStore = RemoteKVStore.getInstance(client);
ReplicatedKVStore kvStore = new ReplicatedKVStore(ctx, remoteKVStore);
kvStore.syncAllKeys();
long endTime = System.currentTimeMillis();
Log.d(TAG, "syncKvStore: DONE in " + (endTime - startTime) + "ms");
}
} | mit |
zkkz/OrientalExpress | source/step/src/sse/ngts/common/plugin/step/business/TCPLogin.java | 9143 | /*########################################################################
*# #
*# Copyright (c) 2014 by #
*# Shanghai Stock Exchange (SSE), Shanghai, China #
*# All rights reserved. #
*# #
*########################################################################
*/
package sse.ngts.common.plugin.step.business;
import sse.ngts.common.plugin.step.FieldNotFound;
import sse.ngts.common.plugin.step.MessageEx;
import sse.ngts.common.plugin.step.field.DefaultApplExtID;
import sse.ngts.common.plugin.step.field.DefaultApplVerID;
import sse.ngts.common.plugin.step.field.DefaultCstmApplVerID;
import sse.ngts.common.plugin.step.field.EncryptMethod;
import sse.ngts.common.plugin.step.field.HeartBtInt;
import sse.ngts.common.plugin.step.field.MessageEncoding;
import sse.ngts.common.plugin.step.field.MsgSeqNum;
import sse.ngts.common.plugin.step.field.MsgType;
import sse.ngts.common.plugin.step.field.NextExpectedMsgSeqNum;
import sse.ngts.common.plugin.step.field.Password;
import sse.ngts.common.plugin.step.field.ResetSeqNumFlag;
import sse.ngts.common.plugin.step.field.SenderCompID;
import sse.ngts.common.plugin.step.field.SendingTime;
import sse.ngts.common.plugin.step.field.TargetCompID;
import sse.ngts.common.plugin.step.field.UserName;
public class TCPLogin extends MessageEx {
private static final long serialVersionUID = 6126341111805458449L;
public static final String MSGTYPE = "A";
public TCPLogin() {
super();
setMsgType(new MsgType(MSGTYPE), 1);
getHeader().setField(new MsgType(MSGTYPE));
}
public TCPLogin(int[] fieldOrder, long sendMsgSeqNum) {
super(fieldOrder);
setMsgType(new MsgType(MSGTYPE), sendMsgSeqNum);
getHeader().setField(new MsgType(MSGTYPE));
}
public void set(SenderCompID value) {
setField(value);
}
public SenderCompID get(SenderCompID value) throws FieldNotFound {
getField(value);
return value;
}
public SenderCompID getSenderCompID() throws FieldNotFound {
SenderCompID value = new SenderCompID();
getField(value);
return value;
}
public boolean isSet(SenderCompID field) {
return isSetField(field);
}
public boolean isSetSenderCompID() {
return isSetField(SenderCompID.FIELD);
}
public void set(TargetCompID value) {
setField(value);
}
public TargetCompID get(TargetCompID value) throws FieldNotFound {
getField(value);
return value;
}
public TargetCompID getTargetCompID() throws FieldNotFound {
TargetCompID value = new TargetCompID();
getField(value);
return value;
}
public boolean isSet(TargetCompID field) {
return isSetField(field);
}
public boolean isSetTargetCompID() {
return isSetField(TargetCompID.FIELD);
}
public void set(SendingTime value) {
setField(value);
}
public SendingTime get(SendingTime value) throws FieldNotFound {
getField(value);
return value;
}
public SendingTime getSendingTime() throws FieldNotFound {
SendingTime value = new SendingTime();
getField(value);
return value;
}
public boolean isSet(SendingTime field) {
return isSetField(field);
}
public boolean isSetSendingTime() {
return isSetField(SendingTime.FIELD);
}
public void set(MsgSeqNum value) {
setField(value);
}
public MsgSeqNum get(MsgSeqNum value) throws FieldNotFound {
getField(value);
return value;
}
public MsgSeqNum getMsgSeqNum() throws FieldNotFound {
MsgSeqNum value = new MsgSeqNum();
getField(value);
return value;
}
public boolean isSet(MsgSeqNum field) {
return isSetField(field);
}
public boolean isSetMsgSeqNum() {
return isSetField(MsgSeqNum.FIELD);
}
public void set(MessageEncoding value) {
setField(value);
}
public MessageEncoding get(MessageEncoding value) throws FieldNotFound {
getField(value);
return value;
}
public MessageEncoding getMessageEncoding() throws FieldNotFound {
MessageEncoding value = new MessageEncoding();
getField(value);
return value;
}
public boolean isSet(MessageEncoding field) {
return isSetField(field);
}
public boolean isSetMessageEncoding() {
return isSetField(MessageEncoding.FIELD);
}
public void set(EncryptMethod value) {
setField(value);
}
public EncryptMethod get(EncryptMethod value) throws FieldNotFound {
getField(value);
return value;
}
public EncryptMethod getEncryptMethod() throws FieldNotFound {
EncryptMethod value = new EncryptMethod();
getField(value);
return value;
}
public boolean isSet(EncryptMethod field) {
return isSetField(field);
}
public boolean isSetEncryptMethod() {
return isSetField(EncryptMethod.FIELD);
}
public void set(HeartBtInt value) {
setField(value);
}
public HeartBtInt get(HeartBtInt value) throws FieldNotFound {
getField(value);
return value;
}
public HeartBtInt getHeartBtInt() throws FieldNotFound {
HeartBtInt value = new HeartBtInt();
getField(value);
return value;
}
public boolean isSet(HeartBtInt field) {
return isSetField(field);
}
public boolean isSetHeartBtInt() {
return isSetField(HeartBtInt.FIELD);
}
public void set(UserName value) {
setField(value);
}
public UserName get(UserName value) throws FieldNotFound {
getField(value);
return value;
}
public UserName getUserName() throws FieldNotFound {
UserName value = new UserName();
getField(value);
return value;
}
public boolean isSet(UserName field) {
return isSetField(field);
}
public boolean isSetUserName() {
return isSetField(UserName.FIELD);
}
public void set(Password value) {
setField(value);
}
public Password get(Password value) throws FieldNotFound {
getField(value);
return value;
}
public Password getPassword() throws FieldNotFound {
Password value = new Password();
getField(value);
return value;
}
public boolean isSet(Password field) {
return isSetField(field);
}
public boolean isSetPassword() {
return isSetField(Password.FIELD);
}
public void set(ResetSeqNumFlag value) {
setField(value);
}
public ResetSeqNumFlag get(ResetSeqNumFlag value) throws FieldNotFound {
getField(value);
return value;
}
public ResetSeqNumFlag getResetSeqNumFlag() throws FieldNotFound {
ResetSeqNumFlag value = new ResetSeqNumFlag();
getField(value);
return value;
}
public boolean isSet(ResetSeqNumFlag field) {
return isSetField(field);
}
public boolean isSetResetSeqNumFlag() {
return isSetField(ResetSeqNumFlag.FIELD);
}
public void set(NextExpectedMsgSeqNum value) {
setField(value);
}
public NextExpectedMsgSeqNum get(NextExpectedMsgSeqNum value) throws FieldNotFound {
getField(value);
return value;
}
public NextExpectedMsgSeqNum getNextExpectedMsgSeqNum() throws FieldNotFound {
NextExpectedMsgSeqNum value = new NextExpectedMsgSeqNum();
getField(value);
return value;
}
public boolean isSet(NextExpectedMsgSeqNum field) {
return isSetField(field);
}
public boolean isSetNextExpectedMsgSeqNum() {
return isSetField(NextExpectedMsgSeqNum.FIELD);
}
public void set(DefaultApplVerID value) {
setField(value);
}
public DefaultApplVerID get(DefaultApplVerID value) throws FieldNotFound {
getField(value);
return value;
}
public DefaultApplVerID getDefaultApplVerID() throws FieldNotFound {
DefaultApplVerID value = new DefaultApplVerID();
getField(value);
return value;
}
public boolean isSet(DefaultApplVerID field) {
return isSetField(field);
}
public boolean isSetDefaultApplVerID() {
return isSetField(DefaultApplVerID.FIELD);
}
public void set(DefaultApplExtID value) {
setField(value);
}
public DefaultApplExtID get(DefaultApplExtID value) throws FieldNotFound {
getField(value);
return value;
}
public DefaultApplExtID getDefaultApplExtID() throws FieldNotFound {
DefaultApplExtID value = new DefaultApplExtID();
getField(value);
return value;
}
public boolean isSet(DefaultApplExtID field) {
return isSetField(field);
}
public boolean isSetDefaultApplExtID() {
return isSetField(DefaultApplExtID.FIELD);
}
public void set(DefaultCstmApplVerID value) {
setField(value);
}
public DefaultCstmApplVerID get(DefaultCstmApplVerID value) throws FieldNotFound {
getField(value);
return value;
}
public DefaultCstmApplVerID getDefaultCstmApplVerID() throws FieldNotFound {
DefaultCstmApplVerID value = new DefaultCstmApplVerID();
getField(value);
return value;
}
public boolean isSet(DefaultCstmApplVerID field) {
return isSetField(field);
}
public boolean isSetDefaultCstmApplVerID() {
return isSetField(DefaultCstmApplVerID.FIELD);
}
}
| mit |
ShaqCc/Spring-helloword | src/main/java/com/paicaifu/app/domain/ErrorInfo.java | 718 | package com.paicaifu.app.domain;
/**
* Created by bayin on 2017/2/20.
*/
public class ErrorInfo<T> {
private String code;
private String msg;
private T data;
private String result;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
| mit |
zmaster587/AdvancedRocketry | src/main/java/zmaster587/advancedRocketry/tile/oxygen/TileOxygenVent.java | 14085 | package zmaster587.advancedRocketry.tile.oxygen;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.relauncher.Side;
import zmaster587.advancedRocketry.api.AdvancedRocketryBlocks;
import zmaster587.advancedRocketry.api.AdvancedRocketryFluids;
import zmaster587.advancedRocketry.api.AreaBlob;
import zmaster587.advancedRocketry.api.Configuration;
import zmaster587.advancedRocketry.api.util.IBlobHandler;
import zmaster587.advancedRocketry.atmosphere.AtmosphereHandler;
import zmaster587.advancedRocketry.atmosphere.AtmosphereType;
import zmaster587.advancedRocketry.dimension.DimensionManager;
import zmaster587.advancedRocketry.inventory.TextureResources;
import zmaster587.advancedRocketry.util.AudioRegistry;
import zmaster587.libVulpes.LibVulpes;
import zmaster587.libVulpes.api.IToggleableMachine;
import zmaster587.libVulpes.block.BlockTile;
import zmaster587.libVulpes.client.RepeatingSound;
import zmaster587.libVulpes.inventory.modules.*;
import zmaster587.libVulpes.network.PacketHandler;
import zmaster587.libVulpes.network.PacketMachine;
import zmaster587.libVulpes.tile.TileInventoriedRFConsumerTank;
import zmaster587.libVulpes.util.FluidUtils;
import zmaster587.libVulpes.util.HashedBlockPosition;
import zmaster587.libVulpes.util.IAdjBlockUpdate;
import zmaster587.libVulpes.util.INetworkMachine;
import zmaster587.libVulpes.util.ZUtils.RedstoneState;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class TileOxygenVent extends TileInventoriedRFConsumerTank implements IBlobHandler, IModularInventory, INetworkMachine, IAdjBlockUpdate, IToggleableMachine, IButtonInventory, IToggleButton {
boolean isSealed;
boolean firstRun;
boolean hasFluid;
boolean soundInit;
boolean allowTrace;
int numScrubbers;
List<TileCO2Scrubber> scrubbers;
int radius = 0;
final static byte PACKET_REDSTONE_ID = 2;
final static byte PACKET_TRACE_ID = 3;
RedstoneState state;
ModuleRedstoneOutputButton redstoneControl;
ModuleToggleSwitch traceToggle;
public TileOxygenVent() {
super(1000,2, 1000);
isSealed = true;
firstRun = true;
hasFluid = true;
soundInit = false;
allowTrace = false;
numScrubbers = 0;
scrubbers = new LinkedList<TileCO2Scrubber>();
state = RedstoneState.ON;
redstoneControl = new ModuleRedstoneOutputButton(174, 4, PACKET_REDSTONE_ID, "", this);
traceToggle = new ModuleToggleSwitch(80, 20, PACKET_TRACE_ID, LibVulpes.proxy.getLocalizedString("msg.vent.trace"), this, TextureResources.buttonGeneric, 80, 18, false);
}
public TileOxygenVent(int energy, int invSize, int tankSize) {
super(energy, invSize, tankSize);
isSealed = false;
firstRun = false;
hasFluid = true;
soundInit = false;
allowTrace = false;
scrubbers = new LinkedList<TileCO2Scrubber>();
state = RedstoneState.ON;
redstoneControl = new ModuleRedstoneOutputButton(174, 4, 0, "", this);
traceToggle = new ModuleToggleSwitch(80, 20, 5, LibVulpes.proxy.getLocalizedString("msg.vent.trace"), this, TextureResources.buttonGeneric, 80, 18, false);
}
@Override
public boolean canPerformFunction() {
return AtmosphereHandler.hasAtmosphereHandler(this.world.provider.getDimension());
}
@Override
public World getWorldObj() {
return getWorld();
}
@Override
public void onAdjacentBlockUpdated() {
if(isSealed)
activateAdjblocks();
scrubbers.clear();
TileEntity[] tiles = new TileEntity[4];
tiles[0] = world.getTileEntity(pos.add(1,0,0));
tiles[1] = world.getTileEntity(pos.add(-1,0,0));
tiles[2] = world.getTileEntity(pos.add(0,0,1));
tiles[3] = world.getTileEntity(pos.add(0,0,-1));
for(TileEntity tile : tiles) {
if(tile instanceof TileCO2Scrubber && world.getBlockState(tile.getPos()).getBlock() == AdvancedRocketryBlocks.blockOxygenScrubber)
scrubbers.add((TileCO2Scrubber)tile);
}
}
private void activateAdjblocks() {
numScrubbers = 0;
numScrubbers = toggleAdjBlock(pos.add(1,0,0), true) ? numScrubbers + 1 : numScrubbers;
numScrubbers = toggleAdjBlock(pos.add(-1,0,0), true) ? numScrubbers + 1 : numScrubbers;
numScrubbers = toggleAdjBlock(pos.add(0,0,1), true) ? numScrubbers + 1 : numScrubbers;
numScrubbers = toggleAdjBlock(pos.add(0,0,-1), true) ? numScrubbers + 1 : numScrubbers;
}
private void deactivateAdjblocks() {
toggleAdjBlock(pos.add(1,0,0), false);
toggleAdjBlock(pos.add(-1,0,0), false);
toggleAdjBlock(pos.add(0,0,1), false);
toggleAdjBlock(pos.add(0,0,-1), false);
}
private boolean toggleAdjBlock(BlockPos pos, boolean on) {
IBlockState state = this.world.getBlockState(pos);
Block block = state.getBlock();
if(block == AdvancedRocketryBlocks.blockOxygenScrubber) {
((BlockTile)block).setBlockState(world, state, pos, on);
return true;
}
return false;
}
@Override
public void invalidate() {
super.invalidate();
AtmosphereHandler handler = AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension());
if(handler != null)
AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).unregisterBlob(this);
deactivateAdjblocks();
}
@Override
public int getPowerPerOperation() {
return (int)((numScrubbers*10 + 1)*Configuration.oxygenVentPowerMultiplier);
}
@Override
public boolean canFill( Fluid fluid) {
return FluidUtils.areFluidsSameType(fluid, AdvancedRocketryFluids.fluidOxygen) && super.canFill( fluid);
}
public boolean getEquivilentPower() {
if(state == RedstoneState.OFF)
return true;
boolean state2 = world.isBlockIndirectlyGettingPowered(pos) > 0;
if(state == RedstoneState.INVERTED)
state2 = !state2;
return state2;
}
@Override
public void performFunction() {
/*NB: canPerformFunction returns false and must return true for perform function to execute
* if there is no O2 handler, this is why we can safely call AtmosphereHandler.getOxygenHandler
* And not have to worry about an NPE being thrown
*/
//IF first tick then register the blob and check for scrubbers
if(!world.isRemote) {
if(firstRun) {
AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).registerBlob(this, pos);
onAdjacentBlockUpdated();
//isSealed starts as true so we can accurately check for scrubbers, we now set it to false to force the tile to check for a seal on first run
setSealed(false);
firstRun = false;
}
if(isSealed && AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).getBlobSize(this) == 0) {
deactivateAdjblocks();
setSealed(false);
}
if(isSealed && !getEquivilentPower()) {
AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).clearBlob(this);
deactivateAdjblocks();
setSealed(false);
}
else if(!isSealed && getEquivilentPower() && hasEnoughEnergy(getPowerPerOperation())) {
setSealed(AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).addBlock(this, new HashedBlockPosition(pos)));
if(isSealed) {
activateAdjblocks();
}
else if(world.getTotalWorldTime() % 10 == 0 && allowTrace) {
radius++;
if(radius > 128)
radius = 0;
}
}
if(isSealed) {
//If scrubbers exist and the config allows then use the cartridge
if(Configuration.scrubberRequiresCartrige){
//TODO: could be optimized
if(world.getTotalWorldTime() % 200 == 0) {
numScrubbers = 0;
for(TileCO2Scrubber scrubber : scrubbers) {
numScrubbers = scrubber.useCharge() ? numScrubbers + 1 : numScrubbers;
}
}
}
int amtToDrain = (int) (AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).getBlobSize(this)*getGasUsageMultiplier());
FluidStack drainedFluid = this.drain(amtToDrain, false);
if( (drainedFluid != null && drainedFluid.amount >= amtToDrain) || amtToDrain == 0) {
this.drain(amtToDrain, true);
if(!hasFluid) {
hasFluid = true;
activateAdjblocks();
AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).setAtmosphereType(this, AtmosphereType.PRESSURIZEDAIR);
}
}
else if(hasFluid){
AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension()).setAtmosphereType(this, DimensionManager.getInstance().getDimensionProperties(this.world.provider.getDimension()).getAtmosphere());
deactivateAdjblocks();
hasFluid = false;
}
}
}
}
@Override
public int getTraceDistance() {
return allowTrace ? radius : -1;
}
@Override
public void update() {
if(canPerformFunction()) {
if(hasEnoughEnergy(getPowerPerOperation())) {
performFunction();
if(!world.isRemote && isSealed) this.energy.extractEnergy(getPowerPerOperation(), false);
}
else
notEnoughEnergyForFunction();
}
else
radius = -1;
if(!soundInit && world.isRemote) {
LibVulpes.proxy.playSound(new RepeatingSound(AudioRegistry.airHissLoop, SoundCategory.BLOCKS, this));
}
soundInit = true;
}
private void setSealed(boolean sealed) {
boolean prevSealed = isSealed;
if((prevSealed != sealed)) {
markDirty();
world.notifyBlockUpdate(pos, world.getBlockState(pos), world.getBlockState(pos), 2);
if(isSealed)
radius = -1;
}
isSealed = sealed;
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
return new SPacketUpdateTileEntity(pos,getBlockMetadata(), getUpdateTag());
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
handleUpdateTag(pkt.getNbtCompound());
}
@Override
public NBTTagCompound getUpdateTag() {
NBTTagCompound tag = super.getUpdateTag();
tag.setBoolean("isSealed", isSealed);
return tag;
}
@Override
public void handleUpdateTag(NBTTagCompound tag) {
super.handleUpdateTag(tag);
isSealed = tag.getBoolean("isSealed");
if(isSealed) {
activateAdjblocks();
}
}
public float getGasUsageMultiplier() {
return (float) (Math.max(0.01f - numScrubbers*0.005f,0)*Configuration.oxygenVentConsumptionMult);
}
@Override
public void notEnoughEnergyForFunction() {
if(!world.isRemote) {
AtmosphereHandler handler = AtmosphereHandler.getOxygenHandler(this.world.provider.getDimension());
if(handler != null)
handler.clearBlob(this);
deactivateAdjblocks();
setSealed(false);
}
}
@Override
public int[] getSlotsForFace(EnumFacing side) {
return new int[]{};
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack itemStack) {
return false;
}
@Override
public boolean canBlobsOverlap(HashedBlockPosition blockPosition, AreaBlob blob) {
return false;
}
@Override
public int getMaxBlobRadius() {
return Configuration.oxygenVentSize;
}
@Override
public HashedBlockPosition getRootPosition() {
return new HashedBlockPosition(pos);
}
@Override
public List<ModuleBase> getModules(int ID, EntityPlayer player) {
ArrayList<ModuleBase> modules = new ArrayList<ModuleBase>();
modules.add(new ModulePower(18, 20, this));
modules.add(new ModuleLiquidIndicator(32, 20, this));
modules.add(redstoneControl);
modules.add(traceToggle);
//modules.add(toggleSwitch = new ModuleToggleSwitch(160, 5, 0, "", this, TextureResources.buttonToggleImage, 11, 26, getMachineEnabled()));
//TODO add itemStack slots for liqiuid
return modules;
}
@Override
public String getModularInventoryName() {
return "OxygenVent";
}
@Override
public boolean canInteractWithContainer(EntityPlayer entity) {
return true;
}
@Override
public boolean canFormBlob() {
return getEquivilentPower();
}
@Override
public boolean isRunning() {
return isSealed;
}
@Override
public void onInventoryButtonPressed(int buttonId) {
if(buttonId == PACKET_REDSTONE_ID) {
state = redstoneControl.getState();
PacketHandler.sendToServer(new PacketMachine(this, PACKET_REDSTONE_ID));
}
if(buttonId == PACKET_TRACE_ID) {
allowTrace = traceToggle.getState();
PacketHandler.sendToServer(new PacketMachine(this, PACKET_TRACE_ID));
}
}
@Override
public void writeDataToNetwork(ByteBuf out, byte id) {
if(id == PACKET_REDSTONE_ID)
out.writeByte(state.ordinal());
else if(id == PACKET_TRACE_ID)
out.writeBoolean(allowTrace);
}
@Override
public void readDataFromNetwork(ByteBuf in, byte packetId,
NBTTagCompound nbt) {
if(packetId == PACKET_REDSTONE_ID)
nbt.setByte("state", in.readByte());
else if(packetId == PACKET_TRACE_ID)
nbt.setBoolean("trace", in.readBoolean());
}
@Override
public void useNetworkData(EntityPlayer player, Side side, byte id,
NBTTagCompound nbt) {
if(id == PACKET_REDSTONE_ID)
state = RedstoneState.values()[nbt.getByte("state")];
else if(id == PACKET_TRACE_ID) {
allowTrace = nbt.getBoolean("trace");
if(!allowTrace)
radius = -1;
}
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
state = RedstoneState.values()[nbt.getByte("redstoneState")];
redstoneControl.setRedstoneState(state);
allowTrace = nbt.getBoolean("allowtrace");
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setByte("redstoneState", (byte) state.ordinal());
nbt.setBoolean("allowtrace", allowTrace);
return nbt;
}
@Override
public boolean isEmpty() {
return inventory.isEmpty();
}
@Override
public void stateUpdated(ModuleBase module) {
if(module.equals(traceToggle)) {
allowTrace = ((ModuleToggleSwitch)module).getState();
PacketHandler.sendToServer(new PacketMachine(this, PACKET_TRACE_ID));
}
}
} | mit |
YcheCourseProject/DIA-Umpire-Maven | DIA-Umpire/DIA-Umpire/src/MSUmpire/SpectrumParser/MzXMLthreadUnit.java | 2804 | /*
* Author: Chih-Chiang Tsou <chihchiang.tsou@gmail.com>
* Nesvizhskii Lab, Department of Computational Medicine and Bioinformatics,
* University of Michigan, Ann Arbor
*
* Copyright 2014 University of Michigan, Ann Arbor, MI
*
* 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 MSUmpire.SpectrumParser;
import MSUmpire.BaseDataStructure.InstrumentParameter;
import MSUmpire.BaseDataStructure.ScanData;
import MSUmpire.BaseDataStructure.SpectralDataType;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.zip.DataFormatException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
/**
* Thread unit for parsing one scan in mzXML file
*
* @author Chih-Chiang Tsou <chihchiang.tsou@gmail.com>
*/
public class MzXMLthreadUnit implements Runnable {
ReentrantReadWriteLock Lock = new ReentrantReadWriteLock();
public ScanData scan;
private String XMLtext;
private InstrumentParameter parameter;
boolean ReadPeak = true;
SpectralDataType.DataType dataType = SpectralDataType.DataType.DDA;
public MzXMLthreadUnit(String XMLtext, InstrumentParameter parameter, SpectralDataType.DataType dataType, boolean ReadPeak) {
this.XMLtext = XMLtext;
this.parameter = parameter;
this.ReadPeak = ReadPeak;
this.dataType = dataType;
}
public MzXMLthreadUnit(String XMLtext, InstrumentParameter parameter, SpectralDataType.DataType dataType) {
this.XMLtext = XMLtext;
this.parameter = parameter;
this.dataType = dataType;
}
private void Read() throws FileNotFoundException, IOException, ParserConfigurationException, SAXException, DataFormatException {
mzXMLReadUnit read = new mzXMLReadUnit(this.XMLtext);
this.scan = read.Parse();
this.XMLtext = null;
read = null;
}
@Override
public void run() {
try {
Read();
} catch (Exception ex) {
Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
}
scan.Preprocessing(parameter);
}
}
| mit |
TylerMcCraw/android-udacity-bigger | app/src/main/java/com/udacity/gradle/builditbigger/EndpointsAsyncTask.java | 2811 | package com.udacity.gradle.builditbigger;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.udacity.gradle.backend.jokeApi.JokeApi;
import java.io.IOException;
public class EndpointsAsyncTask extends AsyncTask<Boolean, Void, String> {
private static final String TAG = "EndpointsAsyncTask";
private static JokeApi mJokeService = null;
private Context context;
public EndpointsAsyncTask(Context context) {
this.context = context;
}
/**
* Execute an asynchronous background task to retrieve a joke from
* either a GCE local development server or a deployed/live GCE server
* @param params boolean true if to retrieve a joke from our deployed GCE server
* @return String joke
*/
@Override
protected String doInBackground(Boolean... params) {
if(mJokeService == null) { // Only do this once
JokeApi.Builder builder;
boolean deployedServer = params[0];
if (deployedServer) {
// GCE DEPLOYMENT
builder = new JokeApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl(context.getString(R.string.api_endpoint));
} else {
// LOCAL DEPLOYMENT
builder = new JokeApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
}
mJokeService = builder.build();
}
try {
return mJokeService.getJoke().execute().getJoke();
} catch (IOException e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
Log.d(TAG, "onPostExecute: result= " + result);
}
} | mit |
FlexTradeUKLtd/jfixture | jfixture/src/main/java/com/flextrade/jfixture/utility/IntegerPolyfill.java | 259 | package com.flextrade.jfixture.utility;
public class IntegerPolyfill {
/**
* @see Integer#compare(int, int) Integer.compare since Java 7
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
}
| mit |
hgrimberg01/BPlusTreeSim | src/edu/ku/eecs/db/APlusTree/InternalUnderflowException.java | 242 | /**
*
*/
package edu.ku.eecs.db.APlusTree;
/**
* @author QtotheC
*
*/
public class InternalUnderflowException extends Exception {
/**
*
*/
private static final long serialVersionUID = -6159625262928865710L;
}
| mit |
jvasileff/aos-servlet | src.java/org/anodyneos/servlet/multipart/MultipartHttpServletRequest.java | 3030 | /*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.anodyneos.servlet.multipart;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.anodyneos.servlet.multipart.commons.CommonsMultipartFile;
/**
* Provides additional methods for dealing with multipart content within a
* servlet request, allowing to access uploaded files.
* Implementations also need to override the standard
* {@link javax.servlet.ServletRequest} methods for parameter access, making
* multipart parameters available.
*
* <p>A concrete implementation is
* {@link org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest}.
* As an intermediate step,
* {@link org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest}
* can be subclassed.
*
* @author Juergen Hoeller
* @author Trevor D. Cook
* @since 29.09.2003
* @see MultipartResolver
* @see MultipartFile
* @see javax.servlet.http.HttpServletRequest#getParameter
* @see javax.servlet.http.HttpServletRequest#getParameterNames
* @see javax.servlet.http.HttpServletRequest#getParameterMap
* @see org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest
* @see org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest
*/
public interface MultipartHttpServletRequest extends HttpServletRequest {
/**
* Return an {@link java.util.Iterator} of String objects containing the
* parameter names of the multipart files contained in this request. These
* are the field names of the form (like with normal parameters), not the
* original file names.
* @return the names of the files
*/
Iterator<String> getFileNames();
/**
* Return the contents plus description of an uploaded file in this request,
* or <code>null</code> if it does not exist.
* @param name a String specifying the parameter name of the multipart file
* @return the uploaded content in the form of a {@link org.springframework.web.multipart.MultipartFile} object
*/
MultipartFile getFile(String name);
/**
* Return a {@link java.util.Map} of the multipart files contained in this request.
* @return a map containing the parameter names as keys, and the
* {@link org.springframework.web.multipart.MultipartFile} objects as values
* @see MultipartFile
*/
Map<String, CommonsMultipartFile> getFileMap();
}
| mit |
digital-crafting-habitat/dch_hack1ng_d4ys_workshop | 05_Ore_Solved/src/main/java/ItemCraftiumDust.java | 1193 | import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
/**
* Created by Rauca on 25.08.2015
*/
public class ItemCraftiumDust extends Item {
public static Item dustCraftium;
public ItemCraftiumDust() {
setUnlocalizedName("dustCraftium");
setCreativeTab(CreativeTabs.tabMaterials);
setTextureName(OreMod.MODID + ":craftium_dust");
}
public static void register() {
GameRegistry.registerItem(dustCraftium = new ItemCraftiumDust(), dustCraftium.getUnlocalizedName());
}
public static void addRecipes() {
addCraftingRecipes();
addOvenRecipes();
}
private static void addCraftingRecipes() {
GameRegistry.addRecipe(new ItemStack(dustCraftium), new Object[]{
" D ",
"DCD",
" D ",
'C', Items.redstone, 'D', Items.coal
});
}
public static void addOvenRecipes() {
GameRegistry.addSmelting(new ItemStack(OreCraftium.oreCraftium), new ItemStack(dustCraftium, 2), 2.0F);
}
}
| mit |
frustra/Feather | src/org/frustra/feather/injectors/PlayerJoinedInjector.java | 1197 | package org.frustra.feather.injectors;
import java.util.List;
import org.frustra.feather.server.Bootstrap;
import org.frustra.filament.HookUtil;
import org.frustra.filament.hooking.BadHookException;
import org.frustra.filament.hooking.FilamentClassNode;
import org.frustra.filament.injection.ClassInjector;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
public class PlayerJoinedInjector extends ClassInjector {
public boolean match(FilamentClassNode node) throws BadHookException {
return node.matches("PlayerHandler");
}
@SuppressWarnings("unchecked")
public void inject(FilamentClassNode node) throws BadHookException {
for (MethodNode method : (List<MethodNode>) node.methods) {
if (HookUtil.compareMethodNode(method, "PlayerHandler.playerJoined")) {
InsnList iList = new InsnList();
iList.add(new VarInsnNode(Opcodes.ALOAD, 2));
iList.add(HookUtil.createMethodInsnNode(Opcodes.INVOKESTATIC, Bootstrap.class, "playerJoined", void.class, Object.class));
method.instructions.insertBefore(method.instructions.getLast(), iList);
break;
}
}
}
}
| mit |
PuyallupFoursquare/ccb-api-client-java | src/main/java/com/p4square/ccbapi/serializer/PhoneFormSerializer.java | 724 | package com.p4square.ccbapi.serializer;
import com.p4square.ccbapi.model.Phone;
/**
* Encode a Phone object as form data for CCB.
*/
public class PhoneFormSerializer extends AbstractFormSerializer<Phone> {
@Override
public void encode(final Phone phone, final FormBuilder builder) {
// Sanity check.
if (phone.getType() == null) {
throw new IllegalArgumentException("Phone type cannot be null");
}
final String key;
if (phone.getType() == Phone.Type.EMERGENCY) {
key = "phone_emergency";
} else {
key = phone.getType().toString().toLowerCase() + "_phone";
}
builder.appendField(key, phone.getNumber());
}
}
| mit |
D3adspaceEnterprises/skylla | commons/src/main/java/de/d3adspace/skylla/commons/listener/PacketListenerContainer.java | 264 | package de.d3adspace.skylla.commons.listener;
import de.d3adspace.skylla.commons.packet.PacketContext;
import de.d3adspace.skylla.protocol.packet.Packet;
public interface PacketListenerContainer {
void callEvent(PacketContext packetContext, Packet packet);
}
| mit |
bluepangolin55/IMP | src/file/Image_Layer.java | 1282 | package file;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class Image_Layer extends Layer{
public BufferedImage image;
public Image_Layer(int width, int height, int imageType, String nameT,
Img mother_image) {
super(width, height, imageType, nameT, mother_image);
image=new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
Graphics g=image.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
}
@Override
public void setTransparency(int t) {
super.setTransparency(t);
int alpha = t;
for (int cx=0;cx<image.getWidth();cx++) {
for (int cy=0;cy<image.getHeight();cy++) {
int rgb = image.getRGB(cx, cy);
Color color = new Color(rgb);
color = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
image.setRGB(cx, cy, color.getRGB());
}
}
}
@Override
public void set_image(BufferedImage new_image) {
super.set_image(new_image);
image=new_image;
}
@Override
public BufferedImage get_image() {
return image;
}
@Override
public void draw(Graphics g, int x, int y, int w, int h) {
g.drawImage(image, x, y, w, h, null);
}
}
| mit |
danteteam/VKUniversity-Android-App | app/src/main/java/com/dantelab/testvkapplication/chat/adapter/ChatMessageImageViewHolder.java | 1361 | package com.dantelab.testvkapplication.chat.adapter;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.dantelab.testvkapplication.R;
import com.squareup.picasso.Picasso;
import com.vk.sdk.api.model.VKApiMessage;
import com.vk.sdk.api.model.VKApiPhoto;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by ivanbrazhnikov on 20.01.16.
*/
public class ChatMessageImageViewHolder extends ChatMessageViewHolder {
public static ChatMessageImageViewHolder newInstance(LayoutInflater inflater, ViewGroup parent) {
return new ChatMessageImageViewHolder(inflater.inflate(R.layout.list_item_chat_message_photo, parent, false));
}
@Bind(R.id.attachment_image)
ImageView attachmentImageView;
public ChatMessageImageViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
@Override
protected View viewForLayout() {
return attachmentImageView;
}
public void loadPhoto(VKApiPhoto photo) {
attachmentImageView.setImageDrawable(null);
Picasso.with(attachmentImageView.getContext()).load(Uri.parse(photo.photo_130)).into(attachmentImageView);
}
}
| mit |
bzyx/AntenneE | AntenneE/build/source/r/debug/pl/bzyx/antennee/R.java | 2704 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package pl.bzyx.antennee;
public final class R {
public static final class attr {
}
public static final class dimen {
/** From: file:/home/bzyx/AndroidStudioProjects/AntenneEProject/AntenneE/src/main/res/values/dimens.xml
From: file:/home/bzyx/AndroidStudioProjects/AntenneEProject/AntenneE/src/main/res/values-sw720dp-land/dimens.xml
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int action_settings=0x7f080006;
public static final int button=0x7f080003;
public static final int button2=0x7f080004;
public static final int chronometer=0x7f080005;
public static final int spinner=0x7f080001;
public static final int textView=0x7f080000;
public static final int textView2=0x7f080002;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int main=0x7f070000;
}
public static final class string {
/** From: file:/home/bzyx/AndroidStudioProjects/AntenneEProject/AntenneE/src/main/res/values/strings.xml
*/
public static final int action_settings=0x7f050000;
public static final int app_name=0x7f050001;
public static final int clickmeButton=0x7f050002;
public static final int hello_world=0x7f050003;
}
public static final class style {
/** From: file:/home/bzyx/AndroidStudioProjects/AntenneEProject/AntenneE/src/main/res/values/styles.xml
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
From: file:/home/bzyx/AndroidStudioProjects/AntenneEProject/AntenneE/src/main/res/values-v11/styles.xml
API 11 theme customizations can go here.
From: file:/home/bzyx/AndroidStudioProjects/AntenneEProject/AntenneE/src/main/res/values-v14/styles.xml
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| mit |
Evan1120/wechat-api-java | src/main/java/com/evan/wechat/event/SubscribeEvent.java | 83 | package com.evan.wechat.event;
public class SubscribeEvent extends BaseEvent {
} | mit |
lazokin/CollaboratingRobots | src/automation/BotAutomator.java | 254 | package automation;
import simulator.interfaces.SimAutomator;
public class BotAutomator {
private SimAutomator simAutomator;
public BotAutomator(SimAutomator simAutomator) {
super();
this.simAutomator = simAutomator;
}
}
| mit |
scaffeinate/crack-the-code | geeks-for-geeks/src/tree/SmallestSubTreeDeepestNodes.java | 1331 | package tree;
import java.util.List;
/**
* Question: https://www.glassdoor.com/Interview/Find-the-shortest-subtree-that-consist-of-all-the-deepest-nodes-The-tree-is-not-binary-QTN_1409104.htm
*/
public class SmallestSubTreeDeepestNodes {
public MultiTreeNode smallestSubTree(MultiTreeNode root) {
int maxHeight = maxHeight(root) - 1;
return smallestSubTree(root, 0, maxHeight);
}
private int maxHeight(MultiTreeNode root) {
if (root == null) return 0;
int max = 0;
List<MultiTreeNode> children = root.children;
for (MultiTreeNode child : children) {
max = Math.max(max, maxHeight(child));
}
return max + 1;
}
private MultiTreeNode smallestSubTree(MultiTreeNode root, int currentHeight, int maxHeight) {
if (root == null) return null;
if (currentHeight == maxHeight) return root;
List<MultiTreeNode> children = root.children;
int count = 0;
MultiTreeNode result = null;
for (MultiTreeNode child : children) {
MultiTreeNode res = smallestSubTree(child, currentHeight + 1, maxHeight);
if (res != null) {
count++;
result = res;
}
}
return (count == 0) ? null : ((count > 1) ? root : result);
}
}
| mit |
reatkin2/karyotyper | src/idiogram/Idiogram.java | 3081 | package idiogram;
import java.util.Collection;
import java.util.LinkedList;
import characterization.ChromosomeBand;
import basic_objects.Chromosome;
public class Idiogram {
private LinkedList<ChromosomeBand> myBands;
private int length;
private int chromosomeNumber;
private int resolution;
public Idiogram() {
this.myBands = new LinkedList<ChromosomeBand>();
this.length = 0;
this.chromosomeNumber = 0;
}
public Idiogram(Idiogram i) {
this.length = i.length();
this.myBands = i.getBands();
this.chromosomeNumber = i.getChromosomeNumber();
}
public Idiogram(Collection<ChromosomeBand> c) {
this();
this.addAll(c);
}
public int length() {
return length;
}
public ChromosomeBand get(int index) {
return this.myBands.get(index);
}
public boolean add(ChromosomeBand newBand) {
this.length += newBand.length();
return this.myBands.add(newBand);
}
public void add(int index, ChromosomeBand newBand) {
this.length += newBand.length();
this.myBands.add(index, newBand);
}
public boolean addAll(Collection<ChromosomeBand> c) {
for (ChromosomeBand band : c) {
this.length += band.length();
this.myBands.add(band);
}
return true;
}
public void addAll(int index, Collection<ChromosomeBand> c) {
for (ChromosomeBand band : c) {
this.length += band.length();
this.myBands.add(band);
}
}
@SuppressWarnings("unchecked")
public LinkedList<ChromosomeBand> getBands() {
return (LinkedList<ChromosomeBand>) this.myBands.clone();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + length;
result = prime * result + ((myBands == null) ? 0 : myBands.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass() || obj.getClass() != Chromosome.class)
return false;
Idiogram other = (Idiogram) obj;
if (length != other.length)
return false;
if (myBands == null) {
if (other.myBands != null)
return false;
} else if (!myBands.equals(other.myBands))
return false;
return true;
}
public int getChromosomeNumber() {
return chromosomeNumber;
}
public void setChromosomeNumber(int number) {
chromosomeNumber = number;
}
/**
* @return the resolution
*/
public int getResolution() {
return resolution;
}
/**
* @param resolution the resolution to set
*/
public void setResolution(int resolution) {
this.resolution = resolution;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String bandString = "";
for (ChromosomeBand band : myBands) {
bandString += "(" + band.type() + ", " + band.length() + ")";
}
return "Idiogram [myBands= [" + bandString + "], length=" + length + ", chromosomeNumber="
+ chromosomeNumber + ", resolution=" + resolution + "]";
}
} | mit |
owwlo/Courier.Android | src/com/owwlo/courier/s/CourierSService.java | 11415 | package com.owwlo.courier.s;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.owwlo.courier.db.CourierDatabaseHelper.ERROR_DETECT;
import com.owwlo.courier.s.Constants.SMS;
import com.owwlo.courier.s.poster.MessagePosterManager;
import com.owwlo.courier.s.utils.Utils;
public class CourierSService extends Service {
private static final String TAG = "CourierSService";
public static Context sContext;
private ServiceBinder mBinder = new ServiceBinder();
private Handler mHandler = new Handler();
private ContentObserver mObserver;
private Timer mBroadcastTimer = new Timer();
private TimerTask mBroadcastTimerTask = new TimerTask() {
@Override
public void run() {
if (mMessagePosterManager.isConnectedToHost()) {
mBroadcastTimer.cancel();
return;
}
(new BroadCastHelloMessage(BroadCastHelloMessage.TYPE_KNOCKDOOR))
.execute((Void[]) null);
}
};
private MessagePosterManager mMessagePosterManager;
private InetAddress mLastAddress = null;
private static String AUTH_CODE;
private List<AuthcodeListener> mAuthcodeListeners =
Collections.synchronizedList(new ArrayList<AuthcodeListener>());
public static final String EXTRA_ACTION = "extra_action";
public static final String BROADCAST_HELLO_MESSAGE = "broadcast_hello_message";
public CourierSService() {
Log.i(TAG, "class loaded.");
MessagePosterManager.init(this);
mMessagePosterManager = MessagePosterManager.getInstance();
}
private void addSMSObserver() {
sContext = getApplicationContext();
Log.i("CourierSService", "add a SMS observer. ");
ContentResolver localContentResolver = getContentResolver();
mObserver = new SMSObserver(getApplicationContext(),
localContentResolver, new SMSHandler(this));
localContentResolver.registerContentObserver(SMS.CONTENT_URI, true,
mObserver);
}
public final String getAuthCode() {
return AUTH_CODE;
}
public String getSystemTime() {
Time localTime = new Time();
localTime.setToNow();
return localTime.toString();
}
public IBinder onBind(Intent paramIntent) {
Log.i("CourierSService", "start IBinder~~~");
return mBinder;
}
public void onCreate() {
Log.i("CourierSService", "start onCreate~~~");
}
private boolean checkLastSession() {
Cursor cursor = sContext.getContentResolver().query(
Constants.URI_LAST_CONNECT, null, null, null,
ERROR_DETECT.CONNECT_TIME + " desc limit 1");
if (cursor.getCount() < 1) {
return false;
}
cursor.moveToFirst();
final String ip = cursor.getString(cursor
.getColumnIndex(ERROR_DETECT.IP));
sContext.getContentResolver().delete(Constants.URI_LAST_CONNECT, null,
null);
cursor.close();
if (mMessagePosterManager.isConnectedToHost()) {
mBroadcastTimer.cancel();
return false;
}
(new BroadCastHelloMessage(BroadCastHelloMessage.TYPE_RECONNECT, ip))
.execute((Void[]) null);
return true;
}
public boolean onUnbind(Intent paramIntent) {
return super.onUnbind(paramIntent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "On receive command.");
addSMSObserver();
if (Utils.isLocalNetConnected(this)
&& !mMessagePosterManager.isConnectedToHost()) {
if (mLastAddress == null
|| mLastAddress != getLocalIPAddress().get(0)) {
generateAuthCode();
}
boolean isConnectLost = checkLastSession();
try {
mBroadcastTimer.scheduleAtFixedRate(mBroadcastTimerTask,
isConnectLost ? Constants.RECONNECT_TRY_VALID_TIME : 0,
Constants.BROADCAST_DELAY_TIME);
} catch (Exception e) {
Log.i(TAG, "schedule failed.");
}
}
return Service.START_STICKY;
}
public void generateAuthCode() {
Log.i(TAG, "Generate AuthCode.");
InetAddress ip = getLocalIPAddress().get(0);
byte[] ipBytes = ip.getAddress();
String ipHex = Utils.byteArrayToHexString(ipBytes);
String ipPart = ipHex.substring(ipHex.length() - 2);
String imxi = Utils.getIMXI(sContext);
if (TextUtils.isEmpty(imxi) || imxi.length() <= 4) {
imxi = "d92c"; // Magic Code!
}
String imxiPart = imxi.substring(imxi.length() - 4, imxi.length() - 2);
AUTH_CODE = ipPart.substring(0, 1).toUpperCase()
+ Utils.generateRandomAuthChar()
+ ipPart.substring(1, 2).toUpperCase()
+ Utils.generateRandomAuthChar() + imxiPart;
Log.d(TAG, "AuthCode: " + AUTH_CODE);
Toast.makeText(getApplicationContext(), AUTH_CODE, Toast.LENGTH_SHORT)
.show();
for (AuthcodeListener al : mAuthcodeListeners) {
al.onAuthcodeChanged(getAuthCode());
}
}
public class ServiceBinder extends Binder {
public CourierSService getService() {
return CourierSService.this;
}
}
private class BroadCastHelloMessage extends AsyncTask<Void, Void, Void> {
public static final int TYPE_KNOCKDOOR = 0;
public static final int TYPE_RECONNECT = 1;
private JSONObject sendObj;
private String mIp;
@Override
protected Void doInBackground(Void... params) {
List<InetAddress> ipList = getLocalIPAddress();
broadcastMessage(ipList);
return null;
}
public BroadCastHelloMessage(int type) {
this(type, null);
}
public BroadCastHelloMessage(int type, String ip) {
if (type == TYPE_RECONNECT && ip == null) {
throw new InvalidParameterException();
}
mIp = ip;
switch (type) {
case TYPE_KNOCKDOOR:
sendObj = buildKnockDoorJSON();
break;
case TYPE_RECONNECT:
sendObj = buildReconnectJSON();
break;
}
}
private void broadcastMessage(List<InetAddress> ipList) {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
socket.setBroadcast(true);
socket.setReuseAddress(true);
String message = Constants.COURIER_JSON_HEADER + sendObj;
byte[] data = message.getBytes("UTF-8");
Log.i(TAG, "Broadcast Message: " + message);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
DatagramPacket packet = new DatagramPacket(base64.getBytes(),
base64.getBytes().length);
InetAddress broadcastAddr = InetAddress
.getByName("255.255.255.255");
packet.setAddress(broadcastAddr);
packet.setPort(Constants.BROADCAST_PORT);
socket.send(packet);
Log.d(TAG, "Hello Message Broadcasted.");
} catch (SocketException e) {
Log.d(TAG, "Broadcast socket failed.");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "Broadcast packet sent failed.");
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
private JSONObject buildKnockDoorJSON() {
int port = mMessagePosterManager.getTcpListeningPort();
String imxi = Utils.getIMXI(sContext); // imxi could be ""
JSONObject json = new JSONObject();
try {
json.put(Constants.JSON_TYPE, Constants.JSON_TYPE_KNOCKDOOR);
json.put(Constants.JSON_PORT, port);
json.put(Constants.JSON_IMXI, imxi);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
private JSONObject buildReconnectJSON() {
int port = mMessagePosterManager.getTcpListeningPort();
String imxi = Utils.getIMXI(sContext); // imxi could be ""
JSONObject json = new JSONObject();
try {
json.put(Constants.JSON_TYPE, Constants.JSON_TYPE_RECONNECT);
// 这种情况下mIp不为空
json.put(Constants.JSON_RECONNECT_IP, mIp);
json.put(Constants.JSON_PORT, port);
json.put(Constants.JSON_IMXI, imxi);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
}
private ArrayList<InetAddress> getLocalIPAddress() {
ArrayList<InetAddress> ipList = new ArrayList<InetAddress>();
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() // TODO 暂时只支持IPv4协议
&& inetAddress instanceof Inet4Address) {
ipList.add(inetAddress);
}
}
}
} catch (SocketException ex) {
Log.i(TAG, ex.toString());
}
return ipList;
}
public static interface AuthcodeListener {
public void onAuthcodeChanged(String newAuthcode);
}
public void addAuthcodeListener(AuthcodeListener al) {
mAuthcodeListeners.add(al);
}
public void removeAuthcodeListener(AuthcodeListener al) {
mAuthcodeListeners.remove(al);
}
} | mit |
Lambda-3/Stargraph | stargraph-core/src/main/java/net/stargraph/core/index/Indexer.java | 2098 | package net.stargraph.core.index;
/*-
* ==========================License-Start=============================
* stargraph-core
* --------------------------------------------------------------------
* Copyright (C) 2017 Lambda^3
* --------------------------------------------------------------------
* 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.
* ==========================License-End===============================
*/
import net.stargraph.data.Indexable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Definition of an indexer.
*/
public interface Indexer {
void start();
void stop();
void load();
void load(boolean reset, int limit);
void awaitLoader() throws InterruptedException, TimeoutException, ExecutionException;
void awaitLoader(long time, TimeUnit unit) throws InterruptedException, TimeoutException, ExecutionException;
void index(Indexable data) throws InterruptedException;
void flush();
void deleteAll();
}
| mit |
github/codeql | java/ql/src/Performance/InefficientEmptyStringTest.java | 388 | // Inefficient version
class InefficientDBClient {
public void connect(String user, String pw) {
if (user.equals("") || "".equals(pw))
throw new RuntimeException();
...
}
}
// More efficient version
class EfficientDBClient {
public void connect(String user, String pw) {
if (user.length() == 0 || (pw != null && pw.length() == 0))
throw new RuntimeException();
...
}
}
| mit |
MontealegreLuis/movies | src/test/java/com/codeup/movies/jdbc/CategoriesMapperTest.java | 717 | /*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
package com.codeup.movies.jdbc;
import com.codeup.movies.Category;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class CategoriesMapperTest {
@Test
public void it_maps_correctly_a_category() {
CategoriesMapper mapper = new CategoriesMapper();
List<Object> values = new ArrayList<>();
values.addAll(Arrays.asList(6L, "horror"));
Category category = mapper.mapRow(values);
assertEquals(6L, category.id());
assertEquals("horror", category.name());
}
}
| mit |
mailosaur/mailosaur-java | src/main/java/com/mailosaur/models/Server.java | 1965 | package com.mailosaur.models;
import java.util.List;
import com.google.api.client.util.Key;
/**
* Mailosaur virtual SMTP/SMS server.
*/
public class Server {
/**
* Unique identifier for the server.
*/
@Key
private String id;
/**
* The name of the server.
*/
@Key
private String name;
/**
* Users (excluding administrators) who have access to the server (if it is restricted).
*/
@Key
private List<String> users;
/**
* The number of messages currently in the server.
*/
@Key
private Integer messages;
/**
* Gets the unique identifier of the server.
*
* @return The server ID.
*/
public String id() {
return this.id;
}
/**
* Gets the name of the server.
*
* @return The name of the server.
*/
public String name() {
return this.name;
}
/**
* Sets the name of the server.
*
* @param name The name of the server.
* @return the Server object itself.
*/
public Server withName(String name) {
this.name = name;
return this;
}
/**
* Gets the IDs of users who have access to the server (if it is restricted).
*
* @return The IDs of users who have access to the server (if it is restricted).
*/
public List<String> users() {
return this.users;
}
/**
* Sets the IDs of users who have access to the server (if it is restricted).
*
* @param users The IDs of users who have access to the server (if it is restricted).
* @return the Server object itself.
*/
public Server withUsers(List<String> users) {
this.users = users;
return this;
}
/**
* Gets the number of messages currently in the server.
*
* @return The number of messages currently in the server.
*/
public Integer messages() {
return this.messages;
}
}
| mit |
liufeiit/mysql-binlog-connector-java | src/main/java/com/mysql/binlog/event/deserialization/DeleteRowsEventDataDeserializer.java | 2677 | /*
* Copyright 2013 Stanley Shyiko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysql.binlog.event.deserialization;
import java.io.IOException;
import java.io.Serializable;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.mysql.binlog.event.DeleteRowsEventData;
import com.mysql.binlog.event.TableMapEventData;
import com.mysql.binlog.io.ByteArrayInputStream;
/**
* @author <a href="mailto:stanley.shyiko@gmail.com">Stanley Shyiko</a>
*/
public class DeleteRowsEventDataDeserializer extends AbstractRowsEventDataDeserializer<DeleteRowsEventData> {
private boolean mayContainExtraInformation;
public DeleteRowsEventDataDeserializer(Map<Long, TableMapEventData> tableMapEventByTableId) {
super(tableMapEventByTableId);
}
public DeleteRowsEventDataDeserializer setMayContainExtraInformation(boolean mayContainExtraInformation) {
this.mayContainExtraInformation = mayContainExtraInformation;
return this;
}
@Override
public DeleteRowsEventData deserialize(ByteArrayInputStream inputStream) throws IOException {
DeleteRowsEventData eventData = new DeleteRowsEventData();
eventData.setTableId(inputStream.readLong(6));
inputStream.readInteger(2); // reserved
if (mayContainExtraInformation) {
int extraInfoLength = inputStream.readInteger(2);
inputStream.skip(extraInfoLength - 2);
}
int numberOfColumns = inputStream.readPackedInteger();
eventData.setIncludedColumns(inputStream.readBitSet(numberOfColumns, true));
eventData.setRows(deserializeRows(eventData.getTableId(), eventData.getIncludedColumns(), inputStream));
return eventData;
}
private List<Serializable[]> deserializeRows(long tableId, BitSet includedColumns, ByteArrayInputStream inputStream)
throws IOException {
List<Serializable[]> result = new LinkedList<Serializable[]>();
while (inputStream.available() > 0) {
result.add(deserializeRow(tableId, includedColumns, inputStream));
}
return result;
}
}
| mit |
petrs/ECTester | src/cz/crcs/ectester/reader/output/FileTestWriter.java | 1834 | package cz.crcs.ectester.reader.output;
import cz.crcs.ectester.common.output.TeeTestWriter;
import cz.crcs.ectester.common.output.TestWriter;
import javax.xml.parsers.ParserConfigurationException;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.regex.Pattern;
/**
* @author Jan Jancar johny@neuromancer.sk
*/
public class FileTestWriter extends TeeTestWriter {
private static final Pattern PREFIX = Pattern.compile("(text|xml|yaml|yml):.+");
public FileTestWriter(String defaultFormat, boolean systemOut, String[] files) throws ParserConfigurationException, FileNotFoundException {
int fLength = files == null ? 0 : files.length;
writers = new TestWriter[systemOut ? fLength + 1 : fLength];
if (systemOut) {
writers[0] = createWriter(defaultFormat, System.out);
}
for (int i = 0; i < fLength; ++i) {
String fName = files[i];
String format = null;
if (PREFIX.matcher(fName).matches()) {
String[] split = fName.split(":", 2);
format = split[0];
fName = split[1];
}
writers[i + 1] = createWriter(format, new PrintStream(new FileOutputStream(fName)));
}
}
private TestWriter createWriter(String format, PrintStream out) throws ParserConfigurationException {
if (format == null) {
return new TextTestWriter(out);
}
switch (format) {
case "text":
return new TextTestWriter(out);
case "xml":
return new XMLTestWriter(out);
case "yaml":
case "yml":
return new YAMLTestWriter(out);
default:
return null;
}
}
}
| mit |
RaiMan/SikuliX2 | src/main/java/com/sikulix/api/Text.java | 2704 | /*
* Copyright (c) 2017 - sikulix.com - MIT license
*/
package com.sikulix.api;
import com.sikulix.core.SX;
import com.sikulix.core.SXLog;
/**
* implements the API for text search and OCR features<br>
* holds all settings for a text feature processing<br>
* and the results of this processing<br>
* uses Core.TextFinder which implements the text features using Tesseract (via Tess4J)
*
*/
public class Text extends Element {
private static final SXLog log = SX.getSXLog("SX.Text");
private String searchText = null;
private String ocrText = null;
/**
* create a Text object with specific settings to be used later with read
*
* @param settings
*/
public Text(Object... settings) {
init(settings);
}
/**
* create a Text object with specific settings to be used later with find/findAll
*
* @param text
* @param settings
*/
public Text(String text, Object... settings) {
init(settings);
searchText = text;
}
private void init(Object... settings) {
//TODO what settings and how to process/store/access
}
/**
* OCR in the given Element according to the settings of this Text object
*
* @param where
* @return
*/
public Text read(Element where) {
//TODO read the text according to settings and fill ocrText
return this;
}
/**
* convenience: OCR in the given Element according to the standard settings
*
* @param where
* @param settings should be omitted (only to have a valid signature)
* @return
*/
public static Text read(Element where, Object... settings) {
return new Text().read(where);
}
/**
* find the searchText in the given Element
* according to the settings of this Text object
*
* @param where
* @return
*/
public Text find(Element where) {
//TODO search the text and fill lastMatch
return this;
}
/**
* convenience: find the given text in the given Element
* according to the standard settings
*
* @param text
* @param where
* @return
*/
public static Text find(String text, Element where) {
return new Text(text).find(where);
}
/**
* find all occurences of the searchText in the given Element
* according to the settings of this Text object
*
* @param where
* @return
*/
public Text findAll(Element where) {
//TODO search the text and fill lastMatches
return this;
}
/**
* convenience: find all occurences of the given text in the given Element
* according to the standard settings
*
* @param text
* @param where
* @return
*/
public static Text findAll(String text, Element where) {
return new Text(text).findAll(where);
}
}
| mit |
alisowsk/image-and-sound-processing | src/main/java/pl/lodz/p/ftims/poid/exercise1_2/operations/basic/Contrast.java | 1532 | package main.java.pl.lodz.p.ftims.poid.exercise1_2.operations.basic;
import main.java.pl.lodz.p.ftims.poid.exercise1_2.model.Image;
import main.java.pl.lodz.p.ftims.poid.exercise1_2.model.Pixel;
import main.java.pl.lodz.p.ftims.poid.exercise1_2.model.Pixel.RgbColor;
import main.java.pl.lodz.p.ftims.poid.exercise1_2.operations.Transformable;
import static main.java.pl.lodz.p.ftims.poid.exercise1_2.utils.ImageConstants.MAX_PIXEL_VALUE;
import static main.java.pl.lodz.p.ftims.poid.exercise1_2.utils.ImageConstants.MIDDLE_PIXEL_VALUE;
/**
* @author alisowsk
*/
public class Contrast implements Transformable {
private final float coefficient;
public Contrast(float coefficient) {
this.coefficient = coefficient;
}
@Override
public Image process(Image image) {
for (int x=0; x<image.getWidth(); x++){
for (int y=0; y<image.getHeight(); y++){
processSinglePixel(image.getPixel(x,y));
}
}
return image;
}
private void processSinglePixel(Pixel pixel) {
for(RgbColor color : RgbColor.values()){
pixel.setColor(color, processSingleColor(pixel.getColor(color)));
}
}
private int processSingleColor(int colorVal) {
float temp = coefficient * (colorVal - MIDDLE_PIXEL_VALUE) + MIDDLE_PIXEL_VALUE;
if (temp < 0) {
return 0;
} else if((0 <= temp) && (temp <= MAX_PIXEL_VALUE)) {
return (int) temp;
}
return MAX_PIXEL_VALUE;
}
}
| mit |
absentm/Demo | SpringBoot-demo/spring-boot-jpa-thymeleaf-curd/src/main/java/com/neo/JpaThymeleafApplication.java | 695 | package com.neo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@SpringBootApplication
public class JpaThymeleafApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(JpaThymeleafApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(JpaThymeleafApplication.class, args);
}
}
| mit |
armenis/SoftEng | SoftEng/src/Tests/TestUtils.java | 713 | package tests;
import java.awt.Component;
import java.awt.Container;
public class TestUtils {
public static Component getChildNamed(Component parent, String name) {
// Debug line
//System.out.println("Class: " + parent.getClass() +" Name: " + parent.getName());
if (name.equals(parent.getName())) { return parent; }
if (parent instanceof Container) {
Component[] children = ((Container)parent).getComponents();
for (int i = 0; i < children.length; ++i) {
Component child = getChildNamed(children[i], name);
if (child != null) { return child; }
}
}
return null;
}
}
| mit |
detienne11/imie | tp-poo/src/fr/imie/training/cdi13/dav/tpuml/observer/Car.java | 343 | package fr.imie.training.cdi13.dav.tpuml.observer;
import java.util.Observable;
public class Car extends Vehicle {
public Car(){
super();
}
public Car(Observable observable){
super(observable);
}
@Override
public void update(Observable o, Object arg) {
System.out.println("Update Car :" + arg);
}
}
| mit |
xvik/guice-persist-orient | src/main/java/ru/vyarus/guice/persist/orient/repository/delegate/ext/connection/ConnectionParamExtension.java | 2414 | package ru.vyarus.guice.persist.orient.repository.delegate.ext.connection;
import ru.vyarus.guice.persist.orient.repository.core.spi.parameter.MethodParamExtension;
import ru.vyarus.guice.persist.orient.repository.core.spi.parameter.ParamInfo;
import ru.vyarus.guice.persist.orient.repository.delegate.param.DelegateParamsContext;
import ru.vyarus.guice.persist.orient.repository.delegate.spi.DelegateExtension;
import ru.vyarus.guice.persist.orient.repository.delegate.spi.DelegateMethodDescriptor;
import javax.inject.Singleton;
import java.util.List;
import static ru.vyarus.guice.persist.orient.repository.core.MethodDefinitionException.check;
import static ru.vyarus.guice.persist.orient.repository.core.MethodExecutionException.checkExec;
/**
* {@link ru.vyarus.guice.persist.orient.repository.delegate.ext.connection.Connection} parameter annotation extension.
*
* @author Vyacheslav Rusakov
* @since 06.02.2015
*/
@Singleton
public class ConnectionParamExtension implements MethodParamExtension<DelegateMethodDescriptor,
DelegateParamsContext, Connection>, DelegateExtension<DelegateMethodDescriptor> {
private static final String KEY = ConnectionParamExtension.class.getName();
@Override
public void processParameters(final DelegateMethodDescriptor descriptor,
final DelegateParamsContext context,
final List<ParamInfo<Connection>> paramsInfo) {
check(paramsInfo.size() == 1, "Duplicate @%s parameter", Connection.class.getSimpleName());
final ParamInfo<Connection> paramInfo = paramsInfo.get(0);
descriptor.extDescriptors.put(KEY, paramInfo.position);
}
@Override
public void amendParameters(final DelegateMethodDescriptor descriptor, final Object[] targetArgs,
final Object instance, final Object... arguments) {
final Integer position = (Integer) descriptor.extDescriptors.get(KEY);
final Class<?> methodConnType = descriptor.method.getParameterTypes()[position];
final Object connection = descriptor.executor.getConnection();
checkExec(methodConnType.isAssignableFrom(connection.getClass()),
"Bad connection type declared %s, when actual is %s",
methodConnType.getSimpleName(), connection.getClass().getSimpleName());
targetArgs[position] = connection;
}
}
| mit |
feelinglucky/Gojuon | src/com/gracecode/android/gojuon/helper/ViewHelper.java | 1763 | package com.gracecode.android.gojuon.helper;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
/**
* Created with IntelliJ IDEA.
* <p/>
* User: mingcheng
* Date: 15/4/16
*/
final public class ViewHelper {
public static Animator getFadeOutAnimator(View view, int duration) {
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
animator.setDuration((long) (duration));
return animator;
}
public static Animator getFadeInAnimator(View view, int duration) {
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f);
animator.setDuration((long) (duration));
return animator;
}
public static Animator getScaleAnimator(final View view, float from, float to, int duration) {
ValueAnimator animator = ValueAnimator.ofFloat(from, to);
animator.setDuration(duration);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float i = (float) valueAnimator.getAnimatedValue();
view.setScaleX(i);
view.setScaleY(i);
}
});
return animator;
}
public static int getActivityWidth(Activity activity) {
View view = activity.findViewById(android.R.id.content);
if (view != null) {
return view.getWidth();
} else {
return 0;
}
}
}
| mit |
dave90/ANDLV | app/src/main/java/it/unical/mat/andlv/utils/TimeTracker.java | 539 | package it.unical.mat.andlv.utils;
import java.util.Calendar;
import java.util.logging.Logger;
/**
* Created by Stefano on 16/09/2015.
*/
public class TimeTracker {
private final static Logger LOGGER = Logger.getLogger(TimeTracker.class.getName());
private final static boolean ACTIVE = true;
public static void logTime(String message) {
if (ACTIVE)
// LOGGER.info(message + ":" + Calendar.getInstance().get(Calendar.MILLISECOND));
LOGGER.info(message + ":" + System.nanoTime());
}
}
| mit |
bladestery/Sapphire | example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/io/image/UtilImageIO.java | 16172 | /*
* Copyright (c) 2011-2016, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.io.image;
import boofcv.struct.image.*;
import org.ddogleg.struct.GrowQueue_I8;
import sun.awt.image.ByteInterleavedRaster;
import sun.awt.image.IntegerInterleavedRaster;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.net.URL;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.List;
/**
* Class for loading and saving images.
*
* @author Peter Abeles
*/
public class UtilImageIO {
/**
* A function that load the specified image. If anything goes wrong it returns a
* null.
*/
public static BufferedImage loadImage(String fileName) {
BufferedImage img;
try {
img = ImageIO.read(new File(fileName));
if( img == null) {
if( fileName.endsWith("ppm") || fileName.endsWith("PPM") ) {
return loadPPM(fileName,null);
} else if( fileName.endsWith("pgm") || fileName.endsWith("PGM") ) {
return loadPGM(fileName, null);
}
}
} catch (IOException e) {
return null;
}
return img;
}
public static BufferedImage loadImage(String directory , String fileName) {
return loadImage(new File(directory,fileName).getPath());
}
/**
* Loads all the image in the specified directory which match the provided regex
* @param directory File directory
* @param regex Regex used to match file names
* @return List of found images.
*/
public static List<BufferedImage> loadImages( String directory , final String regex ) {
File[] files = new File(directory).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.matches(regex);
}
});
List<BufferedImage> ret = new ArrayList<>();
for( File f : files ) {
BufferedImage img = loadImage(f.getAbsolutePath());
if( img != null )
ret.add( img );
}
return ret;
}
/**
* A function that load the specified image. If anything goes wrong it returns a
* null.
*/
public static BufferedImage loadImage(URL fileName) {
BufferedImage img;
try {
img = ImageIO.read(fileName);
} catch (IOException e) {
return null;
}
return img;
}
/**
* Loads the image and converts into the specified image type.
*
* @param fileName Path to image file.
* @param imageType Type of image that should be returned.
* @return The image or null if the image could not be loaded.
*/
public static <T extends ImageGray> T loadImage(String fileName, Class<T> imageType ) {
BufferedImage img = loadImage(fileName);
if( img == null )
return null;
return ConvertBufferedImage.convertFromSingle(img, (T) null, imageType);
}
public static <T extends ImageGray> T loadImage(String directory , String fileName, Class<T> imageType ) {
return loadImage(new File(directory,fileName).getPath(),imageType);
}
public static <T extends ImageBase> T loadImage( File image, boolean orderRgb, ImageType<T> imageType ) {
BufferedImage img = loadImage(image.getAbsolutePath());
if( img == null )
return null;
T output = imageType.createImage(img.getWidth(),img.getHeight());
ConvertBufferedImage.convertFrom(img, orderRgb, output);
return output;
}
/**
* Saves the {@link BufferedImage} to the specified file. The image type of the output is determined by
* the name's extension. By default the file is saved using {@link ImageIO#write(RenderedImage, String, File)}}
* but if that fails then it will see if it can save it using BoofCV native code for PPM and PGM.
*
* @param img Image which is to be saved.
* @param fileName Name of the output file. The type is determined by the extension.
*/
public static void saveImage(BufferedImage img, String fileName) {
try {
String type;
String a[] = fileName.split("[.]");
if (a.length > 0) {
type = a[a.length - 1];
} else {
type = "jpg";
}
if( !ImageIO.write(img, type, new File(fileName)) ) {
if( fileName.endsWith("ppm") || fileName.endsWith("PPM") ) {
Planar<GrayU8> color = ConvertBufferedImage.convertFromMulti(img,null,true,GrayU8.class);
savePPM(color, fileName, null);
} else if( fileName.endsWith("pgm") || fileName.endsWith("PGM") ) {
GrayU8 gray = ConvertBufferedImage.convertFrom(img, (GrayU8) null);
savePGM(gray, fileName);
}else
throw new IllegalArgumentException("No writer appropriate found");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
*
* <p>Saves the BoofCV formatted image. This is identical to the following code:</p>
*
* <pre>
* BufferedImage out = ConvertBufferedImage.convertTo(image,null,true);
* saveImage(out,fileName);
* </pre>
*
* @param image Image which is to be saved.
* @param fileName Name of the output file. The type is determined by the extension.
*/
public static void saveImage( ImageBase image , String fileName ) {
BufferedImage out = ConvertBufferedImage.convertTo(image,null,true);
saveImage(out,fileName);
}
/**
* Loads a PPM image from a file.
*
* @param fileName Location of PPM image
* @param storage (Optional) Storage for output image. Must be the width and height of the image being read.
* Better performance of type BufferedImage.TYPE_INT_RGB. If null or width/height incorrect a new image
* will be declared.
* @return The read in image
* @throws IOException
*/
public static BufferedImage loadPPM( String fileName , BufferedImage storage ) throws IOException {
return loadPPM(new FileInputStream(fileName),storage);
}
/**
* Loads a PGM image from a file.
*
* @param fileName Location of PGM image
* @param storage (Optional) Storage for output image. Must be the width and height of the image being read.
* Better performance of type BufferedImage.TYPE_BYTE_GRAY. If null or width/height incorrect a new image
* will be declared.
* @return The read in image
* @throws IOException
*/
public static BufferedImage loadPGM( String fileName , BufferedImage storage ) throws IOException {
return loadPGM(new FileInputStream(fileName), storage);
}
/**
* Loads a PPM image from an {@link InputStream}.
*
* @param inputStream InputStream for PPM image
* @param storage (Optional) Storage for output image. Must be the width and height of the image being read.
* Better performance of type BufferedImage.TYPE_INT_RGB. If null or width/height incorrect a new image
* will be declared.
* @return The read in image
* @throws IOException
*/
public static BufferedImage loadPPM( InputStream inputStream , BufferedImage storage ) throws IOException {
DataInputStream in = new DataInputStream(inputStream);
readLine(in);
String line = readLine(in);
while( line.charAt(0) == '#')
line = readLine(in);
String s[] = line.split(" ");
int w = Integer.parseInt(s[0]);
int h = Integer.parseInt(s[1]);
readLine(in);
if( storage == null || storage.getWidth() != w || storage.getHeight() != h )
storage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB );
int length = w*h*3;
byte[] data = new byte[length];
in.read(data,0,length);
boolean useFailSafe = storage.getType() != BufferedImage.TYPE_INT_RGB;
// try using the internal array for better performance
try {
int rgb[] = ((IntegerInterleavedRaster)storage.getRaster()).getDataStorage();
int indexIn = 0;
int indexOut = 0;
for( int y = 0; y < h; y++ ) {
for( int x = 0; x < w; x++ ) {
rgb[indexOut++] = ((data[indexIn++] & 0xFF) << 16) |
((data[indexIn++] & 0xFF) << 8) | (data[indexIn++] & 0xFF);
}
}
} catch( AccessControlException e ) {
useFailSafe = true;
}
if( useFailSafe ) {
// use the slow setRGB() function
int indexIn = 0;
for( int y = 0; y < h; y++ ) {
for( int x = 0; x < w; x++ ) {
storage.setRGB(x, y, ((data[indexIn++] & 0xFF) << 16) |
((data[indexIn++] & 0xFF) << 8) | (data[indexIn++] & 0xFF));
}
}
}
return storage;
}
/**
* Loads a PGM image from an {@link InputStream}.
*
* @param inputStream InputStream for PGM image
* @param storage (Optional) Storage for output image. Must be the width and height of the image being read.
* Better performance of type BufferedImage.TYPE_BYTE_GRAY. If null or width/height incorrect a new image
* will be declared.
* @return The read in image
* @throws IOException
*/
public static BufferedImage loadPGM( InputStream inputStream , BufferedImage storage ) throws IOException {
DataInputStream in = new DataInputStream(inputStream);
readLine(in);
String line = readLine(in);
while( line.charAt(0) == '#')
line = readLine(in);
String s[] = line.split(" ");
int w = Integer.parseInt(s[0]);
int h = Integer.parseInt(s[1]);
readLine(in);
if( storage == null || storage.getWidth() != w || storage.getHeight() != h )
storage = new BufferedImage(w,h,BufferedImage.TYPE_BYTE_GRAY );
int length = w*h;
byte[] data = new byte[length];
in.read(data,0,length);
boolean useFailSafe = storage.getType() != BufferedImage.TYPE_BYTE_GRAY;
// try using the internal array for better performance
try {
byte gray[] = ((ByteInterleavedRaster)storage.getRaster()).getDataStorage();
int indexIn = 0;
int indexOut = 0;
for( int y = 0; y < h; y++ ) {
for( int x = 0; x < w; x++ ) {
gray[indexOut++] = data[indexIn++];
}
}
} catch( AccessControlException e ) {
useFailSafe = true;
}
if( useFailSafe ) {
// use the slow setRGB() function
int indexIn = 0;
for( int y = 0; y < h; y++ ) {
for( int x = 0; x < w; x++ ) {
int gray = data[indexIn++] & 0xFF;
storage.setRGB(x, y, gray << 16 | gray << 8 | gray );
}
}
}
return storage;
}
/**
* Reads a PPM image file directly into a Planar<GrayU8> image. To improve performance when reading
* many images, the user can provide work space memory in the optional parameters
*
* @param fileName Location of PPM file
* @param storage (Optional) Where the image is written in to. Will be resized if needed.
* If null or the number of bands isn't 3, a new instance is declared.
* @param temp (Optional) Used internally to store the image. Can be null.
* @return The image.
* @throws IOException
*/
public static Planar<GrayU8> loadPPM_U8(String fileName , Planar<GrayU8> storage , GrowQueue_I8 temp )
throws IOException
{
return loadPPM_U8(new FileInputStream(fileName),storage,temp);
}
/**
* Reads a PPM image file directly into a Planar<GrayU8> image. To improve performance when reading
* many images, the user can provide work space memory in the optional parameters
*
* @param inputStream InputStream for PPM image
* @param storage (Optional) Where the image is written in to. Will be resized if needed.
* If null or the number of bands isn't 3, a new instance is declared.
* @param temp (Optional) Used internally to store the image. Can be null.
* @return The image.
* @throws IOException
*/
public static Planar<GrayU8> loadPPM_U8(InputStream inputStream, Planar<GrayU8> storage , GrowQueue_I8 temp )
throws IOException
{
DataInputStream in = new DataInputStream(inputStream);
readLine(in);
String line = readLine(in);
while( line.charAt(0) == '#')
line = readLine(in);
String s[] = line.split(" ");
int w = Integer.parseInt(s[0]);
int h = Integer.parseInt(s[1]);
readLine(in);
if( storage == null || storage.getNumBands() != 3 )
storage = new Planar<>(GrayU8.class,w,h,3 );
else
storage.reshape(w,h);
int length = w*h*3;
if( temp == null )
temp = new GrowQueue_I8(length);
temp.resize(length);
byte data[] = temp.data;
in.read(data,0,length);
GrayU8 band0 = storage.getBand(0);
GrayU8 band1 = storage.getBand(1);
GrayU8 band2 = storage.getBand(2);
int indexIn = 0;
for( int y = 0; y < storage.height; y++ ) {
int indexOut = storage.startIndex + y*storage.stride;
for( int x = 0; x < storage.width; x++ , indexOut++ ) {
band0.data[indexOut] = data[indexIn++];
band1.data[indexOut] = data[indexIn++];
band2.data[indexOut] = data[indexIn++];
}
}
return storage;
}
/**
* Loads a PGM image from an {@link InputStream}.
*
* @param fileName InputStream for PGM image
* @param storage (Optional) Storage for output image. Must be the width and height of the image being read.
* If null a new image will be declared.
* @return The read in image
* @throws IOException
*/
public static GrayU8 loadPGM_U8(String fileName , GrayU8 storage )
throws IOException
{
return loadPGM_U8(new FileInputStream(fileName),storage);
}
/**
* Loads a PGM image from an {@link InputStream}.
*
* @param inputStream InputStream for PGM image
* @param storage (Optional) Storage for output image. Must be the width and height of the image being read.
* If null a new image will be declared.
* @return The read in image
* @throws IOException
*/
public static GrayU8 loadPGM_U8(InputStream inputStream , GrayU8 storage ) throws IOException {
DataInputStream in = new DataInputStream(inputStream);
readLine(in);
String line = readLine(in);
while( line.charAt(0) == '#')
line = readLine(in);
String s[] = line.split(" ");
int w = Integer.parseInt(s[0]);
int h = Integer.parseInt(s[1]);
readLine(in);
if( storage == null )
storage = new GrayU8(w,h);
in.read(storage.data,0,w*h);
return storage;
}
/**
* Saves an image in PPM format.
*
* @param rgb 3-band RGB image
* @param fileName Location where the image is to be written to.
* @param temp (Optional) Used internally to store the image. Can be null.
* @throws IOException
*/
public static void savePPM(Planar<GrayU8> rgb , String fileName , GrowQueue_I8 temp ) throws IOException {
File out = new File(fileName);
DataOutputStream os = new DataOutputStream(new FileOutputStream(out));
String header = String.format("P6\n%d %d\n255\n", rgb.width, rgb.height);
os.write(header.getBytes());
if( temp == null )
temp = new GrowQueue_I8();
temp.resize(rgb.width*rgb.height*3);
byte data[] = temp.data;
GrayU8 band0 = rgb.getBand(0);
GrayU8 band1 = rgb.getBand(1);
GrayU8 band2 = rgb.getBand(2);
int indexOut = 0;
for( int y = 0; y < rgb.height; y++ ) {
int index = rgb.startIndex + y*rgb.stride;
for( int x = 0; x < rgb.width; x++ , index++) {
data[indexOut++] = band0.data[index];
data[indexOut++] = band1.data[index];
data[indexOut++] = band2.data[index];
}
}
os.write(data,0,temp.size);
os.close();
}
/**
* Saves an image in PGM format.
*
* @param gray Gray scale image
* @param fileName Location where the image is to be written to.
* @throws IOException
*/
public static void savePGM(GrayU8 gray , String fileName ) throws IOException {
File out = new File(fileName);
DataOutputStream os = new DataOutputStream(new FileOutputStream(out));
String header = String.format("P5\n%d %d\n255\n", gray.width, gray.height);
os.write(header.getBytes());
os.write(gray.data,0,gray.width*gray.height);
os.close();
}
private static String readLine( DataInputStream in ) throws IOException {
String s = "";
while( true ) {
int b = in.read();
if( b == '\n' )
return s;
else
s += (char)b;
}
}
}
| mit |
vinhnguyentb/skyline-queries | src/main/java/skylinequeries/rtree/Comparators.java | 3809 | package skylinequeries.rtree;
import rx.functions.Func1;
import skylinequeries.rtree.geometry.Geometry;
import skylinequeries.rtree.geometry.HasGeometry;
import skylinequeries.rtree.geometry.ListPair;
import skylinequeries.rtree.geometry.Rectangle;
import java.util.Comparator;
import java.util.List;
/**
* Utility functions asociated with {@link Comparator}s, especially for use with
* {@link Selector}s and {@link Splitter}s.
*/
public final class Comparators {
private Comparators() {
// prevent instantiation
}
public static final Comparator<ListPair<?>> overlapListPairComparator = toComparator(Functions.overlapListPair);
/**
* Compares the sum of the areas of two ListPairs.
*/
public static final Comparator<ListPair<?>> areaPairComparator = new Comparator<ListPair<?>>() {
@Override
public int compare(ListPair<?> p1, ListPair<?> p2) {
return ((Float) p1.areaSum()).compareTo(p2.areaSum());
}
};
/**
* Returns a {@link Comparator} that is a normal Double comparator for the
* total of the areas of overlap of the members of the list with the
* rectangle r.
*
* @param <T> type of geometry being compared
* @param r rectangle
* @param list geometries to compare with the rectangle
* @return the total of the areas of overlap of the geometries in the list
* with the rectangle r
*/
public static <T extends HasGeometry> Comparator<HasGeometry> overlapAreaComparator(
final Rectangle r, final List<T> list) {
return toComparator(Functions.overlapArea(r, list));
}
public static <T extends HasGeometry> Comparator<HasGeometry> areaIncreaseComparator(
final Rectangle r) {
return toComparator(Functions.areaIncrease(r));
}
public static Comparator<HasGeometry> areaComparator(final Rectangle r) {
return new Comparator<HasGeometry>() {
@Override
public int compare(HasGeometry g1, HasGeometry g2) {
return ((Float) g1.geometry().mbr().add(r).area()).compareTo(g2.geometry().mbr()
.add(r).area());
}
};
}
public static <R, T extends Comparable<T>> Comparator<R> toComparator(final Func1<R, T> function) {
return new Comparator<R>() {
@Override
public int compare(R g1, R g2) {
return function.call(g1).compareTo(function.call(g2));
}
};
}
public static <T> Comparator<T> compose(final Comparator<T>... comparators) {
return new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
for (Comparator<T> comparator : comparators) {
int value = comparator.compare(t1, t2);
if (value != 0)
return value;
}
return 0;
}
};
}
/**
* <p>
* Returns a comparator that can be used to sort entries returned by search
* methods. For example:
* </p>
* <p>
* <code>search(100).toSortedList(ascendingDistance(r))</code>
* </p>
*
* @param <T> the value type
* @param <S> the entry type
* @param r rectangle to measure distance to
* @return a comparator to sort by ascending distance from the rectangle
*/
public static <T, S extends Geometry> Comparator<Entry<T, S>> ascendingDistance(
final Rectangle r) {
return new Comparator<Entry<T, S>>() {
@Override
public int compare(Entry<T, S> e1, Entry<T, S> e2) {
return ((Double) e1.geometry().distance(r)).compareTo(e2.geometry().distance(r));
}
};
}
}
| mit |
Chris2011/Github-Repository-Viewer | RepositoryViewer/test/unit/src/org/chrisle/netbeans/modules/gitrepoviewer/repositories/UserRepositoryTest.java | 4453 | package org.chrisle.netbeans.modules.gitrepoviewer.repositories;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import org.chrisle.netbeans.modules.gitrepoviewer.beans.User;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
/**
*
* @author chrl
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({
Gson.class
})
public class UserRepositoryTest {
private UserRepository _userRepo;
private final Gson _gsonProvider = PowerMockito.mock(Gson.class);
private String _selectedHost;
private String _dirName;
private String _filePostfix;
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
public Reader _fileReader;
@Before
public void setUp() throws Exception {
// MockitoAnnotations.initMocks(this);
this._selectedHost = "Github";
this._filePostfix = "User.json";
}
/**
* Test of getUser method, of class UserRepository.
* @throws java.io.IOException
*/
// @Ignore
@Test
public void testGetUser() throws IOException {
System.out.println("getUser");
String expResult = "ChrisLE";
File tempFile = testFolder.newFile(this._selectedHost + this._filePostfix);
this._dirName = testFolder.getRoot().getPath();
this._fileReader = new FileReader(testFolder.getRoot().getPath() + "\\" + tempFile.getName());
this._userRepo = new UserRepository(this._gsonProvider, this._dirName);
this._userRepo.setFileReader(_fileReader);
this._userRepo.setSelectedHost(this._selectedHost);
Mockito.when(this._gsonProvider.fromJson(_fileReader, User.class)).thenReturn(new User("ChrisLE", "MyToken"));
User result = this._userRepo.getUser();
assertEquals(expResult, result.getUserName());
}
/**
* Test of getUser method, of class UserRepository.
* @throws java.io.FileNotFoundException
*/
// @Ignore
@Test(expected = FileNotFoundException.class)
public void testGetUserFileNotFound() throws FileNotFoundException {
System.out.println("getUserFileNotFound");
Mockito.when(this._gsonProvider.fromJson(new FileReader("Foooooooooooooooo.json"), User.class)).thenReturn(new User("ChrisLE", "MyToken"));
User result = this._userRepo.getUser();
}
/**
* Test of saveUser method, of class UserRepository.
* @throws java.lang.Exception
*/
@Test
public void testSaveUser() throws Exception {
// Save user:
System.out.println("saveUser");
String userName = "ChrisTest";
String authToken = "te8t9se9tst7etzts8";
User user = new User(userName, authToken);
File tempFile = testFolder.newFile(this._selectedHost + this._filePostfix);
this._dirName = testFolder.getRoot().getPath();
this._fileReader = new FileReader(testFolder.getRoot().getPath() + "\\" + tempFile.getName());
this._userRepo = new UserRepository(this._gsonProvider, this._dirName);
this._userRepo.setFileReader(_fileReader);
this._userRepo.setSelectedHost("Github");
Mockito.when(this._gsonProvider.toJson(user)).thenReturn("{\"_userName\":\"" + userName + "\",\"_authToken\":\"" + authToken + "\"}");
_userRepo.saveUser(user);
// Get user:
this._userRepo = new UserRepository(this._gsonProvider, this._dirName);
this._userRepo.setFileReader(_fileReader);
User newUser = new User("ChrisTest", "te8t9se9tst7etzts8");
Mockito.when(this._gsonProvider.fromJson(this._fileReader, User.class)).thenReturn(newUser);
User result = this._userRepo.getUser();
assertEquals(userName, result.getUserName());
assertEquals(authToken, result.getAuthToken());
}
} | mit |
lfmendivelso10/AppModernization | source/i1/KDM2Model/src/subkdm/kdmObjects/impl/CodeItemImpl.java | 716 | /**
*/
package subkdm.kdmObjects.impl;
import org.eclipse.emf.ecore.EClass;
import subkdm.kdmObjects.CodeItem;
import subkdm.kdmObjects.KdmObjectsPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Code Item</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class CodeItemImpl extends AbstractCodeElementImpl implements CodeItem {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CodeItemImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return KdmObjectsPackage.Literals.CODE_ITEM;
}
} //CodeItemImpl
| mit |
ramswaroop/Algorithms-and-Data-Structures-in-Java | src/main/java/com/rampatra/trees/TreeToList.java | 2085 | package com.rampatra.trees;
import com.rampatra.base.BinaryNode;
import com.rampatra.base.BinarySearchTree;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/26/15
* @time: 4:38 PM
*/
public class TreeToList<E extends Comparable<E>> extends BinarySearchTree<E> {
/**
* A recursive function that takes an ordered binary tree
* and rearranges the internal pointers to make a circular
* doubly linked list out of the tree nodes. The list should
* be arranged so that the nodes are in increasing order.
*/
public void treeToList() {
// print the list
printList(treeToList(root));
}
public static <E extends Comparable<E>> BinaryNode<E> treeToList(BinaryNode<E> node) {
if (node == null) return null;
BinaryNode<E> aList = treeToList(node.left);
BinaryNode<E> bList = treeToList(node.right);
node.left = node;
node.right = node;
// attach left child then root followed by right child (so that final list is in ascending order)
aList = addToList(aList, node);
aList = addToList(aList, bList);
return aList;
}
private static <E extends Comparable<E>> BinaryNode<E> addToList(BinaryNode<E> aList, BinaryNode<E> bList) {
if (aList == null) return bList;
if (bList == null) return aList;
// find the last node in each list
BinaryNode<E> aListLast = aList.left;
BinaryNode<E> bListLast = bList.left;
// join end of one list to beginning of another
aListLast.right = bList;
bList.left = aListLast;
// make circular
aListLast.left = bListLast;
bListLast.right = aList;
return aList;
}
public static void main(String[] args) {
BinarySearchTree<Integer> bst = new BinarySearchTree<>();
bst.put(6);
bst.put(3);
bst.put(5);
bst.put(7);
bst.put(8);
bst.put(9);
bst.inOrder();
// TODO incorrect results
bst.printList(treeToList(bst.root));
}
}
| mit |
gnomex/javando | src/br/github/gnomex/two_th_exercises/products_inventory/views/ProductsCRUD.java | 782 | package br.github.gnomex.two_th_exercises.products_inventory.views;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class ProductsCRUD {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProductsCRUD window = new ProductsCRUD();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ProductsCRUD() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
| mit |
jonestimd/neo4j-rest-java | src/main/java/io/github/jonestimd/neo4j/client/transaction/TransactionManager.java | 5665 | // The MIT License (MIT)
//
// Copyright (c) 2016 Tim Jones
//
// 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 io.github.jonestimd.neo4j.client.transaction;
import java.io.IOException;
import java.util.Timer;
import java.util.function.Supplier;
import com.fasterxml.jackson.core.JsonFactory;
import io.github.jonestimd.neo4j.client.http.HttpDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class can be used to create transactions and perform tasks within transactions. When a transaction is created,
* it is associated with the current thread, so nested calls to {@link #doInTransaction(TransactionCallback)} on the
* same thread will use the same transaction. If {@link #doInTransaction(TransactionCallback)} throws an exception
* then the transaction is rolled back. Otherwise, the transaction is committed when the outermost
* {@link #doInTransaction(TransactionCallback)} returns.
*/
public class TransactionManager {
private static final ThreadLocal<Transaction> TRANSACTION_HOLDER = new ThreadLocal<>();
private final Supplier<Transaction> transactionFactory;
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Create a transaction manager that uses the supplied parameters to create transactions. The driver and URL
* are required and the remaining parameters are optional.
* @param httpDriver the HTTP driver to use for requests
* @param baseUrl the base URL for the Neo4j transaction REST API
* @param jsonFactory factory for creating generators and parsers
* @param timer the timer to use for scheduling the keep alive task
* @param keepAliveMs the period of the keep alive requests in milliseconds
*/
public TransactionManager(HttpDriver httpDriver, String baseUrl, JsonFactory jsonFactory, Timer timer, long keepAliveMs) {
this(Transaction.factory(httpDriver, baseUrl, jsonFactory, timer, keepAliveMs));
}
/**
* Create a transaction manager using the supplied factory to create transactions.
* @param transactionFactory a factory that creates new transactions
*/
public TransactionManager(Supplier<Transaction> transactionFactory) {
this.transactionFactory = transactionFactory;
}
/**
* Get the transaction associated with the current thread.
* @return the transaction or {@code null} is there is no open transaction
*/
public static Transaction getTransaction() {
return TRANSACTION_HOLDER.get();
}
/**
* Run the {@code callback} in a transaction. If there is already a transaction associated with the current thread
* then that transaction is used. Otherwise, a new transaction is created, passed to the {@code callback} and
* committed or rolled back after the {@code callback} completes.
* @param callback the task to perform in the transaction
* @throws Exception
*/
public void runInTransaction(TransactionConsumer callback) throws Exception {
doInTransaction(transaction -> {
callback.accept(transaction);
return null;
});
}
/**
* Run the {@code callback} in a transaction. If there is already a transaction associated with the current thread
* then that transaction is used. Otherwise, a new transaction is created, passed to the {@code callback} and
* committed or rolled back after the {@code callback} completes.
* @param callback the task to perform in the transaction
* @param <T> the result type of the {@code callback}
* @return the result of {@code callback}
* @throws Exception
*/
public <T> T doInTransaction(TransactionCallback<T> callback) throws Exception {
Transaction transaction = TRANSACTION_HOLDER.get();
if (transaction == null) {
transaction = transactionFactory.get();
TRANSACTION_HOLDER.set(transaction);
try {
T result = callback.apply(transaction);
if (!transaction.isComplete()) {
transaction.commit();
}
return result;
} catch (Throwable ex) {
try {
if (!transaction.isComplete()) {
transaction.rollback();
}
} catch (IOException e) {
logger.error("transaction rollback failed", ex);
}
throw ex;
} finally {
TRANSACTION_HOLDER.remove();
}
}
else return callback.apply(transaction);
}
}
| mit |
fizzyman/FRC-Krawler-3.1.0-NoFirebase | app/src/main/java-gen/com/team2052/frckrawler/db/RobotEventDao.java | 9539 | package com.team2052.frckrawler.db;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
import de.greenrobot.dao.internal.SqlUtils;
import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "ROBOT_EVENT".
*/
public class RobotEventDao extends AbstractDao<RobotEvent, Long> {
public static final String TABLENAME = "ROBOT_EVENT";
/**
* Properties of entity RobotEvent.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Robot_id = new Property(1, long.class, "robot_id", false, "ROBOT_ID");
public final static Property Event_id = new Property(2, long.class, "event_id", false, "EVENT_ID");
public final static Property Data = new Property(3, String.class, "data", false, "DATA");
}
private DaoSession daoSession;
private Query<RobotEvent> event_RobotEventListQuery;
private Query<RobotEvent> robot_RobotEventListQuery;
public RobotEventDao(DaoConfig config) {
super(config);
}
public RobotEventDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
this.daoSession = daoSession;
}
/**
* Creates the underlying database table.
*/
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists ? "IF NOT EXISTS " : "";
db.execSQL("CREATE TABLE " + constraint + "\"ROBOT_EVENT\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE ," + // 0: id
"\"ROBOT_ID\" INTEGER NOT NULL ," + // 1: robot_id
"\"EVENT_ID\" INTEGER NOT NULL ," + // 2: event_id
"\"DATA\" TEXT);"); // 3: data
}
/**
* Drops the underlying database table.
*/
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"ROBOT_EVENT\"";
db.execSQL(sql);
}
/**
* @inheritdoc
*/
@Override
protected void bindValues(SQLiteStatement stmt, RobotEvent entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
stmt.bindLong(2, entity.getRobot_id());
stmt.bindLong(3, entity.getEvent_id());
String data = entity.getData();
if (data != null) {
stmt.bindString(4, data);
}
}
@Override
protected void attachEntity(RobotEvent entity) {
super.attachEntity(entity);
entity.__setDaoSession(daoSession);
}
/**
* @inheritdoc
*/
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
/**
* @inheritdoc
*/
@Override
public RobotEvent readEntity(Cursor cursor, int offset) {
RobotEvent entity = new RobotEvent( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.getLong(offset + 1), // robot_id
cursor.getLong(offset + 2), // event_id
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3) // data
);
return entity;
}
/**
* @inheritdoc
*/
@Override
public void readEntity(Cursor cursor, RobotEvent entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setRobot_id(cursor.getLong(offset + 1));
entity.setEvent_id(cursor.getLong(offset + 2));
entity.setData(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
}
/**
* @inheritdoc
*/
@Override
protected Long updateKeyAfterInsert(RobotEvent entity, long rowId) {
entity.setId(rowId);
return rowId;
}
/**
* @inheritdoc
*/
@Override
public Long getKey(RobotEvent entity) {
if (entity != null) {
return entity.getId();
} else {
return null;
}
}
/**
* @inheritdoc
*/
@Override
protected boolean isEntityUpdateable() {
return true;
}
/**
* Internal query to resolve the "robotEventList" to-many relationship of Event.
*/
public List<RobotEvent> _queryEvent_RobotEventList(long event_id) {
synchronized (this) {
if (event_RobotEventListQuery == null) {
QueryBuilder<RobotEvent> queryBuilder = queryBuilder();
queryBuilder.where(Properties.Event_id.eq(null));
event_RobotEventListQuery = queryBuilder.build();
}
}
Query<RobotEvent> query = event_RobotEventListQuery.forCurrentThread();
query.setParameter(0, event_id);
return query.list();
}
/**
* Internal query to resolve the "robotEventList" to-many relationship of Robot.
*/
public List<RobotEvent> _queryRobot_RobotEventList(long robot_id) {
synchronized (this) {
if (robot_RobotEventListQuery == null) {
QueryBuilder<RobotEvent> queryBuilder = queryBuilder();
queryBuilder.where(Properties.Robot_id.eq(null));
robot_RobotEventListQuery = queryBuilder.build();
}
}
Query<RobotEvent> query = robot_RobotEventListQuery.forCurrentThread();
query.setParameter(0, robot_id);
return query.list();
}
private String selectDeep;
protected String getSelectDeep() {
if (selectDeep == null) {
StringBuilder builder = new StringBuilder("SELECT ");
SqlUtils.appendColumns(builder, "T", getAllColumns());
builder.append(',');
SqlUtils.appendColumns(builder, "T0", daoSession.getRobotDao().getAllColumns());
builder.append(',');
SqlUtils.appendColumns(builder, "T1", daoSession.getEventDao().getAllColumns());
builder.append(" FROM ROBOT_EVENT T");
builder.append(" LEFT JOIN ROBOT T0 ON T.\"ROBOT_ID\"=T0.\"_id\"");
builder.append(" LEFT JOIN EVENT T1 ON T.\"EVENT_ID\"=T1.\"_id\"");
builder.append(' ');
selectDeep = builder.toString();
}
return selectDeep;
}
protected RobotEvent loadCurrentDeep(Cursor cursor, boolean lock) {
RobotEvent entity = loadCurrent(cursor, 0, lock);
int offset = getAllColumns().length;
Robot robot = loadCurrentOther(daoSession.getRobotDao(), cursor, offset);
if (robot != null) {
entity.setRobot(robot);
}
offset += daoSession.getRobotDao().getAllColumns().length;
Event event = loadCurrentOther(daoSession.getEventDao(), cursor, offset);
if (event != null) {
entity.setEvent(event);
}
return entity;
}
public RobotEvent loadDeep(Long key) {
assertSinglePk();
if (key == null) {
return null;
}
StringBuilder builder = new StringBuilder(getSelectDeep());
builder.append("WHERE ");
SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
String sql = builder.toString();
String[] keyArray = new String[]{key.toString()};
Cursor cursor = db.rawQuery(sql, keyArray);
try {
boolean available = cursor.moveToFirst();
if (!available) {
return null;
} else if (!cursor.isLast()) {
throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
}
return loadCurrentDeep(cursor, true);
} finally {
cursor.close();
}
}
/**
* Reads all available rows from the given cursor and returns a list of new ImageTO objects.
*/
public List<RobotEvent> loadAllDeepFromCursor(Cursor cursor) {
int count = cursor.getCount();
List<RobotEvent> list = new ArrayList<RobotEvent>(count);
if (cursor.moveToFirst()) {
if (identityScope != null) {
identityScope.lock();
identityScope.reserveRoom(count);
}
try {
do {
list.add(loadCurrentDeep(cursor, false));
} while (cursor.moveToNext());
} finally {
if (identityScope != null) {
identityScope.unlock();
}
}
}
return list;
}
protected List<RobotEvent> loadDeepAllAndCloseCursor(Cursor cursor) {
try {
return loadAllDeepFromCursor(cursor);
} finally {
cursor.close();
}
}
/**
* A raw-style query where you can pass any WHERE clause and arguments.
*/
public List<RobotEvent> queryDeep(String where, String... selectionArg) {
Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
return loadDeepAllAndCloseCursor(cursor);
}
}
| mit |
neolfdev/dlscxx | java_test/com/trend/hbny/service/RDayRemarkManagerTest.java | 1690 | /*
* Powered By [柳丰]
* Web Site: http://www.trend.com.cn
*/
package com.trend.hbny.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.Test;
import static junit.framework.Assert.*;
import java.util.*;
import javacommon.base.*;
import javacommon.util.*;
import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;
import com.trend.hbny.model.*;
import com.trend.hbny.dao.*;
import com.trend.hbny.service.*;
/**
* @author neolf email:neolf(a)foxmail.com
* @version 1.0
* @since 1.0
*/
public class RDayRemarkManagerTest extends BaseManagerTestCase{
private RDayRemarkManager manager;
@Autowired
public void setRDayRemarkManager(RDayRemarkManager manager) {
this.manager = manager;
}
@Override
protected String[] getDbUnitDataFiles() {
return new String[]{"classpath:common_testdata.xml","classpath:RDayRemark_testdata.xml"};
}
@Test
public void crud() {
RDayRemark obj = new RDayRemark();
obj.setCoNo(new java.lang.String("1"));
obj.setRptNo(new java.lang.String("1"));
obj.setRptDate(new java.util.Date(System.currentTimeMillis()));
obj.setRemark1(new java.lang.String("1"));
obj.setRemark2(new java.lang.String("1"));
obj.setRemark3(new java.lang.String("1"));
obj.setRemark4(new java.lang.String("1"));
obj.setRemark5(new java.lang.String("1"));
manager.save(obj);
manager.getEntityDao().flush();
manager.update(obj);
manager.getEntityDao().flush();
assertNotNull(obj.getId());
manager.removeById(obj.getId());
manager.getEntityDao().flush();
}
}
| mit |
simplay/aptRenderer | src/main/java/materials/PointLightMaterial.java | 2287 | package materials;
/**
* Created by simplaY on 05.01.2015.
*/
import base.HitRecord;
import base.Material;
import base.ShadingSample;
import base.Spectrum;
import javax.vecmath.Vector3f;
/**
* This material should be used with {@link lightsources.PointLight}.
*/
public class PointLightMaterial implements Material {
private final Spectrum emission;
public PointLightMaterial(Spectrum emission) {
this.emission = new Spectrum(emission);
}
public Spectrum evaluateEmission(HitRecord hitRecord, Vector3f wOut) {
return new Spectrum(emission);
}
/**
* Return a random direction over the full sphere of directions.
*/
public ShadingSample getEmissionSample(HitRecord hitRecord, float[] sample) {
float theta = (float) (sample[0] * 2 * Math.PI);
float z = sample[1] * 2 - 1;
float s = (float) Math.sqrt(1 - z * z);
Vector3f randomDir = new Vector3f((float) (s * Math.cos(theta)), (float) (s * Math.sin(theta)), z);
return new ShadingSample(new Spectrum(), new Spectrum(emission), randomDir, false, (float) (1 / (4 * Math.PI)));
}
/**
* Shouldn't be called on a point light
*/
public ShadingSample getShadingSample(HitRecord hitRecord, float[] sample) {
return null;
}
/**
* Shouldn't be called on a point light
*/
public boolean castsShadows() {
return false;
}
/**
* Shouldn't be called on a point light
*/
public Spectrum evaluateBRDF(HitRecord hitRecord, Vector3f wOut, Vector3f wIn) {
return new Spectrum();
}
/**
* Shouldn't be called on a point light
*/
public boolean hasSpecularReflection() {
return false;
}
/**
* Shouldn't be called on a point light
*/
public ShadingSample evaluateSpecularReflection(HitRecord hitRecord) {
return null;
}
/**
* Shouldn't be called on a point light
*/
public boolean hasSpecularRefraction() {
return false;
}
/**
* Shouldn't be called on a point light
*/
public ShadingSample evaluateSpecularRefraction(HitRecord hitRecord) {
return null;
}
@Override
public void evaluateBumpMap(HitRecord hitRecord) {
}
}
| mit |
DanteQy/Algorihms-and-Data-Structures | Heap Sort/HeapSort.java | 2188 | /*
* 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 heap;
import java.util.Arrays;
import java.util.Random;
/**
*
* @author Dante
*/
public class HeapSort {
private static int N = 17;
/**
* Complexity: N-elements where each one calls heapify
* Resulting complexity (n log n).
*/
public static void sort(int arr[]) {
// Build heap
for (int i = N / 2 - 1; i >= 0; i--){
heapify(arr, N, i);
}
// max-heapify
for (int i=N-1; i>=0; i--)
{
swap(arr, i, 0);
heapify(arr, i, 0);
}
}
//This build the heap
public static void heapify(int arr[], int n, int i)
{
//i = root
int max = i;
int left = left(i);
int right = right(i);
//left>max
if ((left < n) && (arr[left] > arr[max]))
max = left;
//right>max
if (( right < n) && (arr[right] > arr[max]))
max = right;
//if the largest is not in the root
if (max != i)
{
swap(arr, max, i);
// Recursively heapify the affected sub-tree
heapify(arr, n, max);
}
}
//height has [n/2^(h+1)] nodes.
public static int left(int i){
return 2*i;
}
public static int right(int i){
return (2*i)+1;
}
/* swapping 2 elements*/
public static void swap(int arr[], int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
private static int[] populateArr(int n){
int[] sort = new int[n];
Random random = new Random();
for (int i = 0; i < sort.length; i++) {
sort[i] = random.nextInt(n * 10);
}
return sort;
}
public static void main(String[] args) {
int[] array = populateArr(17);
System.out.println("Original: " + Arrays.toString(array));
sort(array);
System.out.println("Heap Sort: " + Arrays.toString(array));
}
}
| mit |
rhenium/SmileEssence | app/src/main/java/net/lacolaco/smileessence/view/adapter/EventListAdapter.java | 1532 | /*
* The MIT License (MIT)
*
* Copyright (c) 2012-2014 lacolaco.net
*
* 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 net.lacolaco.smileessence.view.adapter;
import android.app.Activity;
import net.lacolaco.smileessence.viewmodel.EventViewModel;
public class EventListAdapter extends UnorderedCustomListAdapter<EventViewModel> {
// --------------------------- CONSTRUCTORS ---------------------------
public EventListAdapter(Activity activity) {
super(activity);
}
}
| mit |
androidstarters/androidstarters.com | templates/mvp-arms/app/src/main/java/me/jessyan/mvparms/demo/mvp/ui/holder/UserItemHolder.java | 2858 | /**
* Copyright 2017 JessYan
*
* 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 <%= appPackage %>.mvp.ui.holder;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import <%= appPackage %>.base.BaseHolder;
import <%= appPackage %>.di.component.AppComponent;
import <%= appPackage %>.http.imageloader.ImageLoader;
import <%= appPackage %>.http.imageloader.glide.ImageConfigImpl;
import <%= appPackage %>.utils.ArmsUtils;
import butterknife.BindView;
import io.reactivex.Observable;
import <%= appPackage %>.R;
import <%= appPackage %>.mvp.model.entity.User;
/**
* ================================================
* 展示 {@link BaseHolder} 的用法
* <p>
* Created by JessYan on 9/4/16 12:56
* <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public class UserItemHolder extends BaseHolder<User> {
@BindView(R.id.iv_avatar)
ImageView mAvater;
@BindView(R.id.tv_name)
TextView mName;
private AppComponent mAppComponent;
private ImageLoader mImageLoader;//用于加载图片的管理类,默认使用 Glide,使用策略模式,可替换框架
public UserItemHolder(View itemView) {
super(itemView);
//可以在任何可以拿到 Context 的地方,拿到 AppComponent,从而得到用 Dagger 管理的单例对象
mAppComponent = ArmsUtils.obtainAppComponentFromContext(itemView.getContext());
mImageLoader = mAppComponent.imageLoader();
}
@Override
public void setData(User data, int position) {
Observable.just(data.getLogin())
.subscribe(s -> mName.setText(s));
mImageLoader.loadImage(mAppComponent.appManager().getTopActivity() == null
? mAppComponent.application() : mAppComponent.appManager().getTopActivity(),
ImageConfigImpl
.builder()
.url(data.getAvatarUrl())
.imageView(mAvater)
.build());
}
@Override
protected void onRelease() {
mImageLoader.clear(mAppComponent.application(), ImageConfigImpl.builder()
.imageViews(mAvater)
.build());
}
}
| mit |
raeffu/codingbat | src/codingbat/warmup1/ParrotTroubleTest.java | 855 | package codingbat.warmup1;
//We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.
//
//parrotTrouble(true, 6) = true
//parrotTrouble(true, 7) = false
//parrotTrouble(false, 6) = false
public class ParrotTroubleTest {
public static void main(String[] args) {
ParrotTroubleTest test = new ParrotTroubleTest();
System.out.println(">" + test.parrotTrouble(true, 6) + "<");
System.out.println(">" + test.parrotTrouble(true, 7) + "<");
System.out.println(">" + test.parrotTrouble(false, 6) + "<");
}
public boolean parrotTrouble(boolean talking, int hour) {
if (talking && (hour < 7 || hour > 20)) {
return true;
}
else {
return false;
}
}
}
| mit |
analogweb/core | src/test/java/org/analogweb/core/ConsumesMediaTypeVerifierTest.java | 7306 | package org.analogweb.core;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
import org.analogweb.ApplicationProcessor;
import org.analogweb.InvocationArguments;
import org.analogweb.InvocationMetadata;
import org.analogweb.MediaType;
import org.analogweb.RequestContext;
import org.analogweb.RequestValueResolver;
import org.analogweb.RequestValueResolvers;
import org.analogweb.TypeMapperContext;
import org.analogweb.annotation.As;
import org.analogweb.annotation.Resolver;
import org.analogweb.annotation.Route;
import org.analogweb.annotation.RequestFormats;
import org.analogweb.util.ReflectionUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ConsumesMediaTypeVerifierTest {
private ConsumesMediaTypeVerifier verifier;
private InvocationArguments args;
private InvocationMetadata metadata;
private RequestContext context;
private TypeMapperContext converters;
private RequestValueResolvers handlers;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() {
verifier = new ConsumesMediaTypeVerifier();
args = mock(InvocationArguments.class);
metadata = mock(InvocationMetadata.class);
context = mock(RequestContext.class);
converters = mock(TypeMapperContext.class);
handlers = mock(RequestValueResolvers.class);
}
@Test
public void testPrepareInvoke() {
MediaType requstType = MediaTypes.APPLICATION_ATOM_XML_TYPE;
when(context.getRequestMethod()).thenReturn("POST");
when(context.getContentType()).thenReturn(requstType);
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsAtom", new Class<?>[]{Object.class});
when(metadata.resolveMethod()).thenReturn(method);
Object actual = verifier.prepareInvoke(args, metadata, context,
converters, handlers);
assertThat(actual, is(ApplicationProcessor.NO_INTERRUPTION));
}
@Test
public void testPrepareInvokeWithGetMethod() {
MediaType requstType = MediaTypes.APPLICATION_ATOM_XML_TYPE;
when(context.getRequestMethod()).thenReturn("GET");
when(context.getContentType()).thenReturn(requstType);
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsAtom", new Class<?>[]{Object.class});
when(metadata.resolveMethod()).thenReturn(method);
Object actual = verifier.prepareInvoke(args, metadata, context,
converters, handlers);
assertThat(actual, is(ApplicationProcessor.NO_INTERRUPTION));
}
@Test
public void testPrepareInvokeInvalidMediaType() {
thrown.expect(UnsupportedMediaTypeException.class);
MediaType requstType = MediaTypes.APPLICATION_JSON_TYPE;
when(context.getRequestMethod()).thenReturn("POST");
when(context.getContentType()).thenReturn(requstType);
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsAtom", new Class<?>[]{Object.class});
when(metadata.resolveMethod()).thenReturn(method);
verifier.prepareInvoke(args, metadata, context, converters, handlers);
}
@Test
public void testPrepareInvokeDefaultFormats() {
MediaType requstType = MediaTypes.APPLICATION_XML_TYPE;
when(context.getRequestMethod()).thenReturn("POST");
when(context.getContentType()).thenReturn(requstType);
SpecificMediaTypeRequestValueResolver handler = mock(SpecificMediaTypeRequestValueResolver.class);
when(handlers.findRequestValueResolver(Xml.class)).thenReturn(handler);
when(handler.supports(requstType)).thenReturn(true);
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsSvg", new Class<?>[]{Object.class});
when(metadata.resolveMethod()).thenReturn(method);
Object actual = verifier.prepareInvoke(args, metadata, context,
converters, handlers);
assertThat(actual, is(ApplicationProcessor.NO_INTERRUPTION));
}
@Test
public void testPrepareInvokeDefaultFormatsNotSupported() {
thrown.expect(UnsupportedMediaTypeException.class);
MediaType requstType = MediaTypes.APPLICATION_JSON_TYPE;
when(context.getRequestMethod()).thenReturn("POST");
when(context.getContentType()).thenReturn(requstType);
SpecificMediaTypeRequestValueResolver handler = mock(SpecificMediaTypeRequestValueResolver.class);
when(handlers.findRequestValueResolver(Xml.class)).thenReturn(handler);
when(handler.supports(requstType)).thenReturn(false);
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsSvg", new Class<?>[]{Object.class});
when(metadata.resolveMethod()).thenReturn(method);
verifier.prepareInvoke(args, metadata, context, converters, handlers);
}
@Test
public void testPrepareInvokeNotDefinedFormats() {
thrown.expect(UnsupportedMediaTypeException.class);
when(context.getRequestMethod()).thenReturn("PUT");
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsParameter", new Class<?>[]{String.class});
when(metadata.resolveMethod()).thenReturn(method);
verifier.prepareInvoke(args, metadata, context, converters, handlers);
}
@Test
public void testPrepareInvokeWithoutFormats() {
thrown.expect(UnsupportedMediaTypeException.class);
when(context.getRequestMethod()).thenReturn("POST");
when(context.getContentType()).thenReturn(
MediaTypes.APPLICATION_XML_TYPE);
SpecificMediaTypeRequestValueResolver handler = mock(SpecificMediaTypeRequestValueResolver.class);
when(handler.supports(MediaTypes.APPLICATION_XML_TYPE)).thenReturn(
false);
when(handlers.findRequestValueResolver(Xml.class)).thenReturn(handler);
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsXml", new Class<?>[]{Object.class});
when(metadata.resolveMethod()).thenReturn(method);
verifier.prepareInvoke(args, metadata, context, converters, handlers);
}
@Test
public void testPrepareInvokeFailureWithoutFormats() {
when(context.getContentType()).thenReturn(
MediaTypes.APPLICATION_XML_TYPE);
when(context.getRequestMethod()).thenReturn("PUT");
SpecificMediaTypeRequestValueResolver handler = mock(SpecificMediaTypeRequestValueResolver.class);
when(handler.supports(MediaTypes.APPLICATION_XML_TYPE))
.thenReturn(true);
when(handlers.findRequestValueResolver(Xml.class)).thenReturn(handler);
Method method = ReflectionUtils.getMethodQuietly(SomeResource.class,
"acceptsXml", new Class<?>[]{Object.class});
when(metadata.resolveMethod()).thenReturn(method);
verifier.prepareInvoke(args, metadata, context, converters, handlers);
}
@Test
public void testPrecidence() {
assertThat(verifier.getPrecedence(), is(1));
}
private static final class SomeResource {
@RequestFormats(MediaTypes.APPLICATION_ATOM_XML)
@Route
public String acceptsAtom(@Resolver(Xml.class) @As Object anXml) {
return "fake!";
}
@Route
public String acceptsXml(@Resolver(Xml.class) @As Object anXml) {
return "fake!";
}
@RequestFormats
@Route
public String acceptsSvg(@Resolver(Xml.class) @As Object anXml) {
return "fake!";
}
@RequestFormats
@Route
public String acceptsParameter(@As("param") String param) {
return "fake!";
}
}
interface Xml extends RequestValueResolver {
}
}
| mit |
castle/castle-java | src/test/java/io/castle/client/CastleMergeHttpTest.java | 3463 | package io.castle.client;
import io.castle.client.model.AuthenticateAction;
import io.castle.client.model.AuthenticateFailoverStrategy;
import io.castle.client.utils.SDKVersion;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import com.google.common.collect.ImmutableMap;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicReference;
import io.castle.client.model.AsyncCallbackHandler;
import org.assertj.core.api.Assertions;
public class CastleMergeHttpTest extends AbstractCastleHttpLayerTest {
public CastleMergeHttpTest() {
super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
}
@Test
public void mergeContextIsSendOnHttp() throws InterruptedException, JSONException {
// Given
server.enqueue(new MockResponse().setResponseCode(200));
String event = "any.valid.event";
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And a extra context
CustomExtraContext customExtraContext = new CustomExtraContext();
customExtraContext.setAddString("String value");
customExtraContext.setCondition(true);
customExtraContext.setValue(10L);
sdk.onRequest(request).mergeContext(customExtraContext).track(event, null, null, null, ImmutableMap.builder()
.put("x", "valueX")
.put("y", 234567)
.build());
RecordedRequest recordedRequest = server.takeRequest();
String body = recordedRequest.getBody().readUtf8();
JSONAssert.assertEquals("{\"event\":\"any.valid.event\",\"context\":{\"active\":true,\"ip\":\"127.0.0.1\",\"headers\":{\"REMOTE_ADDR\":\"127.0.0.1\"}," + SDKVersion.getLibraryString() +",\"add_string\":\"String value\",\"condition\":true,\"value\":10},\"user_traits\":{\"x\":\"valueX\",\"y\":234567}}", body, false);
}
@Test
public void mergeContextIsNull() throws InterruptedException, JSONException {
// Given
server.enqueue(new MockResponse().setResponseCode(200));
String event = "any.valid.event";
// And a mock Request
HttpServletRequest request = new MockHttpServletRequest();
// And null context
sdk.onRequest(request).mergeContext(null).track(event, null, null, null);
RecordedRequest recordedRequest = server.takeRequest();
String body = recordedRequest.getBody().readUtf8();
JSONAssert.assertEquals("{\"event\":\"any.valid.event\"}", body, false);
}
private static class CustomExtraContext {
private String addString;
private Boolean condition;
private Long value;
public String getAddString() {
return addString;
}
public void setAddString(String addString) {
this.addString = addString;
}
public Boolean getCondition() {
return condition;
}
public void setCondition(Boolean condition) {
this.condition = condition;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
}
}
| mit |
shivekkhurana/learning | java/college_java/SimpleThreads.java | 2645 | public class SimpleThreads {
// Display a message, preceded by
// the name of the current thread
static void threadMessage(String message) {
String threadName =
Thread.currentThread().getName();
System.out.format("%s: %s%n",
threadName,
message);
}
private static class MessageLoop implements Runnable {
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
try {
for (int i = 0;
i < importantInfo.length;
i++) {
// Pause for 4 seconds
Thread.sleep(4000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}
public static void main(String args[])
throws InterruptedException {
// Delay, in milliseconds before
// we interrupt MessageLoop
// thread (default one hour).
long patience = 1000 * 60 * 60;
// If command line argument
// present, gives patience
// in seconds.
if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
}
threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
// loop until MessageLoop
// thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience)
&& t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
}
} | mit |
salespaulo/nota-fiscal-api | src/main/java/org/ps/test/spring/notafiscal/repository/MercadoriaRepository.java | 698 | package org.ps.test.spring.notafiscal.repository;
import org.ps.test.spring.notafiscal.domain.Mercadoria;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
/**
* Interface que representa o contrato de um repositório de {@link Mercadoria}s.
* Está utilizando o <b>spring-data-rest</b> para realizar as consultas à base de dados e disponibilizar
* endpoints RESTFull HATEOAS para manipular o recurso Mercadoria.
* @see Mercadoria
*/
@RepositoryRestResource(path = "mercadorias", collectionResourceRel = "mercadorias")
public interface MercadoriaRepository extends JpaRepository<Mercadoria, Long> {
}
| mit |
derursm/bvis | src/main/java/org/camunda/bpm/bvis/ejb/ContractHandler.java | 26140 | package org.camunda.bpm.bvis.ejb;
import org.apache.commons.io.IOUtils;
import org.camunda.bpm.bvis.ejb.beans.CarServiceBean;
import org.camunda.bpm.bvis.ejb.beans.CustomerServiceBean;
import org.camunda.bpm.bvis.ejb.beans.OrderServiceBean;
import org.camunda.bpm.bvis.ejb.beans.PickUpLocationServiceBean;
import org.camunda.bpm.bvis.entities.Car;
import org.camunda.bpm.bvis.entities.CarPriceMap;
import org.camunda.bpm.bvis.entities.Customer;
import org.camunda.bpm.bvis.entities.Insurance;
import org.camunda.bpm.bvis.entities.InsuranceAnswer;
import org.camunda.bpm.bvis.entities.InsurancePriceMap;
import org.camunda.bpm.bvis.entities.InsuranceType;
import org.camunda.bpm.bvis.entities.OrderStatus;
import org.camunda.bpm.bvis.entities.PickUpLocation;
import org.camunda.bpm.bvis.entities.RentalOrder;
import org.camunda.bpm.bvis.rest.send.service.SendContractConfirmation;
import org.camunda.bpm.bvis.rest.send.service.SendContractConfirmationClient;
import org.camunda.bpm.bvis.rest.send.service.SendInquiry;
import org.camunda.bpm.bvis.util.SendHTMLEmail;
import org.camunda.bpm.engine.cdi.BusinessProcess;
import org.camunda.bpm.engine.cdi.jsf.TaskForm;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.IllegalFormatException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
//pdf
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
@Stateless
@Named
public class ContractHandler {
@EJB
private OrderServiceBean orderService;
@EJB
private CustomerServiceBean customerService;
@EJB
private PickUpLocationServiceBean locationService;
@EJB
private CarServiceBean carService;
// Inject task form available through the Camunda cdi artifact
@Inject
private TaskForm taskForm;
@Inject
private BusinessProcess businessProcess;
// private static SendHTMLEmail sendMail;
public void persistOrder(DelegateExecution delegateExecution) throws ParseException {
double estimatedInsurancPrice = 0;
// Create new order instance
System.out.println("Process instance ID " + businessProcess.getProcessInstanceId());
System.out.println("Execution ID: " + businessProcess.getExecutionId());
RentalOrder rentalOrder = new RentalOrder();
// Get all process variables
Map<String, Object> variables = delegateExecution.getVariables();
Customer customer = new Customer();
if (variables.get("customerID") != null) {
customer = customerService.getCustomer(Long.parseLong(variables.get("customerID")+""));
}
else {
customer.setFirstname((String) variables.get("customerFirstname"));
customer.setSurname((String) variables.get("customerSurname"));
String customerCompanyName = (String) variables.get("customerCompanyName");
boolean isCompany = true;
if (customerCompanyName.isEmpty()) {
isCompany = false;
}
customer.setCompanyName(customerCompanyName);
customer.setCompany(isCompany);
customer.setEmail((String) variables.get("customerEmail"));
customer.setPhoneNumber((String) variables.get("customerPhoneNumber"));
System.out.println(variables.get("customerDateOfBirth"));
customer.setDateOfBirth((Date) variables.get("customerDateOfBirth"));
customer.setStreet((String) variables.get("customerStreet"));
customer.setHouseNumber((String) variables.get("customerHouseNumber"));
customer.setPostcode((String) variables.get("customerPostcode"));
customer.setCity((String) variables.get("customerCity"));
customer.setCountry((String) variables.get("customerCountry"));
customer.setEligibility(false);
customerService.create(customer);
}
// Set order attributes
rentalOrder.setCustomer(customer);
rentalOrder.setRequestDate(new Date());
boolean isFleet = (Boolean) variables.get("fleet");
if (!isFleet) {
Date pickUpDate = (Date) variables.get("pickUpDate");
rentalOrder.setPick_up_date(pickUpDate);
Date returnDate = (Date) variables.get("returnDate");
rentalOrder.setReturn_date(returnDate);
Long pickUpLocationId = (Long) variables.get("pickUpLoc");
Long returnStoreId = (Long) variables.get("returnStore");
rentalOrder.setPickUpStore((PickUpLocation) locationService.getPickUpLocation(pickUpLocationId));
rentalOrder.setReturnStore((PickUpLocation) locationService.getPickUpLocation(returnStoreId));
InsuranceType insuranceType = (InsuranceType) variables.get("insuranceType");
Long carId = (Long) variables.get("car");
Car car = carService.getCar(carId);
Collection<Car> cars = new ArrayList<Car>();
cars.add(car);
rentalOrder.setCars((Collection<Car>) cars);
// calculate price for cars
double priceCars = calcCarPrice(cars, returnDate, pickUpDate);
rentalOrder.setPriceCars(priceCars);
// calculate price for insurance
estimatedInsurancPrice = calcInsurancePrice(cars, insuranceType, returnDate, pickUpDate);
if (estimatedInsurancPrice < 0) estimatedInsurancPrice = 0;
}
rentalOrder.setFleetRental(isFleet);
rentalOrder.setInquiryText((String) variables.get("inquiryText"));
rentalOrder.setClerkComments("");
rentalOrder.setApproveStatus(false);
// TODO GENERATE A PROPER INSURANCE. THIS IS JUST A DUMMY FOR TESTING
// PURPOSES
Insurance insurance = new Insurance();
insurance.setPickUpDate((Date) variables.get("pickUpDate"));
insurance.setReturnDate((Date) variables.get("returnDate"));
insurance.setOrder(rentalOrder);
System.out.println(variables.get("insuranceType"));
if(Objects.equals(((InsuranceType) variables.get("insuranceType")).toString(),"total")){
insurance.setDeductible(new BigDecimal(0));
insurance.setType(InsuranceType.total);
System.out.println("Set total insurance");
}
if(Objects.equals(((InsuranceType) variables.get("insuranceType")).toString(),"partial")){
insurance.setDeductible(new BigDecimal(1000));
insurance.setType(InsuranceType.partial);
System.out.println("Set partial insurance");
}
if(Objects.equals(((InsuranceType) variables.get("insuranceType")).toString(),"liability")){
insurance.setDeductible(new BigDecimal(2000));
insurance.setType(InsuranceType.liability);
System.out.println("Set liablilty insurance");
}
insurance.setEstimatedCosts(new BigDecimal(estimatedInsurancPrice));
rentalOrder.setInsurance(insurance);
rentalOrder.setOrderStatus(OrderStatus.PENDING);
orderService.create(rentalOrder);
System.out.println("Cars: " + rentalOrder.getCars());
// Remove no longer needed process variables
delegateExecution.removeVariables(variables.keySet());
// Add newly created order id as process variable
delegateExecution.setVariable("orderId", rentalOrder.getId());
delegateExecution.setVariable("fleet", rentalOrder.isFleetRental());
delegateExecution.setVariable("processId", delegateExecution.getProcessInstanceId());
System.out.println("CREATED ORDER WITH ORDER ID: " + rentalOrder.getId());
}
// Create contract and send to user's email
public void sendContract(DelegateExecution delegateExecution) {
System.out.println("Start creating contract");
RentalOrder order;
Customer customer;
Collection<Car> cars;
String surname, email, pickupLocation, returnLocation, insurancePac, carModel, rentalEnd, rentalStart, date,
type, street, city, orderId_str, vehicleIdent;
double totalPrice, insurancePrice, rentalPrice;
Long orderId;
// Get all process variables
Map<String, Object> variables = delegateExecution.getVariables();
orderId = (long) variables.get("orderId");
order = orderService.getOrder(orderId);
customer = order.getCustomer();
cars = order.getCars();
order.setOrderStatus(OrderStatus.ACCEPTED);
surname = "surname";
email = "email";
pickupLocation = "pickupLocation";
returnLocation = "returnLocation";
carModel = "carmodel";
rentalStart = "rentalStart";
rentalEnd = "rentalEnd";
orderId_str = "orderId";
insurancePac = "insurancePac";
rentalPrice = 0;
insurancePrice = 0;
totalPrice = 0;
vehicleIdent = order.getCars().iterator().next().getVehicleIdentificationNumber();
// Get rental information
if (order.isFleetRental()) {
type = "Fleet";
} else {
type = "Private Single Rental";
}
orderId_str = orderId.toString();
surname = customer.getSurname();
street = customer.getStreet() + " " + customer.getHouseNumber();
city = customer.getPostcode() + " " + customer.getCity();
email = customer.getEmail();
rentalStart = order.getPick_up_date().toString();
rentalEnd = order.getReturn_date().toString();
pickupLocation = order.getPickUpStore().getContactDetails();
returnLocation = order.getReturnStore().getContactDetails();
// insurancePac = order.getInsurance().getType();
rentalPrice = order.getPriceCars();
insurancePrice = order.getInsurance().getActualCosts().doubleValue();
totalPrice = order.getPrice();
insurancePac = order.getInsurance().getType().toString();
carModel = "";
int i = 1;
for (Car loop_car : cars) {
carModel += String.valueOf(i) + ": " + loop_car.getHTMLCarDetails();
}
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date today = new Date();
date = formatter.format(today);
// surname, email, pickupLocation, returnLocation,
// insurancePac, carModel, rentalEnd, rentalStart, orderId_str, date,
// type, street, city;
// double totalPrice, insurancePrice, rentalPrice;
// Long orderId;
final String[][] rentalData = { { "Type:", type }, { "Pick-up date:", rentalStart },
{ "Return date:", rentalEnd }, { "Pick-up location:", pickupLocation },
{ "Return location:", returnLocation }, { "Car:", carModel }, { "Insurance type:", insurancePac },
{ "Price insurance:", String.valueOf(insurancePrice) + " EUR" },
{ "Price car:", String.valueOf(rentalPrice) + " EUR" },
{ "Vehicle identification number:", String.valueOf(vehicleIdent) },
{ "Total:", String.valueOf(totalPrice) + " EUR" }, };
try {
Document document = new Document();
ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter pdf = null;
pdf = PdfWriter.getInstance(document, baosPDF);
document.open();
Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC);
Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL);
Paragraph pa0 = new Paragraph("Order ID: " + orderId_str, paragraphFont);
pa0.setAlignment(Element.ALIGN_RIGHT);
pa0.setFont(FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL));
document.add(pa0);
Chunk chunk = new Chunk("BVIS Rental Contract", chapterFont);
document.add(chunk);
Paragraph pa1 = new Paragraph("The best choice", paragraphFont);
pa1.setSpacingAfter(15);
document.add(pa1);
List list = new List();
list.setListSymbol("");
list.add(new ListItem("Mr/Mrs " + surname));
list.add(new ListItem(street));
list.add(new ListItem(city));
Paragraph pa2 = new Paragraph();
pa2.add(list);
pa2.setSpacingAfter(20);
document.add(pa2);
Paragraph datePar = new Paragraph(date, paragraphFont);
datePar.setAlignment(Element.ALIGN_RIGHT);
document.add(datePar);
document.add(new Paragraph("Dear Mr/Mrs " + surname + ",", paragraphFont));
Paragraph pa3 = new Paragraph(
"thank you for choosing BVIS as your transportation service provider. Please find your rental details below:",
paragraphFont);
pa3.setSpacingAfter(10);
document.add(pa3);
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(80);
table.setHorizontalAlignment(Element.ALIGN_LEFT);
table.setWidths(new int[] { 5, 10 });
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.addCell(rentalData[0][0]);
table.addCell(rentalData[0][1]);
table.addCell(rentalData[1][0]);
table.addCell(rentalData[1][1]);
table.addCell(rentalData[2][0]);
table.addCell(rentalData[2][1]);
table.addCell(rentalData[3][0]);
table.addCell(rentalData[3][1]);
table.addCell(rentalData[4][0]);
table.addCell(rentalData[4][1]);
table.addCell(rentalData[5][0]);
table.addCell(rentalData[5][1]);
table.addCell(rentalData[6][0]);
table.addCell(rentalData[6][1]);
table.addCell(rentalData[7][0]);
table.addCell(rentalData[7][1]);
table.addCell(rentalData[8][0]);
table.addCell(rentalData[8][1]);
table.addCell(rentalData[9][0]);
table.addCell(rentalData[9][1]);
table.addCell(rentalData[10][0]);
table.addCell(rentalData[10][1]);
Paragraph pa4 = new Paragraph();
pa4.add(table);
pa4.setSpacingAfter(15);
document.add(pa4);
document.add(new Paragraph("Thank you and have a nice ride", paragraphFont));
document.close();
pdf.close();
SendHTMLEmail.mainAtt("Final contract",
"Dear Mr/Mrs " + surname + ". <br> Please find attached your contract.", "bvis@test.de", email,
baosPDF, "bvis_contract_" + surname);
} catch (DocumentException e) {
System.out.println("Contracting DocumentException");
}
}
public RentalOrder getOrder(Long orderId) {
// Load order entity from database
return orderService.getOrder(orderId);
}
public boolean isFleetOrder(DelegateExecution delegateExecution) {
Map<String, Object> variables = delegateExecution.getVariables();
boolean isFleetOrder = (Boolean) variables.get("fleet");
return isFleetOrder;
}
public void updateOrder(RentalOrder rentalOrder, boolean completeTask) {
// Merge detached order entity with current persisted state
orderService.updateOrder(rentalOrder);
if (completeTask) {
try {
// Complete user task from
taskForm.completeTask();
} catch (IOException e) {
// Rollback both transactions on error
throw new RuntimeException("Cannot complete task", e);
}
}
}
// General send email method. State states the content of the email. Email
// information is caught from
// process variables
public void sendOrderStateNotification(DelegateExecution delegateExecution) throws ParseException {
RentalOrder order;
Customer customer;
Car car;
Collection<Car> cars;
String surname, subject, text, from, email, state, path, pickupLocation, returnLocation, insurancePac, carModel,
rentalEnd, rentalStart, orderId_str, clerkComment, towingAddress, pathCss, textCss, vehicleIdent;
Long orderId;
boolean isFleetRental;
// tbc..
// Get all process variables
Map<String, Object> variables = delegateExecution.getVariables();
orderId = (long) variables.get("orderId");
state = variables.get("state").toString();
order = orderService.getOrder(orderId);
customer = order.getCustomer();
cars = order.getCars();
surname = "surname";
email = "email";
from = "from";
pickupLocation = "pickupLocation"; // order.getPick_up_store().getStoreName()
// +
// order.getPick_up_store().getCity();
returnLocation = "returnLocation"; // order.getReturn_store().getStoreName()
// +
// order.getReturn_store().getCity();
carModel = "carmodel"; // order.getCars();
rentalStart = "rentalStart";
rentalEnd = "rentalEnd";
orderId_str = "orderId";
towingAddress = "towingAddress";
insurancePac = "insurancePac";
vehicleIdent = " ";
// Get rental information
isFleetRental = order.isFleetRental();
orderId_str = orderId.toString();
surname = customer.getSurname();
email = customer.getEmail();
System.out.println("FLEET");
System.out.println(isFleetRental);
from = "bvis@bvis.com";
if (!isFleetRental) {
rentalStart = order.getPick_up_date().toString();
rentalEnd = order.getReturn_date().toString();
pickupLocation = order.getPickUpStore().getHTMLContactDetails();
returnLocation = order.getReturnStore().getHTMLContactDetails();
clerkComment = order.getClerkComments();
insurancePac = order.getInsurance().getType().toString();
for (Car loop_car : cars) {
carModel += loop_car.getHTMLCarDetails() + "<br>";
vehicleIdent += loop_car.getVehicleIdentificationNumber() + " ";
}
}
subject = "";
path = "/templates/";
pathCss = "/templates/css.txt";
// built email template path by state
switch (state) {
case "canc_fleet":
path += "canc_fleet.txt";
subject = "We are sorry... (No. " + orderId_str + ")";
break;
case "canc_single":
path += "canc_single.txt";
subject = "We are sorry... (No. " + orderId_str + ")";
break;
case "conf_req":
if (isFleetRental) {
path += "conf_req_fleet.txt";
subject = "Booking reservation (No. " + orderId_str + ")";
break;
} else if (!isFleetRental) {
path += "conf_req_single.txt";
subject = "Booking reservation (No. " + orderId_str + ")";
break;
}
break;
case "rej_el":
path += "rej_el.txt";
subject = "We are sorry... (No. " + orderId_str + ")";
break;
case "rej_ins":
path += "rej_ins.txt";
subject = "We are sorry... (No. " + orderId_str + ")";
break;
case "send_cont":
path += "send_cont.txt";
subject = "Congratulation! (No. " + orderId_str + ")";
break;
case "send_sorrow":
path += "send_sorrow.txt";
subject = "Good bye (No. " + orderId_str + ")";
order.setOrderStatus(OrderStatus.REJECTED);
break;
}
InputStream in = this.getClass().getResourceAsStream(path);
InputStream inCss = this.getClass().getResourceAsStream(pathCss);
try {
text = IOUtils.toString(in, "UTF-8");
textCss = IOUtils.toString(inCss, "UTF-8");
} catch (IOException e) {
text = "error in file reading. path: " + path;
textCss = "";
email = "bvis@bvis.com";
} catch (NullPointerException e) {
text = "null pointer file reading. path: " + path;
textCss = "";
email = "bvis@bvis.com";
}
try {
text = String.format(text, surname, carModel, pickupLocation, rentalStart, returnLocation, rentalEnd,
orderId_str, towingAddress, insurancePac, vehicleIdent);
} catch (IllegalFormatException e) {
subject = "illegal conversion ";
email = "bvis@bvis.com";
}
SendHTMLEmail.main(subject, textCss + text, from, email);
}
public void sendInquiryToCapitol(DelegateExecution delegateExecution) {
System.out.println("SENDING TO CAPITOL INITIALIZED");
SendInquiry sender = new SendInquiry();
RentalOrder entityOrder = orderService.getOrder((Long) businessProcess.getVariable("orderId"));
System.out.println("Sending inquiry with vehicle identification number: " + entityOrder.getCars().
iterator().next().getVehicleIdentificationNumber());
String result = sender.sendInquiry(entityOrder, delegateExecution.getProcessInstanceId());
System.out.println("SENDING DONE. INSURANCE API RESPONSE: " + result);
// TODO handle failures
}
public boolean handleInsuranceResponse(DelegateExecution delegateExecution) {
Map<String, Object> variables = delegateExecution.getVariables();
int orderID = Integer.parseInt(variables.get("orderID").toString());
RentalOrder order = orderService.getOrder(orderID);
Insurance insurance = order.getInsurance();
insurance.setActualCosts(new BigDecimal(Double.parseDouble(variables.get("finalPrice").toString())));
insurance.setInquiryText(variables.get("inquiryText").toString());
order.setPrice(insurance.getActualCosts().doubleValue() + order.getPriceCars());
int insuranceAnswer = Integer.parseInt(variables.get("insuranceResult").toString());
if (insuranceAnswer == 0) {
insurance.setInsuranceAnswer(InsuranceAnswer.REJECTED);
System.out.println("INSURANCE REJECTED");
order.setOrderStatus(OrderStatus.REJECTED);
} else if (insuranceAnswer == 1) {
insurance.setInsuranceAnswer(InsuranceAnswer.ACCEPTED);
System.out.println("INSURANCE ACCEPTED");
order.setOrderStatus(OrderStatus.ACCEPTED);
} else {
insurance.setInsuranceAnswer(InsuranceAnswer.ADJUSTED);
System.out.println("INSURANCE ADJUSTED");
}
order.setInsurance(insurance);
delegateExecution.removeVariables();
orderService.updateOrder(order);
// return true to trigger continuation
return true;
}
public void sendContractConfirmation(DelegateExecution delegateExecution) {
Map<String, Object> variables = delegateExecution.getVariables();
int orderID = Integer.parseInt(variables.get("orderID").toString());
RentalOrder order = orderService.getOrder(orderID);
SendContractConfirmation client = new SendContractConfirmation();
System.out.println("SENDING CONTRACT CONFIRMATION");
String processInstanceIDBVIS = (String) variables.get("processId");
String processInstanceIDCapitol = (String) variables.get("processIdCapitol");
client.sendContractConfirmation(order, processInstanceIDBVIS, processInstanceIDCapitol, 1);
System.out.println("CONTRACT CONFIRMATION SUCCESSFULLY SENT"); // TODO
// insert
// proper
// contract
// status
}
public void sendReminder() {
// TODO insert business logic
// TODO create form
}
public void handleRequirements(DelegateExecution delegateExecution) {
Map<String, Object> variables = delegateExecution.getVariables();
// only gets called for single car rentals
RentalOrder rentalOrder = getOrder((Long) variables.get("orderId"));
Car car = rentalOrder.getCars().iterator().next();
// get all cars that have the same model
Collection<Car> sameCars = carService.getAllCarsByModel(car.getModel());
// find a car that is available in the requested period for the current rental order
Date begin = rentalOrder.getPick_up_date();
Date end = rentalOrder.getReturn_date();
boolean foundOne = false;
for (Car c : sameCars) {
boolean available = true;
for (RentalOrder o : c.getRentalOrders()) {
// if it is the same rental order as the current one continue
if (o.equals(rentalOrder)) continue;
// not available when
// case 1: pickup before pickup and return after pickup
// case 2: pickup after pickup and before return
if ((o.getPick_up_date().before(begin) || o.getPick_up_date().equals(begin))
&& (o.getReturn_date().after(begin) || o.getReturn_date().equals(begin))) {
available = false;
break;
}
else if ((o.getPick_up_date().after(begin) || o.getPick_up_date().equals(begin))
&& (o.getPick_up_date().before(end) || o.getPick_up_date().equals(end))) {
available = false;
break;
}
}
// if current car is available
if (available) {
foundOne = true;
// update newly assigned car
Collection<RentalOrder> currentOrders = c.getRentalOrders();
currentOrders.add(rentalOrder);
c.setRentalOrders(currentOrders);
carService.updateCar(c);
// update original car
currentOrders = car.getRentalOrders();
currentOrders.remove(rentalOrder);
carService.updateCar(car);
// update rental order
ArrayList<Car> newCarList = new ArrayList<Car>();
newCarList.add(c);
rentalOrder.setCars(newCarList);
orderService.updateOrder(rentalOrder);
}
}
if (foundOne) System.out.println("Car available");
else System.out.println("No car available");
delegateExecution.setVariable("fulfillable", foundOne);
}
public double calcInsurancePrice(Collection<Car> cars, InsuranceType bookingInsuranceType, Date returnDate, Date pickupDate) {
double insuranceTypeFactor = InsurancePriceMap.getInsuranceFactor(bookingInsuranceType);
int current_year = Calendar.getInstance().get(Calendar.YEAR);
double priceInsurance_expected = 0;
for(Car carItem : cars) {
double carTypeFactor = InsurancePriceMap.getInsuranceFactor(carItem.getType());
int ps = carItem.getPs();
int construction_year = carItem.getConstructionYear();
int year_diff = current_year - construction_year;
priceInsurance_expected += ((insuranceTypeFactor * carTypeFactor) + (ps * 0.15) + (20
- Math.pow(1.2, year_diff) / 30.0 )) /100;
System.out.println(priceInsurance_expected);
}
Long diff = returnDate.getTime() - pickupDate.getTime();
long rentDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
rentDays ++;
double priceInsurance = priceInsurance_expected * (double) rentDays;
return ((double) Math.round(priceInsurance*100))/100;
}
public boolean updateContract(DelegateExecution delegateExecution) {
Map<String, Object> variables = delegateExecution.getVariables();
long newCarID = Long.parseLong(variables.get("newCarId")+"");
Car newCar = carService.getCar(newCarID);
RentalOrder order = orderService.getOrder(Long.parseLong(variables.get("orderId")+""));
ArrayList<Car> cars = new ArrayList<Car>();
cars.add(newCar);
order.setCars(cars);
orderService.updateOrder(order);
System.out.println("NEW CAR: " + order.getCars().iterator().next().getModel());
return true;
}
public double calcCarPrice(Collection<Car> cars, Date returnDate, Date pickupDate) {
Long diff = returnDate.getTime() - pickupDate.getTime();
long rentDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS) + 1;
long price = 0;
for(Car carItem : cars) {
price += (long) CarPriceMap.getPrice(carItem.getType());
}
return rentDays * price;
}
}
| mit |
ysaak/wall-creator | src/main/java/wallmanager/ui/frame/events/ProfileVersionSelectedEvent.java | 317 | package wallmanager.ui.frame.events;
import lombok.Data;
import lombok.NonNull;
import wallmanager.beans.profile.Profile;
import wallmanager.beans.profile.ProfileVersion;
@Data
public class ProfileVersionSelectedEvent {
@NonNull
private final Profile profile;
@NonNull
private final ProfileVersion version;
}
| mit |
opengl-8080/Samples | java/ddd_workshop/src/main/java/domain/Variety.java | 601 | package domain;
public class Variety {
private final String value;
public Variety(String value) {
this.value = value;
}
@Override
public String toString() {
return "品種(" + this.value + ")";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Variety variety = (Variety) o;
return value.equals(variety.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| mit |
nrkno/nrk-shared-java | nrk-ietf/nrk-ietf-rfc7159-json/src/main/java/no/nrk/ietf/rfc7159/json/JsonValue.java | 2126 | package no.nrk.ietf.rfc7159.json;
import java.util.Optional;
import no.nrk.common.util.ToString;
public abstract class JsonValue {
/**
* A JSON value is empty if it contains no value(s), such as an empty JSON
* object, an empty JSON array, <code>null</code> or an "undefined" value
* reference.
*
* <p>
* Be aware that an empty string is not empty - see
* {@link JsonStringValue#isEmpty()} for details.
* </p>
*/
public abstract boolean isEmpty();
public abstract Optional<JsonStringValue> isString();
public abstract Optional<JsonNullValue> isNull();
public abstract Optional<JsonUndefinedValue> isUndefined();
public abstract Optional<JsonNumberValue> isNumber();
public abstract Optional<JsonBooleanValue> isBoolean();
public abstract Optional<JsonObjectValue> isObject();
public abstract Optional<JsonArrayValue> isArray();
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof JsonValue) {
JsonValue rhs = (JsonValue) obj;
if (this.isEmpty() != rhs.isEmpty()) {
return false;
}
if (this.isUndefined().isPresent() != rhs.isUndefined().isPresent()) {
return false;
}
return equalsJsonValue(rhs);
} else {
return super.equals(obj);
}
}
protected abstract boolean equalsJsonValue(JsonValue rhs);
/**
* @return this instance, if it's a JSON object, otherwise an undefined
* {@link JsonObjectValue}.
*/
public final JsonObjectValue asObject() {
return isObject().orElseGet(JsonObjectValue::undefined);
}
/**
* @return this instance, if it's a JSON array, otherwise an undefined
* {@link JsonArrayValue}.
*/
public final JsonArrayValue asArray() {
return isArray().orElseGet(JsonArrayValue::undefined);
}
/**
* @return this instance, if it's a String value, otherwise an undefined
* {@link JsonStringValue}.
*/
public final JsonStringValue asString() {
return isString().orElseGet(UndefinedJsonStringValue::instance);
}
@Override
public String toString() {
return ToString.of(this)
.withObjectIdentity()
.toString();
}
}
| mit |
hovsepm/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ElasticPoolImpl.java | 7373 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.sql.v2014_04_01.implementation;
import com.microsoft.azure.management.sql.v2014_04_01.ElasticPool;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import com.microsoft.azure.management.sql.v2014_04_01.ElasticPoolUpdate;
import java.util.Map;
import org.joda.time.DateTime;
import com.microsoft.azure.management.sql.v2014_04_01.ElasticPoolState;
import com.microsoft.azure.management.sql.v2014_04_01.ElasticPoolEdition;
import rx.functions.Func1;
class ElasticPoolImpl extends CreatableUpdatableImpl<ElasticPool, ElasticPoolInner, ElasticPoolImpl> implements ElasticPool, ElasticPool.Definition, ElasticPool.Update {
private final SqlManager manager;
private String resourceGroupName;
private String serverName;
private String elasticPoolName;
private ElasticPoolUpdate updateParameter;
ElasticPoolImpl(String name, SqlManager manager) {
super(name, new ElasticPoolInner());
this.manager = manager;
// Set resource name
this.elasticPoolName = name;
//
this.updateParameter = new ElasticPoolUpdate();
}
ElasticPoolImpl(ElasticPoolInner inner, SqlManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.elasticPoolName = inner.name();
// resource ancestor names
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.serverName = IdParsingUtils.getValueFromIdByName(inner.id(), "servers");
this.elasticPoolName = IdParsingUtils.getValueFromIdByName(inner.id(), "elasticPools");
//
this.updateParameter = new ElasticPoolUpdate();
}
@Override
public SqlManager manager() {
return this.manager;
}
@Override
public Observable<ElasticPool> createResourceAsync() {
ElasticPoolsInner client = this.manager().inner().elasticPools();
return client.createOrUpdateAsync(this.resourceGroupName, this.serverName, this.elasticPoolName, this.inner())
.map(new Func1<ElasticPoolInner, ElasticPoolInner>() {
@Override
public ElasticPoolInner call(ElasticPoolInner resource) {
resetCreateUpdateParameters();
return resource;
}
})
.map(innerToFluentMap(this));
}
@Override
public Observable<ElasticPool> updateResourceAsync() {
ElasticPoolsInner client = this.manager().inner().elasticPools();
return client.updateAsync(this.resourceGroupName, this.serverName, this.elasticPoolName, this.updateParameter)
.map(new Func1<ElasticPoolInner, ElasticPoolInner>() {
@Override
public ElasticPoolInner call(ElasticPoolInner resource) {
resetCreateUpdateParameters();
return resource;
}
})
.map(innerToFluentMap(this));
}
@Override
protected Observable<ElasticPoolInner> getInnerAsync() {
ElasticPoolsInner client = this.manager().inner().elasticPools();
return client.getAsync(this.resourceGroupName, this.serverName, this.elasticPoolName);
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
private void resetCreateUpdateParameters() {
this.updateParameter = new ElasticPoolUpdate();
}
@Override
public DateTime creationDate() {
return this.inner().creationDate();
}
@Override
public Integer databaseDtuMax() {
return this.inner().databaseDtuMax();
}
@Override
public Integer databaseDtuMin() {
return this.inner().databaseDtuMin();
}
@Override
public Integer dtu() {
return this.inner().dtu();
}
@Override
public ElasticPoolEdition edition() {
return this.inner().edition();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String kind() {
return this.inner().kind();
}
@Override
public String location() {
return this.inner().location();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public ElasticPoolState state() {
return this.inner().state();
}
@Override
public Integer storageMB() {
return this.inner().storageMB();
}
@Override
public Map<String, String> tags() {
return this.inner().getTags();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public Boolean zoneRedundant() {
return this.inner().zoneRedundant();
}
@Override
public ElasticPoolImpl withExistingServer(String resourceGroupName, String serverName) {
this.resourceGroupName = resourceGroupName;
this.serverName = serverName;
return this;
}
@Override
public ElasticPoolImpl withLocation(String location) {
this.inner().withLocation(location);
return this;
}
@Override
public ElasticPoolImpl withDatabaseDtuMax(Integer databaseDtuMax) {
if (isInCreateMode()) {
this.inner().withDatabaseDtuMax(databaseDtuMax);
} else {
this.updateParameter.withDatabaseDtuMax(databaseDtuMax);
}
return this;
}
@Override
public ElasticPoolImpl withDatabaseDtuMin(Integer databaseDtuMin) {
if (isInCreateMode()) {
this.inner().withDatabaseDtuMin(databaseDtuMin);
} else {
this.updateParameter.withDatabaseDtuMin(databaseDtuMin);
}
return this;
}
@Override
public ElasticPoolImpl withDtu(Integer dtu) {
if (isInCreateMode()) {
this.inner().withDtu(dtu);
} else {
this.updateParameter.withDtu(dtu);
}
return this;
}
@Override
public ElasticPoolImpl withEdition(ElasticPoolEdition edition) {
if (isInCreateMode()) {
this.inner().withEdition(edition);
} else {
this.updateParameter.withEdition(edition);
}
return this;
}
@Override
public ElasticPoolImpl withStorageMB(Integer storageMB) {
if (isInCreateMode()) {
this.inner().withStorageMB(storageMB);
} else {
this.updateParameter.withStorageMB(storageMB);
}
return this;
}
@Override
public ElasticPoolImpl withTags(Map<String, String> tags) {
if (isInCreateMode()) {
this.inner().withTags(tags);
} else {
this.updateParameter.withTags(tags);
}
return this;
}
@Override
public ElasticPoolImpl withZoneRedundant(Boolean zoneRedundant) {
if (isInCreateMode()) {
this.inner().withZoneRedundant(zoneRedundant);
} else {
this.updateParameter.withZoneRedundant(zoneRedundant);
}
return this;
}
}
| mit |
Microsoft/ProjectOxford-Apps-MimickerAlarm | Mimicker/app/src/main/java/com/microsoft/mimickeralarm/ringing/AlarmRingtonePlayer.java | 3121 | /*
*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license.
*
* Project Oxford: http://ProjectOxford.ai
*
* Project Oxford Mimicker Alarm Github:
* https://github.com/Microsoft/ProjectOxford-Apps-MimickerAlarm
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License:
* 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.microsoft.mimickeralarm.ringing;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import com.microsoft.mimickeralarm.utilities.Logger;
/**
* A simple utility class to wrap the system media player. This class is utilized by the
* AlarmRingingController.
*/
public class AlarmRingtonePlayer {
private MediaPlayer mPlayer;
private Context mContext;
public AlarmRingtonePlayer(Context context) {
mContext = context;
}
public void initialize() {
try {
mPlayer = new MediaPlayer();
} catch (Exception e) {
Logger.trackException(e);
}
}
public void cleanup() {
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
public void play(Uri toneUri) {
try {
if (mPlayer != null && !mPlayer.isPlaying()) {
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mPlayer.setDataSource(mContext, toneUri);
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mPlayer.setLooping(true);
mPlayer.prepareAsync();
}
} catch (Exception e) {
Logger.trackException(e);
}
}
public void stop() {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.reset();
}
}
}
| mit |
JasonWayne/lintcode-solutions | src/main/java/linkedlist/CopyListWithRandomPointer.java | 1745 | package linkedlist;
import java.util.HashMap;
import java.util.Map;
/**
* http://www.lintcode.com/en/problem/copy-list-with-random-pointer/#
* Created by wuwenjie on 2/14/16.
*/
public class CopyListWithRandomPointer {
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
// key: oldNode, value: newNode
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode dummy = new RandomListNode(0);
dummy.next = head;
RandomListNode newDummy = new RandomListNode(0);
// copy the linked list
RandomListNode last = newDummy;
while (head != null) {
RandomListNode newHead = new RandomListNode(head.label);
map.put(head, newHead);
last.next = newHead;
last = newHead;
head = head.next;
}
// copy random pointer
RandomListNode current = dummy.next;
RandomListNode currentNew = newDummy.next;
while (current != null) {
currentNew.random = map.get(current.random);
currentNew = currentNew.next;
current = current.next;
}
return newDummy.next;
}
}
}
| mit |
cloudmessagingcenter/cmc-java | src/test/java/com/telecomsys/cmc/MessagingApiTest.java | 31705 | package com.telecomsys.cmc;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import com.telecomsys.cmc.api.MessagingApi;
import com.telecomsys.cmc.exception.CMCAuthenticationException;
import com.telecomsys.cmc.exception.CMCException;
import com.telecomsys.cmc.exception.CMCIOException;
import com.telecomsys.cmc.exception.CMCClientException;
import com.telecomsys.cmc.http.HttpResponseWrapper;
import com.telecomsys.cmc.model.Message;
import com.telecomsys.cmc.model.ProgramReply;
import com.telecomsys.cmc.response.DeliveryReceipt;
import com.telecomsys.cmc.response.DeliveryReceiptResponse;
import com.telecomsys.cmc.response.MessageReplies;
import com.telecomsys.cmc.response.MessageRepliesResponse;
import com.telecomsys.cmc.response.MessageReply;
import com.telecomsys.cmc.response.MessageStatus;
import com.telecomsys.cmc.response.Notifications;
import com.telecomsys.cmc.response.NotificationsResponse;
import com.telecomsys.cmc.response.RestResponse;
import com.telecomsys.cmc.response.TrackingInformation;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.*;
public class MessagingApiTest {
/**
* CMC REST user name (account ID).
*/
private static final String USERNAME = "9876";
/**
* CMC REST user name (account ID).
*/
private static final String PASSWORD = "1234";
/**
* CMC REST connection keyword.
*/
private static final String REST_CONNECTION_KEYWORD = "scsrest";
/**
* CMC client instance.
*/
private MessagingApi messagingApi;
@Rule
public WireMockRule wireMockRule = new WireMockRule(18089);
@Before
public void setup() {
messagingApi = new MessagingApi("http://localhost:18089", USERNAME, PASSWORD);
}
@Test(expected=CMCIOException.class)
public void invalidHostTest() throws CMCException {
MessagingApi invalidMessagingApi = new MessagingApi("http://invalidHost:1234", USERNAME, PASSWORD);
List<String> destinations = new ArrayList<String>();
destinations.add("4102804827");
Message message = new Message(destinations, REST_CONNECTION_KEYWORD, "Test message");
invalidMessagingApi.sendMessage(message);
}
@Test(expected=CMCAuthenticationException.class)
public void invalidCredentialsTest() throws CMCException {
stubFor(post(urlEqualTo("/messages"))
.willReturn(aResponse()
.withStatus(401)
.withHeader("Content-Type", "text/html")
.withBody("This request requires HTTP authentication.")));
List<String> destinations = new ArrayList<String>();
destinations.add("4102804827");
Message message = new Message(destinations, REST_CONNECTION_KEYWORD, "Test message");
messagingApi.sendMessage(message);
}
@Test
public void invalidKeywordTest() throws CMCException {
stubFor(post(urlEqualTo("/messages"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"1010\",\"message\":\"Your message failed: Invalid from address.\"}}")));
try {
List<String> destinations = new ArrayList<String>();
destinations.add("4102804827");
Message message = new Message(destinations, REST_CONNECTION_KEYWORD, "Test message");
messagingApi.sendMessage(message);
} catch (CMCClientException cmex) {
RestResponse error = cmex.getError();
assertEquals(error.getStatus(), "fail");
assertEquals(error.getCode(), "1010");
assertEquals(error.getMessage(), "Your message failed: Invalid from address.");
}
}
@Test
public void rmiConnectionDownTest() throws CMCException {
stubFor(post(urlEqualTo("/messages"))
.willReturn(aResponse()
.withStatus(500)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"1001\",\"message\":\"Your message failed: Invalid from address.\"}}")));
try {
List<String> destinations = new ArrayList<String>();
destinations.add("4102804827");
Message message = new Message(destinations, REST_CONNECTION_KEYWORD, "Test message");
messagingApi.sendMessage(message);
} catch (CMCClientException cmex) {
RestResponse error = cmex.getError();
assertEquals(error.getStatus(), "fail");
assertEquals(error.getCode(), "1001");
assertEquals(error.getMessage(), "Your message failed: sent error.");
}
}
@Test
public void sendMessagesSingleDestination() throws CMCException {
stubFor(post(urlEqualTo("/messages"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"success\",\"notifications\":{\"to\":[\"4102804827\"],\"from\":\"scsrest\",\"trackinginformation\":[{\"destination\":\"4102804827\",\"messagestatus\":\"Message Accepted\",\"messageID\":\"GW1_AVvciGlHRM32pw0Q\",\"messagetext\":\"Test message\"}]}}}")));
List<String> destinations = new ArrayList<String>();
destinations.add("4102804827");
Message message = new Message(destinations, REST_CONNECTION_KEYWORD, "Test message");
HttpResponseWrapper<NotificationsResponse> response = messagingApi.sendMessage(message);
// Verify the response
assertEquals(response.getHttpStatusCode(), 200);
Notifications notifications = response.getResponseBody().getNotifications();
assertEquals(notifications.getFromAddress(),"scsrest");
assertEquals(notifications.getTo().size(),1);
assertEquals(notifications.getTo().get(0),"4102804827");
List<TrackingInformation> trackingInformation = notifications.getTrackingInformation();
assertEquals(trackingInformation.size(),1);
assertEquals(trackingInformation.get(0).getDestination(),"4102804827");
assertEquals(trackingInformation.get(0).getMessageID(),"GW1_AVvciGlHRM32pw0Q");
assertEquals(trackingInformation.get(0).getMessageText(),"Test message");
// Verify the request
List<LoggedRequest> requests = findAll(postRequestedFor(urlMatching("/messages")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "{\"sendmessage\":{\"message\":\"Test message\",\"to\":[\"4102804827\"],\"from\":\"scsrest\"}}");
}
@Test
public void sendMessagesMultipleDestinations() throws CMCException {
stubFor(post(urlEqualTo("/messages"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"success\",\"notifications\":{\"to\":[\"4102804827\",\"4102804828\"],\"from\":\"scsrest\",\"trackinginformation\":[{\"destination\":\"4102804827\",\"messagestatus\":\"Message Accepted\",\"messageID\":\"GW1_AVvciGlHRM32pw0Q\",\"messagetext\":\"Test message\"},{\"destination\":\"4102804828\",\"messagestatus\":\"Message Accepted\",\"messageID\":\"GW1_AVvciGlHRM32Rg0O\",\"messagetext\":\"Test message\"}]}}}")));
List<String> destinations = new ArrayList<String>();
destinations.add("4102804827");
destinations.add("4102804828");
Message message = new Message(destinations, REST_CONNECTION_KEYWORD, "Test message");
message.setNotifyURL("http://customer.com/notifications");
message.setReplyExpiry(60);
HttpResponseWrapper<NotificationsResponse> response = messagingApi.sendMessage(message);
// Verify the response
assertEquals(response.getHttpStatusCode(), 200);
Notifications notifications = response.getResponseBody().getNotifications();
assertEquals(notifications.getFromAddress(),"scsrest");
assertEquals(notifications.getTo().size(),2);
assertEquals(notifications.getTo().get(0),"4102804827");
assertEquals(notifications.getTo().get(1),"4102804828");
List<TrackingInformation> trackingInformation = notifications.getTrackingInformation();
assertEquals(trackingInformation.size(),2);
assertEquals(trackingInformation.get(0).getDestination(),"4102804827");
assertEquals(trackingInformation.get(0).getMessageID(),"GW1_AVvciGlHRM32pw0Q");
assertEquals(trackingInformation.get(0).getMessageText(),"Test message");
assertEquals(trackingInformation.get(1).getDestination(),"4102804828");
assertEquals(trackingInformation.get(1).getMessageID(),"GW1_AVvciGlHRM32Rg0O");
assertEquals(trackingInformation.get(1).getMessageText(),"Test message");
// Verify the request
List<LoggedRequest> requests = findAll(postRequestedFor(urlMatching("/messages")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "{\"sendmessage\":{\"message\":\"Test message\",\"notifyURL\":\"http://customer.com/notifications\",\"to\":[\"4102804827\",\"4102804828\"],\"from\":\"scsrest\",\"replyexpiry\":60}}");
}
@Test
public void getDeliveryNotificationInvalidTrackingID() throws CMCException {
stubFor(get(urlMatching("/notifications/[0-9A-Za-z]+"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"5001\",\"message\":\"Tracking ID Not Found -- Notifications AewVvciGlHRM31jg0K.\"}}")));
HttpResponseWrapper<NotificationsResponse> response = messagingApi.getDeliveryNotifications("AewVvciGlHRM31jg0K");
// Verify the response.
assertEquals(response.getHttpStatusCode(), 404);
assertEquals(response.getResponseBody().getStatus(), "fail");
assertEquals(response.getResponseBody().getCode(), "5001");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/notifications/[0-9A-Za-z]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getDeliveryNotificationValidTrackingID() throws CMCException {
stubFor(get(urlMatching("/notifications/[0-9A-Za-z]+"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"success\",\"notifications\":{\"to\":[\"4102804827\"],\"from\":\"scsrest\",\"trackinginformation\":[{\"destination\":\"4102804827\",\"messagestatus\":\"Message Accepted\",\"messageID\":\"GW1_AVvciGlHRM32pw0Q\",\"messagetext\":\"Test message\"}]}}}")));
HttpResponseWrapper<NotificationsResponse> response = messagingApi.getDeliveryNotifications("AewVvciGlHRM31jg0K");
// Verify the response
assertEquals(response.getHttpStatusCode(), 200);
Notifications notifications = response.getResponseBody().getNotifications();
assertEquals(notifications.getFromAddress(),"scsrest");
assertEquals(notifications.getTo().size(),1);
assertEquals(notifications.getTo().get(0),"4102804827");
List<TrackingInformation> trackingInformation = notifications.getTrackingInformation();
assertEquals(trackingInformation.size(),1);
assertEquals(trackingInformation.get(0).getDestination(),"4102804827");
assertEquals(trackingInformation.get(0).getMessageID(),"GW1_AVvciGlHRM32pw0Q");
assertEquals(trackingInformation.get(0).getMessageText(),"Test message");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/notifications/[0-9A-Za-z]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getDeliveryReceiptInvalidMessageID() throws CMCException {
stubFor(get(urlMatching("/receipts/[0-9A-Za-z,]+"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"2003\",\"message\":\"Message ID Not Found -- Receipts AewVvciGlHRM31jg0K.\"}}")));
List<String> messageIds = new ArrayList<String>();
messageIds.add("AewVvciGlHRM31jg0K");
HttpResponseWrapper<DeliveryReceiptResponse> response = messagingApi.getDeliveryReceipts(messageIds);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 404);
assertEquals(response.getResponseBody().getStatus(), "fail");
assertEquals(response.getResponseBody().getCode(), "2003");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/receipts/[0-9A-Za-z,]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getDeliveryReceiptValidMessageID() throws CMCException {
stubFor(get(urlMatching("/receipts/[0-9A-Za-z,_]+"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"success\",\"deliveryreceipt\":{\"deliverystatuslist\":[{\"deliverydate\":\"2014-05-28T00:00Z\",\"deliverystatus\":\"Undeliverable by Gateway\",\"messageID\":\"GW1_EwGohZtGQpmh8lGB\",\"to\":\"14106277808\"},{\"deliverydate\":\"2014-06-12T00:00Z\",\"deliverystatus\":\"Delivered to Handset\",\"messageID\":\"GW1_EwBpkTJGkGVEsZ1U\",\"to\":\"14103334444\"}]}}}")));
List<String> messageIds = new ArrayList<String>();
messageIds.add("GW1_EwGohZtGQpmh8lGB");
messageIds.add("GW1_EwBpkTJGkGVEsZ1U");
HttpResponseWrapper<DeliveryReceiptResponse> response = messagingApi.getDeliveryReceipts(messageIds);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 200);
assertEquals(response.getResponseBody().getStatus(),"success");
DeliveryReceipt deliveryReceipt = response.getResponseBody().getDeliveryReceipt();
List<MessageStatus> deliverystatuslist = deliveryReceipt.getDeliverystatuslist();
assertEquals(deliverystatuslist.size(),2);
assertEquals(deliverystatuslist.get(0).getMin(),"14106277808");
assertEquals(deliverystatuslist.get(0).getDeliveryStatus(),"Undeliverable by Gateway");
assertEquals(deliverystatuslist.get(0).getMessageID(),"GW1_EwGohZtGQpmh8lGB");
assertEquals(deliverystatuslist.get(0).getDeliveryDate(),"2014-05-28T00:00Z");
assertEquals(deliverystatuslist.get(1).getMin(),"14103334444");
assertEquals(deliverystatuslist.get(1).getDeliveryStatus(),"Delivered to Handset");
assertEquals(deliverystatuslist.get(1).getMessageID(),"GW1_EwBpkTJGkGVEsZ1U");
assertEquals(deliverystatuslist.get(1).getDeliveryDate(),"2014-06-12T00:00Z");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/receipts/[0-9A-Za-z,_]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getRepliesInvalidMessageID() throws CMCException {
stubFor(get(urlMatching("/replies/[0-9A-Za-z]+"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"success\",\"replies\":{\"numberofreplies\":0}}}")));
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getReplies("AewVvciGlHRM31jg0K");
// Verify the response.
assertEquals(response.getHttpStatusCode(), 200);
assertEquals(response.getResponseBody().getStatus(), "success");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/replies/[0-9A-Za-z]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getRepliesValidMessageID() throws CMCException {
stubFor(get(urlMatching("/replies/[0-9A-Za-z_]+"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\": \"success\",\"replies\":{\"numberofreplies\": 2,\"replylist\":[{\"from\": \"14106277808\",\"text\": \"Reply back\",\"date\": \"2015-07-13T00:00Z\"},{\"from\": \"14106277809\",\"text\":\"Reply back again\",\"date\":\"2015-09-13T00:00Z\"}]}}}")));
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getReplies("GW1_EwGohZtGQpmh8lGB");
// Verify the response.
assertEquals(response.getHttpStatusCode(), 200);
assertEquals(response.getResponseBody().getStatus(),"success");
MessageReplies messageReplies = response.getResponseBody().getMessageReplies();
List<MessageReply> replylist = messageReplies.getReplies();
assertEquals(replylist.size(),2);
assertEquals(replylist.get(0).getMin(),"14106277808");
assertEquals(replylist.get(0).getMsgText(),"Reply back");
assertEquals(replylist.get(0).getReplyDate(),"2015-07-13T00:00Z");
assertEquals(replylist.get(1).getMin(),"14106277809");
assertEquals(replylist.get(1).getMsgText(),"Reply back again");
assertEquals(replylist.get(1).getReplyDate(),"2015-09-13T00:00Z");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/replies/[0-9A-Za-z_]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesInvalidProgram() throws CMCException {
stubFor(get(urlMatching("/programreplies/[0-9A-Za-z]+"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"4003\",\"message\":\"Program not found 1.\"}}")));
ProgramReply programReply = new ProgramReply("1");
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 404);
assertEquals(response.getResponseBody().getStatus(), "fail");
assertEquals(response.getResponseBody().getCode(), "4003");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/programreplies/[0-9A-Za-z]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesValidProgram() throws CMCException {
stubFor(get(urlMatching("/programreplies/[0-9A-Za-z]+"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\": \"success\",\"replies\":{\"numberofreplies\": 2,\"replylist\":[{\"from\": \"14106277808\",\"text\": \"Reply back\",\"date\": \"2015-07-13T00:00Z\"},{\"from\": \"14106277809\",\"text\":\"Reply back again\",\"date\":\"2015-09-13T00:00Z\"}]}}}")));
ProgramReply programReply = new ProgramReply("GW1EwGohZtGQpmh8lGB");
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 200);
assertEquals(response.getResponseBody().getStatus(),"success");
MessageReplies messageReplies = response.getResponseBody().getMessageReplies();
List<MessageReply> replylist = messageReplies.getReplies();
assertEquals(replylist.size(),2);
assertEquals(replylist.get(0).getMin(),"14106277808");
assertEquals(replylist.get(0).getMsgText(),"Reply back");
assertEquals(replylist.get(0).getReplyDate(),"2015-07-13T00:00Z");
assertEquals(replylist.get(1).getMin(),"14106277809");
assertEquals(replylist.get(1).getMsgText(),"Reply back again");
assertEquals(replylist.get(1).getReplyDate(),"2015-09-13T00:00Z");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/programreplies/[0-9A-Za-z]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesInvalidProgramWithMdns() throws CMCException {
stubFor(get(urlMatching("/programreplies/[0-9A-Za-z]+/[0-9,]+"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"4003\",\"message\":\"Program not found 1.\"}}")));
ProgramReply programReply = new ProgramReply("1");
List<String> destinations = new ArrayList<String>();
destinations.add("14106277808");
destinations.add("14106277809");
programReply.setDestinations(destinations);
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 404);
assertEquals(response.getResponseBody().getStatus(), "fail");
assertEquals(response.getResponseBody().getCode(), "4003");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/programreplies/[0-9A-Za-z]+/[0-9,]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesValidProgramWithMdns() throws CMCException {
stubFor(get(urlMatching("/programreplies/[0-9A-Za-z]+/[0-9,]+"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\": \"success\",\"replies\":{\"numberofreplies\": 2,\"replylist\":[{\"from\": \"14106277808\",\"text\": \"Reply back\",\"date\": \"2015-07-13T00:00Z\"},{\"from\": \"14106277809\",\"text\":\"Reply back again\",\"date\":\"2015-09-13T00:00Z\"}]}}}")));
ProgramReply programReply = new ProgramReply("GW1EwGohZtGQpmh8lGB");
List<String> destinations = new ArrayList<String>();
destinations.add("14106277808");
destinations.add("14106277809");
programReply.setDestinations(destinations);
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 200);
assertEquals(response.getResponseBody().getStatus(),"success");
MessageReplies messageReplies = response.getResponseBody().getMessageReplies();
List<MessageReply> replylist = messageReplies.getReplies();
assertEquals(replylist.size(),2);
assertEquals(replylist.get(0).getMin(),"14106277808");
assertEquals(replylist.get(0).getMsgText(),"Reply back");
assertEquals(replylist.get(0).getReplyDate(),"2015-07-13T00:00Z");
assertEquals(replylist.get(1).getMin(),"14106277809");
assertEquals(replylist.get(1).getMsgText(),"Reply back again");
assertEquals(replylist.get(1).getReplyDate(),"2015-09-13T00:00Z");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlMatching("/programreplies/[0-9A-Za-z]+/[0-9,]+")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesInvalidProgramWithMinutes() throws CMCException {
stubFor(get(urlPathMatching("/programreplies(.*)"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"4003\",\"message\":\"Program not found 1.\"}}")));
ProgramReply programReply = new ProgramReply("1");
programReply.setMinutes("7");
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 404);
assertEquals(response.getResponseBody().getStatus(), "fail");
assertEquals(response.getResponseBody().getCode(), "4003");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/programreplies(.*)")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesValidProgramWithMinutes() throws CMCException {
stubFor(get(urlPathMatching("/programreplies(.*)"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\": \"success\",\"replies\":{\"numberofreplies\": 2,\"replylist\":[{\"from\": \"14106277808\",\"text\": \"Reply back\",\"date\": \"2015-07-13T00:00Z\"},{\"from\": \"14106277809\",\"text\":\"Reply back again\",\"date\":\"2015-09-13T00:00Z\"}]}}}")));
ProgramReply programReply = new ProgramReply("GW1EwGohZtGQpmh8lGB");
programReply.setMinutes("7");
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 200);
assertEquals(response.getResponseBody().getStatus(),"success");
MessageReplies messageReplies = response.getResponseBody().getMessageReplies();
List<MessageReply> replylist = messageReplies.getReplies();
assertEquals(replylist.size(),2);
assertEquals(replylist.get(0).getMin(),"14106277808");
assertEquals(replylist.get(0).getMsgText(),"Reply back");
assertEquals(replylist.get(0).getReplyDate(),"2015-07-13T00:00Z");
assertEquals(replylist.get(1).getMin(),"14106277809");
assertEquals(replylist.get(1).getMsgText(),"Reply back again");
assertEquals(replylist.get(1).getReplyDate(),"2015-09-13T00:00Z");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/programreplies(.*)")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesInvalidProgramWithMdnsAndMinutes() throws CMCException {
stubFor(get(urlPathMatching("/programreplies(.*)"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\":\"fail\",\"code\":\"4003\",\"message\":\"Program not found 1.\"}}")));
ProgramReply programReply = new ProgramReply("1");
List<String> destinations = new ArrayList<String>();
destinations.add("14106277808");
destinations.add("14106277809");
programReply.setDestinations(destinations);
programReply.setMinutes("7");
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 404);
assertEquals(response.getResponseBody().getStatus(), "fail");
assertEquals(response.getResponseBody().getCode(), "4003");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/programreplies(.*)")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
@Test
public void getProgramRepliesValidProgramWithMdnsAndMinutes() throws CMCException {
stubFor(get(urlPathMatching("/programreplies(.*)"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"response\":{\"status\": \"success\",\"replies\":{\"numberofreplies\": 2,\"replylist\":[{\"from\": \"14106277808\",\"text\": \"Reply back\",\"date\": \"2015-07-13T00:00Z\"},{\"from\": \"14106277809\",\"text\":\"Reply back again\",\"date\":\"2015-09-13T00:00Z\"}]}}}")));
ProgramReply programReply = new ProgramReply("GW1EwGohZtGQpmh8lGB");
List<String> destinations = new ArrayList<String>();
destinations.add("14106277808");
destinations.add("14106277809");
programReply.setDestinations(destinations);
programReply.setMinutes("7");
HttpResponseWrapper<MessageRepliesResponse> response = messagingApi.getProgramReplies(programReply);
// Verify the response.
assertEquals(response.getHttpStatusCode(), 200);
assertEquals(response.getResponseBody().getStatus(),"success");
MessageReplies messageReplies = response.getResponseBody().getMessageReplies();
List<MessageReply> replylist = messageReplies.getReplies();
assertEquals(replylist.size(),2);
assertEquals(replylist.get(0).getMin(),"14106277808");
assertEquals(replylist.get(0).getMsgText(),"Reply back");
assertEquals(replylist.get(0).getReplyDate(),"2015-07-13T00:00Z");
assertEquals(replylist.get(1).getMin(),"14106277809");
assertEquals(replylist.get(1).getMsgText(),"Reply back again");
assertEquals(replylist.get(1).getReplyDate(),"2015-09-13T00:00Z");
// Verify the request
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/programreplies(.*)")));
assertEquals(requests.size(), 1);
assertEquals(requests.get(0).getBodyAsString(), "");
}
}
| mit |
OzanKurt/Citelic-742 | src/com/citelic/game/entity/player/content/controllers/impl/events/DeathEvent.java | 10403 | package com.citelic.game.entity.player.content.controllers.impl.events;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import com.citelic.GameConstants;
import com.citelic.cores.CoresManager;
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.npc.impl.others.GraveStone;
import com.citelic.game.entity.player.Player;
import com.citelic.game.entity.player.content.actions.skills.magic.Magic;
import com.citelic.game.entity.player.content.controllers.Controller;
import com.citelic.game.entity.player.item.FloorItem;
import com.citelic.game.entity.player.item.Item;
import com.citelic.game.map.MapBuilder;
import com.citelic.game.map.objects.GameObject;
import com.citelic.game.map.tile.Tile;
import com.citelic.networking.codec.decode.WorldPacketsDecoder;
import com.citelic.utility.Logger;
import com.citelic.utility.Utilities;
public class DeathEvent extends Controller {
public static final Tile[] HUBS = {
// Lumbridge
new Tile(3222, 3219, 0)
// Varrock
, new Tile(3212, 3422, 0)
// EDGEVILLE
, new Tile(3094, 3502, 0)
// FALADOR
, new Tile(2965, 3386, 0)
// SEERS VILLAGE
, new Tile(2725, 3491, 0)
// ARDOUDGE
, new Tile(2662, 3305, 0)
// YANNILE
, new Tile(2605, 3093, 0)
// KELDAGRIM
, new Tile(2845, 10210, 0)
// DORGESH-KAN
, new Tile(2720, 5351, 0)
// LYETYA
, new Tile(2341, 3171, 0)
// ETCETERIA
, new Tile(2614, 3894, 0)
// DAEMONHEIM
, new Tile(3450, 3718, 0)
// CANIFIS
, new Tile(3496, 3489, 0)
// THZAAR AREA
, new Tile(4651, 5151, 0)
// BURTHORPE
, new Tile(2889, 3528, 0)
// ALKARID
, new Tile(3275, 3166, 0)
// DRAYNOR VILLAGE
, new Tile(3079, 3250, 0) };
// 3796 - 0 - Lumbridge Castle - {1=Falador Castle, 2=Camelot, 3=Soul Wars,
// 4=Burthorpe}
public static final Tile[] RESPAWN_LOCATIONS = { new Tile(3222, 3219, 0),
new Tile(2971, 3343, 0), new Tile(2758, 3486, 0),
new Tile(1891, 3177, 0), new Tile(2889, 3528, 0) };
private int[] boundChuncks;
private Stages stage;
private Integer[][] slots;
private int currentHub;
public static int getCurrentHub(Tile tile) {
int nearestHub = -1;
int distance = 0;
for (int i = 0; i < DeathEvent.HUBS.length; i++) {
int d = Utilities.getDistance(DeathEvent.HUBS[i], tile);
if (nearestHub == -1 || d < distance) {
distance = d;
nearestHub = i;
}
}
return nearestHub;
}
public static Tile getRespawnHub(Player player) {
return DeathEvent.HUBS[DeathEvent.getCurrentHub(player)];
}
@Override
public boolean canEquip(int slotId, int itemId) {
return false;
}
@Override
public boolean canPlayerOption1(Player target) {
return false;
}
public boolean canPlayerOption2(Player target) {
return false;
}
public boolean canPlayerOption3(Player target) {
return false;
}
public boolean canPlayerOption4(Player target) {
return false;
}
public boolean canTakeItem(FloorItem item) {
return false;
}
public void destroyRoom() {
if (stage != Stages.RUNNING)
return;
stage = Stages.DESTROYING;
CoresManager.slowExecutor.schedule(new Runnable() {
@Override
public void run() {
try {
MapBuilder.destroyMap(boundChuncks[0], boundChuncks[1], 8,
8);
} catch (Throwable e) {
Logger.handle(e);
}
}
}, 1200, TimeUnit.MILLISECONDS);
}
@Override
public void forceClose() {
destroyRoom();
}
public Tile getDeathTile() {
if (getArguments() == null || getArguments().length < 2)
return GameConstants.START_PLAYER_LOCATION;
return (Tile) getArguments()[0];
}
public int getProtectSlots() {
return -1;
}
public void getReadyToRespawn() {
slots = GraveStone.getItemSlotsKeptOnDeath(player, false, hadSkull(),
player.getPrayer().isProtectingItem());
player.getInterfaceManager().sendInterface(18);
if (slots[0].length > 0) {
player.getPackets().sendConfigByFile(9227, slots[0].length);
sendProtectedItems();
} else {
player.getPackets().sendConfigByFile(9222, -1);
player.getPackets().sendConfigByFile(9227, 1);
}
player.getPackets().sendConfigByFile(668, 1); // unlocks camelot respawn
// spot
player.getPackets().sendConfig(105, -1);
player.getPackets().sendConfigByFile(9231,
currentHub = DeathEvent.getCurrentHub(getDeathTile()));
player.getPackets().sendUnlockIComponentOptionSlots(18, 9, 0,
slots[0].length, 0);
player.getPackets().sendUnlockIComponentOptionSlots(18, 17, 0, 100, 0);
player.getPackets().sendUnlockIComponentOptionSlots(18, 45, 0,
DeathEvent.RESPAWN_LOCATIONS.length, 0);
player.setCloseInterfacesEvent(new Runnable() {
@Override
public void run() {
Tile respawnTile = currentHub >= 256 ? DeathEvent.RESPAWN_LOCATIONS[currentHub - 256]
: DeathEvent.HUBS[currentHub];
synchronized (slots) {
player.sendItemsOnDeath(null, getDeathTile(), respawnTile,
false, slots);
}
player.setCloseInterfacesEvent(null);
Magic.sendObjectTeleportSpell(player, true, respawnTile);
}
});
}
public boolean hadSkull() {
if (getArguments() == null || getArguments().length < 2)
return false;
return (boolean) getArguments()[1];
}
public void loadRoom() {
stage = Stages.LOADING;
player.lock(); // locks player
CoresManager.slowExecutor.execute(new Runnable() {
@Override
public void run() {
try {
boundChuncks = MapBuilder.findEmptyChunkBound(2, 2);
MapBuilder.copyMap(246, 662, boundChuncks[0],
boundChuncks[1], 2, 2, new int[1], new int[1]);
player.reset();
player.setNextTile(new Tile(boundChuncks[0] * 8 + 10,
boundChuncks[1] * 8 + 6, 0));
// 1delay because player cant walk while teleing :p, +
// possible
// issues avoid
EngineTaskManager.schedule(new EngineTask() {
@Override
public void run() {
player.setNextAnimation(new Animation(-1));
player.getMusicsManager().playMusic(683);
player.getPackets().sendMiniMapStatus(2);
sendInterfaces();
player.unlock(); // unlocks player
stage = Stages.RUNNING;
}
}, 1);
} catch (Throwable e) {
Logger.handle(e);
}
}
});
}
@Override
public boolean login() {
loadRoom();
return false;
}
@Override
public boolean logout() {
player.setLocation(new Tile(1978, 5302, 0));
destroyRoom();
return false;
}
@Override
public void magicTeleported(int type) {
destroyRoom();
player.getPackets().sendMiniMapStatus(0);
player.getInterfaceManager().sendCombatStyles();
player.getCombatDefinitions().sendUnlockAttackStylesButtons();
player.getInterfaceManager().sendTaskSystem();
player.getInterfaceManager().sendSkills();
player.getInterfaceManager().sendInventory();
player.getInventory().unlockInventoryOptions();
player.getInterfaceManager().sendEquipment();
player.getInterfaceManager().sendPrayerBook();
player.getPrayer().unlockPrayerBookButtons();
player.getInterfaceManager().sendMagicBook();
player.getInterfaceManager().sendEmotes();
player.getEmotesManager().unlockEmotesBook();
removeController();
}
/**
* return process normaly
*/
@Override
public boolean processButtonClick(int interfaceId, int componentId,
int slotId, int slotId2, int packetId) {
if (interfaceId == 18) {
if (componentId == 9) {
if (packetId == WorldPacketsDecoder.ACTION_BUTTON1_PACKET) {
unprotect(slotId);
}
} else if (componentId == 17) {
if (packetId == WorldPacketsDecoder.ACTION_BUTTON1_PACKET) {
protect(slotId2);
}
} else if (componentId == 45) {
// slotid - 1
if (slotId > DeathEvent.RESPAWN_LOCATIONS.length)
return false;
currentHub = 255 + slotId;
}
return false;
}
return true;
}
@Override
public boolean processItemTeleport(Tile toTile) {
return false;
}
@Override
public boolean processMagicTeleport(Tile toTile) {
return false;
}
/**
* return process normaly
*/
@Override
public boolean processObjectClick1(GameObject object) {
if (object.getId() == 45803) {
if (getArguments() == null || getArguments().length < 2) {
Magic.sendObjectTeleportSpell(player, true,
GameConstants.START_PLAYER_LOCATION);
} else {
getReadyToRespawn();
}
return false;
}
return true;
}
public void protect(int itemId) {
synchronized (slots) {
int slot = -1;
for (int i = 0; i < slots[1].length; i++) {
Item item = slots[1][i] >= 16 ? player.getInventory().getItem(
slots[1][i] - 16) : player.getEquipment().getItem(
slots[1][i] - 1);
if (item == null) {
continue;
}
if (item.getId() == itemId) {
slot = i;
break;
}
}
if (slot == -1 || getProtectSlots() <= slots[0].length)
return;
slots[0] = Arrays.copyOf(slots[0], slots[0].length + 1);
slots[0][slots[0].length - 1] = slots[1][slot];
Integer[] lItems = new Integer[slots[1].length - 1];
System.arraycopy(slots[1], 0, lItems, 0, slot);
System.arraycopy(slots[1], slot + 1, lItems, slot, lItems.length
- slot);
slots[1] = lItems;
sendProtectedItems();
}
}
@Override
public void sendInterfaces() {
player.getInterfaceManager().closeCombatStyles();
player.getInterfaceManager().closeTaskSystem();
player.getInterfaceManager().closeSkills();
player.getInterfaceManager().closeInventory();
player.getInterfaceManager().closeEquipment();
player.getInterfaceManager().closePrayerBook();
player.getInterfaceManager().closeMagicBook();
player.getInterfaceManager().closeEmotes();
}
public void sendProtectedItems() {
for (int i = 0; i < getProtectSlots(); i++) {
player.getPackets().sendConfigByFile(9222 + i,
i >= slots[0].length ? -1 : slots[0][i]);
}
}
@Override
public void start() {
loadRoom();
}
public void unprotect(int slot) {
synchronized (slots) {
if (slot >= slots[0].length)
return;
slots[1] = Arrays.copyOf(slots[1], slots[1].length + 1);
slots[1][slots[1].length - 1] = slots[0][slot];
Integer[] pItems = new Integer[slots[0].length - 1];
System.arraycopy(slots[0], 0, pItems, 0, slot);
System.arraycopy(slots[0], slot + 1, pItems, slot, pItems.length
- slot);
slots[0] = pItems;
sendProtectedItems();
}
}
private static enum Stages {
LOADING, RUNNING, DESTROYING
}
}
| mit |
sriharshachilakapati/WebGL4J | webgl4j/src/main/java/com/shc/webgl4j/client/OES_texture_half_float_linear.java | 3160 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2015 Sri Harsha Chilakapati
*
* 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.shc.webgl4j.client;
/**
* @author Sri Harsha Chilakapati
*/
public final class OES_texture_half_float_linear
{
/* Prevent instantiation */
private OES_texture_half_float_linear()
{
}
public static boolean isSupported()
{
if (!WebGL10.isSupported())
return false;
if (!WebGL10.isContextCompatible())
throw new IllegalStateException("You must have a WebGL context >= 1.0 to check if extension is supported.");
for (String supportedExtension : WebGL10.glGetSupportedExtensions())
{
switch (supportedExtension)
{
case "OES_texture_half_float_linear":
case "O_OES_texture_half_float_linear":
case "IE_OES_texture_half_float_linear":
case "MOZ_OES_texture_half_float_linear":
case "WEBKIT_OES_texture_half_float_linear":
return true;
}
}
return false;
}
public static void enableExtension()
{
if (!WebGL10.isContextCompatible())
throw new IllegalStateException("You must have a WebGL context >= 1.0 to enable this extension.");
if (!isSupported())
throw new RuntimeException("This browser does not support the OES_texture_half_float_linear extension.");
if (!isExtensionEnabled())
nEnableExtension();
}
public static native boolean isExtensionEnabled() /*-{
return typeof ($wnd.gl.othfl_ext) !== 'undefined';
}-*/;
private static native void nEnableExtension() /*-{
$wnd.gl.othfl_ext = $wnd.gl.getExtension('OES_texture_half_float_linear') ||
$wnd.gl.getExtension('O_OES_texture_half_float_linear') ||
$wnd.gl.getExtension('IE_OES_texture_half_float_linear') ||
$wnd.gl.getExtension('MOZ_OES_texture_half_float_linear') ||
$wnd.gl.getExtension('WEBKIT_OES_texture_half_float_linear');
}-*/;
}
| mit |
Abestanis/APython | app/src/main/java/com/apython/python/pythonhost/interpreter/app/AppActivityProxy.java | 47196 | package com.apython.python.pythonhost.interpreter.app;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.LoaderManager;
import android.app.PendingIntent;
import android.app.SharedElementCallback;
import android.app.TaskStackBuilder;
import android.app.VoiceInteractor;
import android.app.assist.AssistContent;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PersistableBundle;
import android.os.UserHandle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.transition.Scene;
import android.transition.TransitionManager;
import android.util.AttributeSet;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Toolbar;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
/**
* This Activity proxies most calls to the provided real activity,
* but intercepts calls related to the context and the classloader.
*
* Created by Sebastian on 09.09.2016.
*/
@SuppressLint({"Registered", "MissingPermission"})
@SuppressWarnings("deprecation")
public class AppActivityProxy extends Activity {
private final Activity wrappedActivity;
private final Context context;
public AppActivityProxy(Activity wrappedActivity, Context context) {
super();
this.wrappedActivity = wrappedActivity;
this.context = context;
}
@Override
public ClassLoader getClassLoader() {
return context.getClassLoader();
}
@Override
public Context getBaseContext() {
return context;
}
@Override
public Context getApplicationContext() {
return context;
}
@Override
public Intent getIntent() {
return wrappedActivity.getIntent();
}
@Override
public void setIntent(Intent newIntent) {
wrappedActivity.setIntent(newIntent);
}
@Override
public WindowManager getWindowManager() {
return wrappedActivity.getWindowManager();
}
@Override
public Window getWindow() {
return wrappedActivity.getWindow();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public LoaderManager getLoaderManager() {
return wrappedActivity.getLoaderManager();
}
@Nullable
@Override
public View getCurrentFocus() {
return wrappedActivity.getCurrentFocus();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
wrappedActivity.onCreate(savedInstanceState, persistentState);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
wrappedActivity.onRestoreInstanceState(savedInstanceState, persistentState);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
wrappedActivity.onPostCreate(savedInstanceState, persistentState);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onStateNotSaved() {
wrappedActivity.onStateNotSaved();
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public boolean isVoiceInteraction() {
return wrappedActivity.isVoiceInteraction();
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public boolean isVoiceInteractionRoot() {
return wrappedActivity.isVoiceInteractionRoot();
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public VoiceInteractor getVoiceInteractor() {
return wrappedActivity.getVoiceInteractor();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
wrappedActivity.onSaveInstanceState(outState, outPersistentState);
}
@Override
public boolean onCreateThumbnail(Bitmap outBitmap, Canvas canvas) {
return wrappedActivity.onCreateThumbnail(outBitmap, canvas);
}
@Nullable
@Override
public CharSequence onCreateDescription() {
return wrappedActivity.onCreateDescription();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onProvideAssistData(Bundle data) {
wrappedActivity.onProvideAssistData(data);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onProvideAssistContent(AssistContent outContent) {
wrappedActivity.onProvideAssistContent(outContent);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public boolean showAssist(Bundle args) {
return wrappedActivity.showAssist(args);
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void reportFullyDrawn() {
wrappedActivity.reportFullyDrawn();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
wrappedActivity.onConfigurationChanged(newConfig);
}
@Override
public int getChangingConfigurations() {
return wrappedActivity.getChangingConfigurations();
}
@Nullable
@Override
public Object getLastNonConfigurationInstance() {
return wrappedActivity.getLastNonConfigurationInstance();
}
@Override
public Object onRetainNonConfigurationInstance() {
return wrappedActivity.onRetainNonConfigurationInstance();
}
@Override
public void onLowMemory() {
wrappedActivity.onLowMemory();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void onTrimMemory(int level) {
wrappedActivity.onTrimMemory(level);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public FragmentManager getFragmentManager() {
return wrappedActivity.getFragmentManager();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onAttachFragment(Fragment fragment) {
wrappedActivity.onAttachFragment(fragment);
}
@Override
public void startManagingCursor(Cursor c) {
wrappedActivity.startManagingCursor(c);
}
@Override
public void stopManagingCursor(Cursor c) {
wrappedActivity.stopManagingCursor(c);
}
@Override
public <T extends View> T findViewById(int id) {
return wrappedActivity.findViewById(id);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Nullable
@Override
public ActionBar getActionBar() {
return wrappedActivity.getActionBar();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void setActionBar(Toolbar toolbar) {
wrappedActivity.setActionBar(toolbar);
}
@Override
public void setContentView(int layoutResID) {
wrappedActivity.setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
wrappedActivity.setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
wrappedActivity.setContentView(view, params);
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
wrappedActivity.addContentView(view, params);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public TransitionManager getContentTransitionManager() {
return wrappedActivity.getContentTransitionManager();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void setContentTransitionManager(TransitionManager tm) {
wrappedActivity.setContentTransitionManager(tm);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public Scene getContentScene() {
return wrappedActivity.getContentScene();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void setFinishOnTouchOutside(boolean finish) {
wrappedActivity.setFinishOnTouchOutside(finish);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return wrappedActivity.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
return wrappedActivity.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
return wrappedActivity.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
return wrappedActivity.onKeyMultiple(keyCode, repeatCount, event);
}
@Override
public void onBackPressed() {
wrappedActivity.onBackPressed();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean onKeyShortcut(int keyCode, KeyEvent event) {
return wrappedActivity.onKeyShortcut(keyCode, event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return wrappedActivity.onTouchEvent(event);
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
return wrappedActivity.onTrackballEvent(event);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
return wrappedActivity.onGenericMotionEvent(event);
}
@Override
public void onUserInteraction() {
wrappedActivity.onUserInteraction();
}
@Override
public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
wrappedActivity.onWindowAttributesChanged(params);
}
@Override
public void onContentChanged() {
wrappedActivity.onContentChanged();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
wrappedActivity.onWindowFocusChanged(hasFocus);
}
@Override
public void onAttachedToWindow() {
wrappedActivity.onAttachedToWindow();
}
@Override
public void onDetachedFromWindow() {
wrappedActivity.onDetachedFromWindow();
}
@Override
public boolean hasWindowFocus() {
return wrappedActivity.hasWindowFocus();
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
return wrappedActivity.dispatchKeyEvent(event);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return wrappedActivity.dispatchKeyShortcutEvent(event);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return wrappedActivity.dispatchTouchEvent(ev);
}
@Override
public boolean dispatchTrackballEvent(MotionEvent ev) {
return wrappedActivity.dispatchTrackballEvent(ev);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
public boolean dispatchGenericMotionEvent(MotionEvent ev) {
return wrappedActivity.dispatchGenericMotionEvent(ev);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return wrappedActivity.dispatchPopulateAccessibilityEvent(event);
}
@Nullable
@Override
public View onCreatePanelView(int featureId) {
return wrappedActivity.onCreatePanelView(featureId);
}
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
return wrappedActivity.onCreatePanelMenu(featureId, menu);
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
return wrappedActivity.onPreparePanel(featureId, view, menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return wrappedActivity.onMenuOpened(featureId, menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
return wrappedActivity.onMenuItemSelected(featureId, item);
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
wrappedActivity.onPanelClosed(featureId, menu);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void invalidateOptionsMenu() {
wrappedActivity.invalidateOptionsMenu();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return wrappedActivity.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return wrappedActivity.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return wrappedActivity.onOptionsItemSelected(item);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onNavigateUp() {
return wrappedActivity.onNavigateUp();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onNavigateUpFromChild(Activity child) {
return wrappedActivity.onNavigateUpFromChild(child);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCreateNavigateUpTaskStack(TaskStackBuilder builder) {
wrappedActivity.onCreateNavigateUpTaskStack(builder);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onPrepareNavigateUpTaskStack(TaskStackBuilder builder) {
wrappedActivity.onPrepareNavigateUpTaskStack(builder);
}
@Override
public void onOptionsMenuClosed(Menu menu) {
wrappedActivity.onOptionsMenuClosed(menu);
}
@Override
public void openOptionsMenu() {
wrappedActivity.openOptionsMenu();
}
@Override
public void closeOptionsMenu() {
wrappedActivity.closeOptionsMenu();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
wrappedActivity.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public void registerForContextMenu(View view) {
wrappedActivity.registerForContextMenu(view);
}
@Override
public void unregisterForContextMenu(View view) {
wrappedActivity.unregisterForContextMenu(view);
}
@Override
public void openContextMenu(View view) {
wrappedActivity.openContextMenu(view);
}
@Override
public void closeContextMenu() {
wrappedActivity.closeContextMenu();
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return wrappedActivity.onContextItemSelected(item);
}
@Override
public void onContextMenuClosed(Menu menu) {
wrappedActivity.onContextMenuClosed(menu);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public boolean onSearchRequested(SearchEvent searchEvent) {
return wrappedActivity.onSearchRequested(searchEvent);
}
@Override
public boolean onSearchRequested() {
return wrappedActivity.onSearchRequested();
}
@Override
public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) {
wrappedActivity.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
}
@Override
public void triggerSearch(String query, Bundle appSearchData) {
wrappedActivity.triggerSearch(query, appSearchData);
}
@Override
public void takeKeyEvents(boolean get) {
wrappedActivity.takeKeyEvents(get);
}
@NonNull
@Override
public LayoutInflater getLayoutInflater() {
return wrappedActivity.getLayoutInflater();
}
@NonNull
@Override
public MenuInflater getMenuInflater() {
return wrappedActivity.getMenuInflater();
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
wrappedActivity.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
return wrappedActivity.shouldShowRequestPermissionRationale(permission);
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
wrappedActivity.startActivityForResult(intent, requestCode);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
wrappedActivity.startActivityForResult(intent, requestCode, options);
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException {
wrappedActivity.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException {
wrappedActivity.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags, options);
}
@Override
public void startActivity(Intent intent) {
wrappedActivity.startActivity(intent);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startActivity(Intent intent, Bundle options) {
wrappedActivity.startActivity(intent, options);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void startActivities(Intent[] intents) {
wrappedActivity.startActivities(intents);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startActivities(Intent[] intents, Bundle options) {
wrappedActivity.startActivities(intents, options);
}
@Override
public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException {
wrappedActivity.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException {
wrappedActivity.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, options);
}
@Override
public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode) {
return wrappedActivity.startActivityIfNeeded(intent, requestCode);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean startActivityIfNeeded(@NonNull Intent intent, int requestCode, Bundle options) {
return wrappedActivity.startActivityIfNeeded(intent, requestCode, options);
}
@Override
public boolean startNextMatchingActivity(@NonNull Intent intent) {
return wrappedActivity.startNextMatchingActivity(intent);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean startNextMatchingActivity(@NonNull Intent intent, Bundle options) {
return wrappedActivity.startNextMatchingActivity(intent, options);
}
@Override
public void startActivityFromChild(@NonNull Activity child, Intent intent, int requestCode) {
wrappedActivity.startActivityFromChild(child, intent, requestCode);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startActivityFromChild(@NonNull Activity child, Intent intent, int requestCode, Bundle options) {
wrappedActivity.startActivityFromChild(child, intent, requestCode, options);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent, int requestCode) {
wrappedActivity.startActivityFromFragment(fragment, intent, requestCode);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startActivityFromFragment(@NonNull Fragment fragment, Intent intent, int requestCode, Bundle options) {
wrappedActivity.startActivityFromFragment(fragment, intent, requestCode, options);
}
@Override
public void startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException {
wrappedActivity.startIntentSenderFromChild(child, intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void startIntentSenderFromChild(Activity child, IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException {
wrappedActivity.startIntentSenderFromChild(child, intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags, options);
}
@Override
public void overridePendingTransition(int enterAnim, int exitAnim) {
wrappedActivity.overridePendingTransition(enterAnim, exitAnim);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
@Nullable
@Override
public Uri getReferrer() {
return wrappedActivity.getReferrer();
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public Uri onProvideReferrer() {
return wrappedActivity.onProvideReferrer();
}
@Nullable
@Override
public String getCallingPackage() {
return wrappedActivity.getCallingPackage();
}
@Nullable
@Override
public ComponentName getCallingActivity() {
return wrappedActivity.getCallingActivity();
}
@Override
public void setVisible(boolean visible) {
wrappedActivity.setVisible(visible);
}
@Override
public boolean isFinishing() {
return wrappedActivity.isFinishing();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public boolean isDestroyed() {
return wrappedActivity.isDestroyed();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean isChangingConfigurations() {
return wrappedActivity.isChangingConfigurations();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void recreate() {
wrappedActivity.recreate();
}
@Override
public void finish() {
wrappedActivity.finish();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void finishAffinity() {
wrappedActivity.finishAffinity();
}
@Override
public void finishFromChild(Activity child) {
wrappedActivity.finishFromChild(child);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void finishAfterTransition() {
wrappedActivity.finishAfterTransition();
}
@Override
public void finishActivity(int requestCode) {
wrappedActivity.finishActivity(requestCode);
}
@Override
public void finishActivityFromChild(@NonNull Activity child, int requestCode) {
wrappedActivity.finishActivityFromChild(child, requestCode);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void finishAndRemoveTask() {
wrappedActivity.finishAndRemoveTask();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean releaseInstance() {
return wrappedActivity.releaseInstance();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onActivityReenter(int resultCode, Intent data) {
wrappedActivity.onActivityReenter(resultCode, data);
}
@Override
public PendingIntent createPendingResult(int requestCode, @NonNull Intent data, int flags) {
return wrappedActivity.createPendingResult(requestCode, data, flags);
}
@Override
public void setRequestedOrientation(int requestedOrientation) {
wrappedActivity.setRequestedOrientation(requestedOrientation);
}
@Override
public int getRequestedOrientation() {
return wrappedActivity.getRequestedOrientation();
}
@Override
public int getTaskId() {
return wrappedActivity.getTaskId();
}
@Override
public boolean isTaskRoot() {
return wrappedActivity.isTaskRoot();
}
@Override
public boolean moveTaskToBack(boolean nonRoot) {
return wrappedActivity.moveTaskToBack(nonRoot);
}
@NonNull
@Override
public String getLocalClassName() {
return wrappedActivity.getLocalClassName();
}
@Override
public ComponentName getComponentName() {
return wrappedActivity.getComponentName();
}
@Override
public SharedPreferences getPreferences(int mode) {
return wrappedActivity.getPreferences(mode);
}
@Override
public Object getSystemService(@NonNull String name) {
return wrappedActivity.getSystemService(name);
}
@Override
public void setTitle(CharSequence title) {
wrappedActivity.setTitle(title);
}
@Override
public void setTitle(int titleId) {
wrappedActivity.setTitle(titleId);
}
@Override
public void setTitleColor(int textColor) {
wrappedActivity.setTitleColor(textColor);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
wrappedActivity.setTaskDescription(taskDescription);
}
@Nullable
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return wrappedActivity.onCreateView(name, context, attrs);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
return wrappedActivity.onCreateView(parent, name, context, attrs);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
wrappedActivity.dump(prefix, fd, writer, args);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public boolean isImmersive() {
return wrappedActivity.isImmersive();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean requestVisibleBehind(boolean visible) {
return wrappedActivity.requestVisibleBehind(visible);
}
@SuppressLint("MissingSuperCall")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onVisibleBehindCanceled() {
wrappedActivity.onVisibleBehindCanceled();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onEnterAnimationComplete() {
wrappedActivity.onEnterAnimationComplete();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void setImmersive(boolean i) {
wrappedActivity.setImmersive(i);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Nullable
@Override
public ActionMode startActionMode(ActionMode.Callback callback) {
return wrappedActivity.startActionMode(callback);
}
@TargetApi(Build.VERSION_CODES.M)
@Nullable
@Override
public ActionMode startActionMode(ActionMode.Callback callback, int type) {
return wrappedActivity.startActionMode(callback, type);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Nullable
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
return wrappedActivity.onWindowStartingActionMode(callback);
}
@TargetApi(Build.VERSION_CODES.M)
@Nullable
@Override
public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
return wrappedActivity.onWindowStartingActionMode(callback, type);
}
@SuppressLint("MissingSuperCall")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onActionModeStarted(ActionMode mode) {
wrappedActivity.onActionModeStarted(mode);
}
@SuppressLint("MissingSuperCall")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onActionModeFinished(ActionMode mode) {
wrappedActivity.onActionModeFinished(mode);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean shouldUpRecreateTask(Intent targetIntent) {
return wrappedActivity.shouldUpRecreateTask(targetIntent);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean navigateUpTo(Intent upIntent) {
return wrappedActivity.navigateUpTo(upIntent);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean navigateUpToFromChild(Activity child, Intent upIntent) {
return wrappedActivity.navigateUpToFromChild(child, upIntent);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Nullable
@Override
public Intent getParentActivityIntent() {
return wrappedActivity.getParentActivityIntent();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void setEnterSharedElementCallback(SharedElementCallback callback) {
wrappedActivity.setEnterSharedElementCallback(callback);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void setExitSharedElementCallback(SharedElementCallback callback) {
wrappedActivity.setExitSharedElementCallback(callback);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void postponeEnterTransition() {
wrappedActivity.postponeEnterTransition();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void startPostponedEnterTransition() {
wrappedActivity.startPostponedEnterTransition();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void startLockTask() {
wrappedActivity.startLockTask();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void stopLockTask() {
wrappedActivity.stopLockTask();
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void showLockTaskEscapeMessage() {
wrappedActivity.showLockTaskEscapeMessage();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void applyOverrideConfiguration(Configuration overrideConfiguration) {
wrappedActivity.applyOverrideConfiguration(overrideConfiguration);
}
@Override
public Resources getResources() {
return wrappedActivity.getResources();
}
@Override
public void setTheme(int resId) {
wrappedActivity.setTheme(resId);
}
@Override
public Resources.Theme getTheme() {
return wrappedActivity.getTheme();
}
@Override
public AssetManager getAssets() {
return wrappedActivity.getAssets();
}
@Override
public PackageManager getPackageManager() {
return wrappedActivity.getPackageManager();
}
@Override
public ContentResolver getContentResolver() {
return wrappedActivity.getContentResolver();
}
@Override
public Looper getMainLooper() {
return wrappedActivity.getMainLooper();
}
@Override
public String getPackageName() {
return wrappedActivity.getPackageName();
}
@Override
public ApplicationInfo getApplicationInfo() {
return wrappedActivity.getApplicationInfo();
}
@Override
public String getPackageResourcePath() {
return wrappedActivity.getPackageResourcePath();
}
@Override
public String getPackageCodePath() {
return wrappedActivity.getPackageCodePath();
}
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return wrappedActivity.getSharedPreferences(name, mode);
}
@Override
public FileInputStream openFileInput(String name) throws FileNotFoundException {
return wrappedActivity.openFileInput(name);
}
@Override
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException {
return wrappedActivity.openFileOutput(name, mode);
}
@Override
public boolean deleteFile(String name) {
return wrappedActivity.deleteFile(name);
}
@Override
public File getFileStreamPath(String name) {
return wrappedActivity.getFileStreamPath(name);
}
@Override
public String[] fileList() {
return wrappedActivity.fileList();
}
@Override
public File getFilesDir() {
return wrappedActivity.getFilesDir();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public File getNoBackupFilesDir() {
return wrappedActivity.getNoBackupFilesDir();
}
@Override
public File getExternalFilesDir(String type) {
return wrappedActivity.getExternalFilesDir(type);
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public File[] getExternalFilesDirs(String type) {
return wrappedActivity.getExternalFilesDirs(type);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public File getObbDir() {
return wrappedActivity.getObbDir();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public File[] getObbDirs() {
return wrappedActivity.getObbDirs();
}
@Override
public File getCacheDir() {
return wrappedActivity.getCacheDir();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public File getCodeCacheDir() {
return wrappedActivity.getCodeCacheDir();
}
@Override
public File getExternalCacheDir() {
return wrappedActivity.getExternalCacheDir();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public File[] getExternalCacheDirs() {
return wrappedActivity.getExternalCacheDirs();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public File[] getExternalMediaDirs() {
return wrappedActivity.getExternalMediaDirs();
}
@Override
public File getDir(String name, int mode) {
return wrappedActivity.getDir(name, mode);
}
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
return wrappedActivity.openOrCreateDatabase(name, mode, factory);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
return wrappedActivity.openOrCreateDatabase(name, mode, factory, errorHandler);
}
@Override
public boolean deleteDatabase(String name) {
return wrappedActivity.deleteDatabase(name);
}
@Override
public File getDatabasePath(String name) {
return wrappedActivity.getDatabasePath(name);
}
@Override
public String[] databaseList() {
return wrappedActivity.databaseList();
}
@Override
public Drawable getWallpaper() {
return wrappedActivity.getWallpaper();
}
@Override
public Drawable peekWallpaper() {
return wrappedActivity.peekWallpaper();
}
@Override
public int getWallpaperDesiredMinimumWidth() {
return wrappedActivity.getWallpaperDesiredMinimumWidth();
}
@Override
public int getWallpaperDesiredMinimumHeight() {
return wrappedActivity.getWallpaperDesiredMinimumHeight();
}
@Override
public void setWallpaper(Bitmap bitmap) throws IOException {
wrappedActivity.setWallpaper(bitmap);
}
@Override
public void setWallpaper(InputStream data) throws IOException {
wrappedActivity.setWallpaper(data);
}
@Override
public void clearWallpaper() throws IOException {
wrappedActivity.clearWallpaper();
}
@Override
public void sendBroadcast(Intent intent) {
wrappedActivity.sendBroadcast(intent);
}
@Override
public void sendBroadcast(Intent intent, String receiverPermission) {
wrappedActivity.sendBroadcast(intent, receiverPermission);
}
@Override
public void sendOrderedBroadcast(Intent intent, String receiverPermission) {
wrappedActivity.sendOrderedBroadcast(intent, receiverPermission);
}
@Override
public void sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
wrappedActivity.sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void sendBroadcastAsUser(Intent intent, UserHandle user) {
wrappedActivity.sendBroadcastAsUser(intent, user);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission) {
wrappedActivity.sendBroadcastAsUser(intent, user, receiverPermission);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
wrappedActivity.sendOrderedBroadcastAsUser(intent, user, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
@Override
public void sendStickyBroadcast(Intent intent) {
wrappedActivity.sendStickyBroadcast(intent);
}
@Override
public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
wrappedActivity.sendStickyOrderedBroadcast(intent, resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
@Override
public void removeStickyBroadcast(Intent intent) {
wrappedActivity.removeStickyBroadcast(intent);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
wrappedActivity.sendStickyBroadcastAsUser(intent, user);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
wrappedActivity.sendStickyOrderedBroadcastAsUser(intent, user, resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) {
wrappedActivity.removeStickyBroadcastAsUser(intent, user);
}
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
return wrappedActivity.registerReceiver(receiver, filter);
}
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) {
return wrappedActivity.registerReceiver(receiver, filter, broadcastPermission, scheduler);
}
@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
wrappedActivity.unregisterReceiver(receiver);
}
@Override
public ComponentName startService(Intent service) {
return wrappedActivity.startService(service);
}
@Override
public boolean stopService(Intent name) {
return wrappedActivity.stopService(name);
}
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
return wrappedActivity.bindService(service, conn, flags);
}
@Override
public void unbindService(ServiceConnection conn) {
wrappedActivity.unbindService(conn);
}
@Override
public boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments) {
return wrappedActivity.startInstrumentation(className, profileFile, arguments);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public String getSystemServiceName(Class<?> serviceClass) {
return wrappedActivity.getSystemServiceName(serviceClass);
}
@Override
public int checkPermission(String permission, int pid, int uid) {
return wrappedActivity.checkPermission(permission, pid, uid);
}
@Override
public int checkCallingPermission(String permission) {
return wrappedActivity.checkCallingPermission(permission);
}
@Override
public int checkCallingOrSelfPermission(String permission) {
return wrappedActivity.checkCallingOrSelfPermission(permission);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public int checkSelfPermission(String permission) {
return wrappedActivity.checkSelfPermission(permission);
}
@Override
public void enforcePermission(String permission, int pid, int uid, String message) {
wrappedActivity.enforcePermission(permission, pid, uid, message);
}
@Override
public void enforceCallingPermission(String permission, String message) {
wrappedActivity.enforceCallingPermission(permission, message);
}
@Override
public void enforceCallingOrSelfPermission(String permission, String message) {
wrappedActivity.enforceCallingOrSelfPermission(permission, message);
}
@Override
public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
wrappedActivity.grantUriPermission(toPackage, uri, modeFlags);
}
@Override
public void revokeUriPermission(Uri uri, int modeFlags) {
wrappedActivity.revokeUriPermission(uri, modeFlags);
}
@Override
public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
return wrappedActivity.checkUriPermission(uri, pid, uid, modeFlags);
}
@Override
public int checkCallingUriPermission(Uri uri, int modeFlags) {
return wrappedActivity.checkCallingUriPermission(uri, modeFlags);
}
@Override
public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
return wrappedActivity.checkCallingOrSelfUriPermission(uri, modeFlags);
}
@Override
public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags) {
return wrappedActivity.checkUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags);
}
@Override
public void enforceUriPermission(Uri uri, int pid, int uid, int modeFlags, String message) {
wrappedActivity.enforceUriPermission(uri, pid, uid, modeFlags, message);
}
@Override
public void enforceCallingUriPermission(Uri uri, int modeFlags, String message) {
wrappedActivity.enforceCallingUriPermission(uri, modeFlags, message);
}
@Override
public void enforceCallingOrSelfUriPermission(Uri uri, int modeFlags, String message) {
wrappedActivity.enforceCallingOrSelfUriPermission(uri, modeFlags, message);
}
@Override
public void enforceUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message) {
wrappedActivity.enforceUriPermission(uri, readPermission, writePermission, pid, uid, modeFlags, message);
}
@Override
public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException {
return wrappedActivity.createPackageContext(packageName, flags);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public Context createConfigurationContext(Configuration overrideConfiguration) {
return wrappedActivity.createConfigurationContext(overrideConfiguration);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public Context createDisplayContext(Display display) {
return wrappedActivity.createDisplayContext(display);
}
@Override
public boolean isRestricted() {
return wrappedActivity.isRestricted();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void registerComponentCallbacks(ComponentCallbacks callback) {
wrappedActivity.registerComponentCallbacks(callback);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void unregisterComponentCallbacks(ComponentCallbacks callback) {
wrappedActivity.unregisterComponentCallbacks(callback);
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
return wrappedActivity.equals(o);
}
@Override
public int hashCode() {
return wrappedActivity.hashCode();
}
@Override
public String toString() {
return wrappedActivity.toString();
}
}
| mit |