repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
lantunes/fixd | src/main/java/org/bigtesting/fixd/interpolation/RequestBodyValueProvider.java | // Path: src/main/java/org/bigtesting/fixd/request/HttpRequest.java
// public interface HttpRequest {
//
// String getPath();
//
// String getUndecodedPath();
//
// Set<String> getRequestParameterNames();
//
// String getRequestParameter(String name);
//
// String getPathParameter(String name);
//
// List<String> getHeaderNames();
//
// String getHeaderValue(String name);
//
// String getBody();
//
// InputStream getBodyAsStream() throws IOException;
//
// <T> T getBody(Class<T> type);
//
// long getContentLength();
//
// String getContentType();
//
// String getMethod();
//
// long getTime();
//
// String getQuery();
//
// int getMajor();
//
// int getMinor();
//
// String getTarget();
//
// /**
// * @return a session, if it exists, or null if it does not
// */
// Session getSession();
//
// Route getRoute();
// }
//
// Path: src/main/java/org/bigtesting/fixd/util/RequestUtils.java
// public class RequestUtils {
//
// public static byte[] readBody(InputStream in) {
//
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try {
//
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = in.read(buffer)) != -1) {
// out.write(buffer, 0, len);
// }
//
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// } finally {
// if (in != null) try {in.close();} catch (IOException e2) {}
// }
//
// return out.toByteArray();
// }
//
// public static String getUndecodedPath(Request request) {
//
// String path = request.getTarget();
// int queryIndex = path.indexOf('?');
// if (queryIndex != -1) {
// path = path.substring(0, queryIndex);
// }
// return path;
// }
// }
| import java.io.IOException;
import org.bigtesting.fixd.request.HttpRequest;
import org.bigtesting.fixd.util.RequestUtils; | /*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.interpolation;
/**
*
* @author Luis Antunes
*/
class RequestBodyValueProvider implements RequestValueProvider<String> {
public String getValue(HttpRequest request) {
try { | // Path: src/main/java/org/bigtesting/fixd/request/HttpRequest.java
// public interface HttpRequest {
//
// String getPath();
//
// String getUndecodedPath();
//
// Set<String> getRequestParameterNames();
//
// String getRequestParameter(String name);
//
// String getPathParameter(String name);
//
// List<String> getHeaderNames();
//
// String getHeaderValue(String name);
//
// String getBody();
//
// InputStream getBodyAsStream() throws IOException;
//
// <T> T getBody(Class<T> type);
//
// long getContentLength();
//
// String getContentType();
//
// String getMethod();
//
// long getTime();
//
// String getQuery();
//
// int getMajor();
//
// int getMinor();
//
// String getTarget();
//
// /**
// * @return a session, if it exists, or null if it does not
// */
// Session getSession();
//
// Route getRoute();
// }
//
// Path: src/main/java/org/bigtesting/fixd/util/RequestUtils.java
// public class RequestUtils {
//
// public static byte[] readBody(InputStream in) {
//
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try {
//
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = in.read(buffer)) != -1) {
// out.write(buffer, 0, len);
// }
//
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// } finally {
// if (in != null) try {in.close();} catch (IOException e2) {}
// }
//
// return out.toByteArray();
// }
//
// public static String getUndecodedPath(Request request) {
//
// String path = request.getTarget();
// int queryIndex = path.indexOf('?');
// if (queryIndex != -1) {
// path = path.substring(0, queryIndex);
// }
// return path;
// }
// }
// Path: src/main/java/org/bigtesting/fixd/interpolation/RequestBodyValueProvider.java
import java.io.IOException;
import org.bigtesting.fixd.request.HttpRequest;
import org.bigtesting.fixd.util.RequestUtils;
/*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.interpolation;
/**
*
* @author Luis Antunes
*/
class RequestBodyValueProvider implements RequestValueProvider<String> {
public String getValue(HttpRequest request) {
try { | return new String(RequestUtils.readBody(request.getBodyAsStream())); |
lantunes/fixd | src/main/java/org/bigtesting/fixd/core/async/Broadcast.java | // Path: src/main/java/org/bigtesting/fixd/capture/impl/SimpleCapturedRequest.java
// public class SimpleCapturedRequest implements CapturedRequest {
//
// private final Request request;
//
// private boolean broadcast = false;
//
// public SimpleCapturedRequest(Request request) {
// this.request = request;
// }
//
// public String getPath() {
//
// return request.getPath().getPath();
// }
//
// public String getRequestLine() {
//
// return headerLines()[0];
// }
//
// public String getMethod() {
//
// return request.getMethod();
// }
//
// public List<String> getHeaders() {
//
// List<String> headers = new ArrayList<String>();
// String[] lines = headerLines();
// for (int i = 1; i < lines.length; i++) {
// headers.add(lines[i]);
// }
//
// return headers;
// }
//
// public byte[] getBody() {
//
// try {
// return RequestUtils.readBody(request.getInputStream());
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// }
// }
//
// public String getBody(String encoding) {
//
// try {
//
// return new String(getBody(), encoding);
//
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("error getting encoded body", e);
// }
// }
//
// private String[] headerLines() {
//
// String header = request.getHeader().toString();
// return header.split("\\r?\\n");
// }
//
// public void setBroadcast(boolean broadcast) {
//
// this.broadcast = broadcast;
// }
//
// public boolean isBroadcast() {
//
// return broadcast;
// }
// }
//
// Path: src/main/java/org/bigtesting/fixd/core/Upon.java
// public class Upon {
//
// private final Method method;
// private final String resource;
// private final String contentType;
// private final RequestHandlerImpl handler;
//
// public Upon(Method method, String resource, RequestHandlerImpl handler) {
// this(method, resource, null, handler);
// }
//
// public Upon(Method method, String resource, String contentType,
// RequestHandlerImpl handler) {
//
// this.method = method;
// this.resource = resource;
// this.contentType = contentType;
// this.handler = handler;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public String getResource() {
// return resource;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public RequestHandlerImpl getHandler() {
// return handler;
// }
// }
| import org.bigtesting.fixd.capture.impl.SimpleCapturedRequest;
import org.bigtesting.fixd.core.Upon;
import org.bigtesting.routd.Route;
import org.simpleframework.http.Request; | /*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.core.async;
/**
*
* @author Luis Antunes
*/
public class Broadcast {
private final Request request;
private final Route route; | // Path: src/main/java/org/bigtesting/fixd/capture/impl/SimpleCapturedRequest.java
// public class SimpleCapturedRequest implements CapturedRequest {
//
// private final Request request;
//
// private boolean broadcast = false;
//
// public SimpleCapturedRequest(Request request) {
// this.request = request;
// }
//
// public String getPath() {
//
// return request.getPath().getPath();
// }
//
// public String getRequestLine() {
//
// return headerLines()[0];
// }
//
// public String getMethod() {
//
// return request.getMethod();
// }
//
// public List<String> getHeaders() {
//
// List<String> headers = new ArrayList<String>();
// String[] lines = headerLines();
// for (int i = 1; i < lines.length; i++) {
// headers.add(lines[i]);
// }
//
// return headers;
// }
//
// public byte[] getBody() {
//
// try {
// return RequestUtils.readBody(request.getInputStream());
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// }
// }
//
// public String getBody(String encoding) {
//
// try {
//
// return new String(getBody(), encoding);
//
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("error getting encoded body", e);
// }
// }
//
// private String[] headerLines() {
//
// String header = request.getHeader().toString();
// return header.split("\\r?\\n");
// }
//
// public void setBroadcast(boolean broadcast) {
//
// this.broadcast = broadcast;
// }
//
// public boolean isBroadcast() {
//
// return broadcast;
// }
// }
//
// Path: src/main/java/org/bigtesting/fixd/core/Upon.java
// public class Upon {
//
// private final Method method;
// private final String resource;
// private final String contentType;
// private final RequestHandlerImpl handler;
//
// public Upon(Method method, String resource, RequestHandlerImpl handler) {
// this(method, resource, null, handler);
// }
//
// public Upon(Method method, String resource, String contentType,
// RequestHandlerImpl handler) {
//
// this.method = method;
// this.resource = resource;
// this.contentType = contentType;
// this.handler = handler;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public String getResource() {
// return resource;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public RequestHandlerImpl getHandler() {
// return handler;
// }
// }
// Path: src/main/java/org/bigtesting/fixd/core/async/Broadcast.java
import org.bigtesting.fixd.capture.impl.SimpleCapturedRequest;
import org.bigtesting.fixd.core.Upon;
import org.bigtesting.routd.Route;
import org.simpleframework.http.Request;
/*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.core.async;
/**
*
* @author Luis Antunes
*/
public class Broadcast {
private final Request request;
private final Route route; | private final Upon upon; |
lantunes/fixd | src/main/java/org/bigtesting/fixd/core/async/Broadcast.java | // Path: src/main/java/org/bigtesting/fixd/capture/impl/SimpleCapturedRequest.java
// public class SimpleCapturedRequest implements CapturedRequest {
//
// private final Request request;
//
// private boolean broadcast = false;
//
// public SimpleCapturedRequest(Request request) {
// this.request = request;
// }
//
// public String getPath() {
//
// return request.getPath().getPath();
// }
//
// public String getRequestLine() {
//
// return headerLines()[0];
// }
//
// public String getMethod() {
//
// return request.getMethod();
// }
//
// public List<String> getHeaders() {
//
// List<String> headers = new ArrayList<String>();
// String[] lines = headerLines();
// for (int i = 1; i < lines.length; i++) {
// headers.add(lines[i]);
// }
//
// return headers;
// }
//
// public byte[] getBody() {
//
// try {
// return RequestUtils.readBody(request.getInputStream());
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// }
// }
//
// public String getBody(String encoding) {
//
// try {
//
// return new String(getBody(), encoding);
//
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("error getting encoded body", e);
// }
// }
//
// private String[] headerLines() {
//
// String header = request.getHeader().toString();
// return header.split("\\r?\\n");
// }
//
// public void setBroadcast(boolean broadcast) {
//
// this.broadcast = broadcast;
// }
//
// public boolean isBroadcast() {
//
// return broadcast;
// }
// }
//
// Path: src/main/java/org/bigtesting/fixd/core/Upon.java
// public class Upon {
//
// private final Method method;
// private final String resource;
// private final String contentType;
// private final RequestHandlerImpl handler;
//
// public Upon(Method method, String resource, RequestHandlerImpl handler) {
// this(method, resource, null, handler);
// }
//
// public Upon(Method method, String resource, String contentType,
// RequestHandlerImpl handler) {
//
// this.method = method;
// this.resource = resource;
// this.contentType = contentType;
// this.handler = handler;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public String getResource() {
// return resource;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public RequestHandlerImpl getHandler() {
// return handler;
// }
// }
| import org.bigtesting.fixd.capture.impl.SimpleCapturedRequest;
import org.bigtesting.fixd.core.Upon;
import org.bigtesting.routd.Route;
import org.simpleframework.http.Request; | /*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.core.async;
/**
*
* @author Luis Antunes
*/
public class Broadcast {
private final Request request;
private final Route route;
private final Upon upon; | // Path: src/main/java/org/bigtesting/fixd/capture/impl/SimpleCapturedRequest.java
// public class SimpleCapturedRequest implements CapturedRequest {
//
// private final Request request;
//
// private boolean broadcast = false;
//
// public SimpleCapturedRequest(Request request) {
// this.request = request;
// }
//
// public String getPath() {
//
// return request.getPath().getPath();
// }
//
// public String getRequestLine() {
//
// return headerLines()[0];
// }
//
// public String getMethod() {
//
// return request.getMethod();
// }
//
// public List<String> getHeaders() {
//
// List<String> headers = new ArrayList<String>();
// String[] lines = headerLines();
// for (int i = 1; i < lines.length; i++) {
// headers.add(lines[i]);
// }
//
// return headers;
// }
//
// public byte[] getBody() {
//
// try {
// return RequestUtils.readBody(request.getInputStream());
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// }
// }
//
// public String getBody(String encoding) {
//
// try {
//
// return new String(getBody(), encoding);
//
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("error getting encoded body", e);
// }
// }
//
// private String[] headerLines() {
//
// String header = request.getHeader().toString();
// return header.split("\\r?\\n");
// }
//
// public void setBroadcast(boolean broadcast) {
//
// this.broadcast = broadcast;
// }
//
// public boolean isBroadcast() {
//
// return broadcast;
// }
// }
//
// Path: src/main/java/org/bigtesting/fixd/core/Upon.java
// public class Upon {
//
// private final Method method;
// private final String resource;
// private final String contentType;
// private final RequestHandlerImpl handler;
//
// public Upon(Method method, String resource, RequestHandlerImpl handler) {
// this(method, resource, null, handler);
// }
//
// public Upon(Method method, String resource, String contentType,
// RequestHandlerImpl handler) {
//
// this.method = method;
// this.resource = resource;
// this.contentType = contentType;
// this.handler = handler;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public String getResource() {
// return resource;
// }
//
// public String getContentType() {
// return contentType;
// }
//
// public RequestHandlerImpl getHandler() {
// return handler;
// }
// }
// Path: src/main/java/org/bigtesting/fixd/core/async/Broadcast.java
import org.bigtesting.fixd.capture.impl.SimpleCapturedRequest;
import org.bigtesting.fixd.core.Upon;
import org.bigtesting.routd.Route;
import org.simpleframework.http.Request;
/*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.core.async;
/**
*
* @author Luis Antunes
*/
public class Broadcast {
private final Request request;
private final Route route;
private final Upon upon; | private final SimpleCapturedRequest captured; |
lantunes/fixd | src/main/java/org/bigtesting/fixd/capture/impl/SimpleCapturedRequest.java | // Path: src/main/java/org/bigtesting/fixd/capture/CapturedRequest.java
// public interface CapturedRequest {
//
// String getPath();
//
// String getRequestLine();
//
// String getMethod();
//
// List<String> getHeaders();
//
// byte[] getBody();
//
// String getBody(String encoding);
//
// /**
// * Returns true if this request was broadcast to any subscribers.
// */
// boolean isBroadcast();
// }
//
// Path: src/main/java/org/bigtesting/fixd/util/RequestUtils.java
// public class RequestUtils {
//
// public static byte[] readBody(InputStream in) {
//
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try {
//
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = in.read(buffer)) != -1) {
// out.write(buffer, 0, len);
// }
//
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// } finally {
// if (in != null) try {in.close();} catch (IOException e2) {}
// }
//
// return out.toByteArray();
// }
//
// public static String getUndecodedPath(Request request) {
//
// String path = request.getTarget();
// int queryIndex = path.indexOf('?');
// if (queryIndex != -1) {
// path = path.substring(0, queryIndex);
// }
// return path;
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.bigtesting.fixd.capture.CapturedRequest;
import org.bigtesting.fixd.util.RequestUtils;
import org.simpleframework.http.Request; | /*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.capture.impl;
/**
*
* @author Luis Antunes
*/
public class SimpleCapturedRequest implements CapturedRequest {
private final Request request;
private boolean broadcast = false;
public SimpleCapturedRequest(Request request) {
this.request = request;
}
public String getPath() {
return request.getPath().getPath();
}
public String getRequestLine() {
return headerLines()[0];
}
public String getMethod() {
return request.getMethod();
}
public List<String> getHeaders() {
List<String> headers = new ArrayList<String>();
String[] lines = headerLines();
for (int i = 1; i < lines.length; i++) {
headers.add(lines[i]);
}
return headers;
}
public byte[] getBody() {
try { | // Path: src/main/java/org/bigtesting/fixd/capture/CapturedRequest.java
// public interface CapturedRequest {
//
// String getPath();
//
// String getRequestLine();
//
// String getMethod();
//
// List<String> getHeaders();
//
// byte[] getBody();
//
// String getBody(String encoding);
//
// /**
// * Returns true if this request was broadcast to any subscribers.
// */
// boolean isBroadcast();
// }
//
// Path: src/main/java/org/bigtesting/fixd/util/RequestUtils.java
// public class RequestUtils {
//
// public static byte[] readBody(InputStream in) {
//
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try {
//
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = in.read(buffer)) != -1) {
// out.write(buffer, 0, len);
// }
//
// } catch (IOException e) {
// throw new RuntimeException("error getting body", e);
// } finally {
// if (in != null) try {in.close();} catch (IOException e2) {}
// }
//
// return out.toByteArray();
// }
//
// public static String getUndecodedPath(Request request) {
//
// String path = request.getTarget();
// int queryIndex = path.indexOf('?');
// if (queryIndex != -1) {
// path = path.substring(0, queryIndex);
// }
// return path;
// }
// }
// Path: src/main/java/org/bigtesting/fixd/capture/impl/SimpleCapturedRequest.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.bigtesting.fixd.capture.CapturedRequest;
import org.bigtesting.fixd.util.RequestUtils;
import org.simpleframework.http.Request;
/*
* Copyright (C) 2015 BigTesting.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 org.bigtesting.fixd.capture.impl;
/**
*
* @author Luis Antunes
*/
public class SimpleCapturedRequest implements CapturedRequest {
private final Request request;
private boolean broadcast = false;
public SimpleCapturedRequest(Request request) {
this.request = request;
}
public String getPath() {
return request.getPath().getPath();
}
public String getRequestLine() {
return headerLines()[0];
}
public String getMethod() {
return request.getMethod();
}
public List<String> getHeaders() {
List<String> headers = new ArrayList<String>();
String[] lines = headerLines();
for (int i = 1; i < lines.length; i++) {
headers.add(lines[i]);
}
return headers;
}
public byte[] getBody() {
try { | return RequestUtils.readBody(request.getInputStream()); |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/events/TelegramUpdateEvent.java | // Path: src/com/cadiducho/minegram/api/Update.java
// @ToString
// @Getter @Setter
// public class Update {
//
// /**
// * The update‘s unique identifier.
// * Update identifiers start from a certain positive number and increase sequentially.
// * This ID becomes especially handy if you’re using Webhooks,
// * since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
// */
// private Integer update_id;
//
// /**
// * Optional. New incoming message of any kind — text, photo, sticker, etc.
// */
// private Message message;
//
// /**
// * Optional. New version of a message that is known to the bot and was edited
// */
// private Message edited_message;
//
// /**
// * Optional. New incoming channel post of any kind — text, photo, sticker, etc.
// */
// private Message channel_post;
//
// /**
// * Optional. New version of a channel post that is known to the bot and was edited
// */
// private Message edited_channel_post;
// /**
// * Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
// */
// private InlineQuery inline_query;
//
// /**
// * Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
// */
// private ChosenInlineResult chosen_inline_result;
//
// /**
// * Optional. New incoming callback query
// */
// private CallbackQuery callback_query;
//
// /**
// * Optional. New incoming shipping query. Only for invoices with flexible price
// */
// private ShippingQuery shipping_query;
//
// /**
// * Optional. New incoming pre-checkout query. Contains full information about checkout
// */
// private PreCheckoutQuery pre_checkout_query;
//
// }
| import com.cadiducho.minegram.api.Update;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.events;
@Getter @Setter
public class TelegramUpdateEvent extends Event { | // Path: src/com/cadiducho/minegram/api/Update.java
// @ToString
// @Getter @Setter
// public class Update {
//
// /**
// * The update‘s unique identifier.
// * Update identifiers start from a certain positive number and increase sequentially.
// * This ID becomes especially handy if you’re using Webhooks,
// * since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
// */
// private Integer update_id;
//
// /**
// * Optional. New incoming message of any kind — text, photo, sticker, etc.
// */
// private Message message;
//
// /**
// * Optional. New version of a message that is known to the bot and was edited
// */
// private Message edited_message;
//
// /**
// * Optional. New incoming channel post of any kind — text, photo, sticker, etc.
// */
// private Message channel_post;
//
// /**
// * Optional. New version of a channel post that is known to the bot and was edited
// */
// private Message edited_channel_post;
// /**
// * Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
// */
// private InlineQuery inline_query;
//
// /**
// * Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
// */
// private ChosenInlineResult chosen_inline_result;
//
// /**
// * Optional. New incoming callback query
// */
// private CallbackQuery callback_query;
//
// /**
// * Optional. New incoming shipping query. Only for invoices with flexible price
// */
// private ShippingQuery shipping_query;
//
// /**
// * Optional. New incoming pre-checkout query. Contains full information about checkout
// */
// private PreCheckoutQuery pre_checkout_query;
//
// }
// Path: src/com/cadiducho/minegram/api/events/TelegramUpdateEvent.java
import com.cadiducho.minegram.api.Update;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.events;
@Getter @Setter
public class TelegramUpdateEvent extends Event { | private Update update; |
Cadiducho/Minegram | src/com/cadiducho/minegram/BotAPI.java | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
| import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin; |
/**
* Use this method to send answers to callback queries sent from inline keyboards.
* The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
*
* @param callback_query_id Unique identifier for the query to be answered
* @param text Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters
* @param show_alert If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.
* @param url URL that will be opened by the user's client.
If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.
Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter.
* @param cache_time The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean answerCallbackQuery(String callback_query_id, String text, Boolean show_alert, String url, Integer cache_time) throws TelegramException;
/**
* Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited {@link Message} is returned, otherwise True is returned.
* @param chat_id Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param message_id Required if inline_message_id is not specified. Unique identifier of the sent message
* @param inline_message_id Required if chat_id and message_id are not specified. Identifier of the inline message
* @param text New text of the message
* @param parse_mode Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
* @param disable_web_page_preview Disables link previews for links in this message
* @param reply_markup A JSON-serialized object for an inline keyboard.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/ | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
// Path: src/com/cadiducho/minegram/BotAPI.java
import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin;
/**
* Use this method to send answers to callback queries sent from inline keyboards.
* The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
*
* @param callback_query_id Unique identifier for the query to be answered
* @param text Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters
* @param show_alert If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false.
* @param url URL that will be opened by the user's client.
If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.
Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter.
* @param cache_time The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean answerCallbackQuery(String callback_query_id, String text, Boolean show_alert, String url, Integer cache_time) throws TelegramException;
/**
* Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited {@link Message} is returned, otherwise True is returned.
* @param chat_id Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param message_id Required if inline_message_id is not specified. Unique identifier of the sent message
* @param inline_message_id Required if chat_id and message_id are not specified. Identifier of the inline message
* @param text New text of the message
* @param parse_mode Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message.
* @param disable_web_page_preview Disables link previews for links in this message
* @param reply_markup A JSON-serialized object for an inline keyboard.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/ | public Boolean editMessageText(Object chat_id, Integer message_id, String inline_message_id, String text, String parse_mode, Boolean disable_web_page_preview, InlineKeyboardMarkup reply_markup) throws TelegramException; |
Cadiducho/Minegram | src/com/cadiducho/minegram/BotAPI.java | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
| import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin; | * @param url HTTPS url to send updates to. Use an empty string to remove webhook integration
* @param certificate Optional. Upload your public key certificate so that the root certificate in use can be checked.
* See our <a href="https://core.telegram.org/bots/self-signed">self-signed guide</a> for details.
* @param max_connections Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40.
* Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput.
* @param allowed_updates Optional. List the types of updates you want your bot to receive.
* For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types.
* See {@link Update} for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default).
* If not specified, the previous setting will be used.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean setWebhook(String url, java.io.File certificate, Integer max_connections, List<String> allowed_updates) throws TelegramException;
/**
* Use this method to remove webhook integration if you decide to switch back to {@link BotAPI#getUpdates}. Returns True on success. Requires no parameters.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean deleteWebhook() throws TelegramException;
/**
* Use this method to send answers to an inline query. On success, True is returned.
* No more than <b>50</b> results per query are allowed.
*
* @param inlineQueryId Unique identifier for the answered query
* @param results A JSON-serialized array of results for the inline query
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/ | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
// Path: src/com/cadiducho/minegram/BotAPI.java
import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin;
* @param url HTTPS url to send updates to. Use an empty string to remove webhook integration
* @param certificate Optional. Upload your public key certificate so that the root certificate in use can be checked.
* See our <a href="https://core.telegram.org/bots/self-signed">self-signed guide</a> for details.
* @param max_connections Optional. Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40.
* Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput.
* @param allowed_updates Optional. List the types of updates you want your bot to receive.
* For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types.
* See {@link Update} for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default).
* If not specified, the previous setting will be used.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean setWebhook(String url, java.io.File certificate, Integer max_connections, List<String> allowed_updates) throws TelegramException;
/**
* Use this method to remove webhook integration if you decide to switch back to {@link BotAPI#getUpdates}. Returns True on success. Requires no parameters.
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean deleteWebhook() throws TelegramException;
/**
* Use this method to send answers to an inline query. On success, True is returned.
* No more than <b>50</b> results per query are allowed.
*
* @param inlineQueryId Unique identifier for the answered query
* @param results A JSON-serialized array of results for the inline query
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/ | public Boolean answerInlineQuery(String inlineQueryId, List<InlineQueryResult> results) throws TelegramException; |
Cadiducho/Minegram | src/com/cadiducho/minegram/BotAPI.java | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
| import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin; | * @param cache_time The maximum amount of time in seconds that the result of the inline query may be cached on
* the server. Defaults to 300.
* @param is_personal Pass <i>True</i>, if results may be cached on the server side only for the user that sent
* the query. By default, results may be returned to any user who sends the same query
* @param next_offset Pass the offset that a client should send in the next query with the same text to receive
* more results. Pass an empty string if there are no more results or if you don‘t support
* pagination. Offset length can’t exceed 64 bytes.
* @param switch_pm_text If passed, clients will display a button with specified text that switches the user to a private chat
* with the bot and sends the bot a start message with the parameter switch_pm_parameter
* @param switch_pm_parameter
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean answerInlineQuery(String inlineQueryId, List<InlineQueryResult> results, Integer cache_time, Boolean is_personal, String next_offset,
String switch_pm_text, String switch_pm_parameter) throws TelegramException;
/**
* Use this method to send invoices. On success, the sent Message is returned.
* @param chat_id Unique identifier for the target private chat
* @param title Product name
* @param description Product description
* @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
* @param provider_token Payments provider token, obtained via Botfather
* @param start_parameter Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter
* @param currency Three-letter ISO 4217 currency code, see more on https://core.telegram.org/bots/payments#supported-currencies
* @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
* @return {@link Message}
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Message sendInvoice(Integer chat_id, String title, String description, String payload, String provider_token, String start_parameter, String currency, | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
// Path: src/com/cadiducho/minegram/BotAPI.java
import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin;
* @param cache_time The maximum amount of time in seconds that the result of the inline query may be cached on
* the server. Defaults to 300.
* @param is_personal Pass <i>True</i>, if results may be cached on the server side only for the user that sent
* the query. By default, results may be returned to any user who sends the same query
* @param next_offset Pass the offset that a client should send in the next query with the same text to receive
* more results. Pass an empty string if there are no more results or if you don‘t support
* pagination. Offset length can’t exceed 64 bytes.
* @param switch_pm_text If passed, clients will display a button with specified text that switches the user to a private chat
* with the bot and sends the bot a start message with the parameter switch_pm_parameter
* @param switch_pm_parameter
* @return On success, True is returned.
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Boolean answerInlineQuery(String inlineQueryId, List<InlineQueryResult> results, Integer cache_time, Boolean is_personal, String next_offset,
String switch_pm_text, String switch_pm_parameter) throws TelegramException;
/**
* Use this method to send invoices. On success, the sent Message is returned.
* @param chat_id Unique identifier for the target private chat
* @param title Product name
* @param description Product description
* @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
* @param provider_token Payments provider token, obtained via Botfather
* @param start_parameter Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter
* @param currency Three-letter ISO 4217 currency code, see more on https://core.telegram.org/bots/payments#supported-currencies
* @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.)
* @return {@link Message}
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Message sendInvoice(Integer chat_id, String title, String description, String payload, String provider_token, String start_parameter, String currency, | List<LabeledPrice> prices) throws TelegramException; |
Cadiducho/Minegram | src/com/cadiducho/minegram/BotAPI.java | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
| import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin; | * @param reply_markup A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
* @return {@link Message}
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Message sendInvoice(Integer chat_id, String title, String description, String payload, String provider_token, String start_parameter, String currency,
List<LabeledPrice> prices, String photo_url, Integer photo_size, Integer photo_width, Integer photo_height, Boolean need_name, Boolean need_phone_number,
Boolean need_email, Boolean need_shipping_address, Boolean is_flexible, Boolean disable_notification, Integer reply_to_message_id, InlineKeyboardMarkup reply_markup) throws TelegramException;
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot.
* Use this method to reply to shipping queries.
* On success, True is returned.
* @param shipping_query_id Unique identifier for the query to be answered
* @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
* @return True on success
* @throws TelegramException
*/
public Boolean answerShippingQuery(String shipping_query_id, Boolean ok) throws TelegramException;
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot.
* Use this method to reply to shipping queries.
* On success, True is returned.
* @param shipping_query_id Unique identifier for the query to be answered
* @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
* @param shipping_options Required if ok is True. A JSON-serialized array of available shipping options.
* @param error_message Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
* @return True on success
* @throws TelegramException
*/ | // Path: src/com/cadiducho/minegram/api/inline/InlineKeyboardMarkup.java
// @ToString
// @Getter @Setter
// public class InlineKeyboardMarkup {
//
// /**
// * Array of button rows, each represented by an Array of {@link InlineKeyboardButton} objects
// */
// private List<List<InlineKeyboardButton>> inline_keyboard;
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQueryResult.java
// @ToString
// @Getter @Setter
// public abstract class InlineQueryResult {
//
// /**
// * Type of the result
// */
// protected final String type;
//
// /**
// * Unique identifier for this result, 1-64 Bytes
// */
// protected String id;
//
// /**
// * Optional. Inline keyboard attached to the message
// */
// protected InlineKeyboardMarkup reply_markup;
//
// /**
// * Optional. Content of the message to be sent instead of the file
// */
// protected InputMessageContent input_message_content;
//
// public InlineQueryResult(String type) {
// this.type = type;
// this.id = UUID.randomUUID().toString().replace("-", "") + UUID.randomUUID().toString().replace("-", "");
// }
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/LabeledPrice.java
// @ToString
// @Getter @Setter
// public class LabeledPrice {
//
// /**
// * Portion label
// */
// private String label;
//
// /**
// * Price of the product in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingOption.java
// @ToString
// @Getter @Setter
// public class ShippingOption {
//
// /**
// * Shipping option identifier
// */
// private String id;
//
// /**
// * Option title
// */
// private String title;
//
// /**
// * List of price portions
// */
// private List<LabeledPrice> prices;
//
// }
// Path: src/com/cadiducho/minegram/BotAPI.java
import com.cadiducho.minegram.api.inline.InlineKeyboardMarkup;
import com.cadiducho.minegram.api.inline.InlineQueryResult;
import com.cadiducho.minegram.api.*;
import com.cadiducho.minegram.api.exception.*;
import com.cadiducho.minegram.api.payment.LabeledPrice;
import com.cadiducho.minegram.api.payment.ShippingOption;
import java.util.List;
import org.bukkit.plugin.Plugin;
* @param reply_markup A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button.
* @return {@link Message}
* @throws com.cadiducho.minegram.api.exception.TelegramException
*/
public Message sendInvoice(Integer chat_id, String title, String description, String payload, String provider_token, String start_parameter, String currency,
List<LabeledPrice> prices, String photo_url, Integer photo_size, Integer photo_width, Integer photo_height, Boolean need_name, Boolean need_phone_number,
Boolean need_email, Boolean need_shipping_address, Boolean is_flexible, Boolean disable_notification, Integer reply_to_message_id, InlineKeyboardMarkup reply_markup) throws TelegramException;
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot.
* Use this method to reply to shipping queries.
* On success, True is returned.
* @param shipping_query_id Unique identifier for the query to be answered
* @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
* @return True on success
* @throws TelegramException
*/
public Boolean answerShippingQuery(String shipping_query_id, Boolean ok) throws TelegramException;
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot.
* Use this method to reply to shipping queries.
* On success, True is returned.
* @param shipping_query_id Unique identifier for the query to be answered
* @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
* @param shipping_options Required if ok is True. A JSON-serialized array of available shipping options.
* @param error_message Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
* @return True on success
* @throws TelegramException
*/ | public Boolean answerShippingQuery(String shipping_query_id, Boolean ok, List<ShippingOption> shipping_options, String error_message) throws TelegramException; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/Update.java | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
| import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/ | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
// Path: src/com/cadiducho/minegram/api/Update.java
import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/ | private InlineQuery inline_query; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/Update.java | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
| import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/
private InlineQuery inline_query;
/**
* Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
*/ | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
// Path: src/com/cadiducho/minegram/api/Update.java
import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/
private InlineQuery inline_query;
/**
* Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
*/ | private ChosenInlineResult chosen_inline_result; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/Update.java | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
| import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/
private InlineQuery inline_query;
/**
* Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
*/
private ChosenInlineResult chosen_inline_result;
/**
* Optional. New incoming callback query
*/
private CallbackQuery callback_query;
/**
* Optional. New incoming shipping query. Only for invoices with flexible price
*/ | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
// Path: src/com/cadiducho/minegram/api/Update.java
import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/
private InlineQuery inline_query;
/**
* Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
*/
private ChosenInlineResult chosen_inline_result;
/**
* Optional. New incoming callback query
*/
private CallbackQuery callback_query;
/**
* Optional. New incoming shipping query. Only for invoices with flexible price
*/ | private ShippingQuery shipping_query; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/Update.java | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
| import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/
private InlineQuery inline_query;
/**
* Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
*/
private ChosenInlineResult chosen_inline_result;
/**
* Optional. New incoming callback query
*/
private CallbackQuery callback_query;
/**
* Optional. New incoming shipping query. Only for invoices with flexible price
*/
private ShippingQuery shipping_query;
/**
* Optional. New incoming pre-checkout query. Contains full information about checkout
*/ | // Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
// @ToString
// @Getter @Setter
// public class ChosenInlineResult {
//
// /**
// * The unique identifier for the result that was chosen.
// */
// private String result_id;
//
// /**
// * The user that chose the result.
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that require user location
// */
// private Location location;
//
// /**
// * Optional. Identifier of the sent inline message.
// * Available only if there is an inline keyboard attached to the message.
// * Will be also received in callback queries and can be used to edit the message.
// */
// private String inline_message_id;
//
// /**
// * The query that was used to obtain the result.
// */
// private String query;
//
// }
//
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
// @ToString
// @Getter @Setter
// public class InlineQuery {
//
// /**
// * Unique identifier for this query
// */
// private String id;
//
// /**
// * Sender
// */
// private User from;
//
// /**
// * Optional. Sender location, only for bots that request user location
// */
// private Location location;
//
// /**
// * Text of the query
// */
// private String query;
//
// /**
// * Offset of the results to be returned, can be controlled by the bot
// */
// private String offset;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
// @ToString
// @Getter @Setter
// public class PreCheckoutQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
// @ToString
// @Getter @Setter
// public class ShippingQuery {
//
// /**
// * Unique query identifier
// */
// private String id;
//
// /**
// * User who sent the query
// */
// private User from;
//
// /**
// * Bot specified invoice payload
// */
// private String invoice_payload;
//
// /**
// * User specified shipping address
// */
// private ShippingAddress shipping_address;
//
// }
// Path: src/com/cadiducho/minegram/api/Update.java
import com.cadiducho.minegram.api.inline.ChosenInlineResult;
import com.cadiducho.minegram.api.inline.InlineQuery;
import com.cadiducho.minegram.api.payment.PreCheckoutQuery;
import com.cadiducho.minegram.api.payment.ShippingQuery;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api;
/**
* This object represents an incoming update.
*/
@ToString
@Getter @Setter
public class Update {
/**
* The update‘s unique identifier.
* Update identifiers start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
*/
private Integer update_id;
/**
* Optional. New incoming message of any kind — text, photo, sticker, etc.
*/
private Message message;
/**
* Optional. New version of a message that is known to the bot and was edited
*/
private Message edited_message;
/**
* Optional. New incoming channel post of any kind — text, photo, sticker, etc.
*/
private Message channel_post;
/**
* Optional. New version of a channel post that is known to the bot and was edited
*/
private Message edited_channel_post;
/**
* Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
*/
private InlineQuery inline_query;
/**
* Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
*/
private ChosenInlineResult chosen_inline_result;
/**
* Optional. New incoming callback query
*/
private CallbackQuery callback_query;
/**
* Optional. New incoming shipping query. Only for invoices with flexible price
*/
private ShippingQuery shipping_query;
/**
* Optional. New incoming pre-checkout query. Contains full information about checkout
*/ | private PreCheckoutQuery pre_checkout_query; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/inline/InlineQuery.java | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
| import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.
*/
@ToString
@Getter @Setter
public class InlineQuery {
/**
* Unique identifier for this query
*/
private String id;
/**
* Sender
*/ | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.
*/
@ToString
@Getter @Setter
public class InlineQuery {
/**
* Unique identifier for this query
*/
private String id;
/**
* Sender
*/ | private User from; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/inline/InlineQuery.java | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
| import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.
*/
@ToString
@Getter @Setter
public class InlineQuery {
/**
* Unique identifier for this query
*/
private String id;
/**
* Sender
*/
private User from;
/**
* Optional. Sender location, only for bots that request user location
*/ | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
// Path: src/com/cadiducho/minegram/api/inline/InlineQuery.java
import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.
*/
@ToString
@Getter @Setter
public class InlineQuery {
/**
* Unique identifier for this query
*/
private String id;
/**
* Sender
*/
private User from;
/**
* Optional. Sender location, only for bots that request user location
*/ | private Location location; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/payment/ShippingQuery.java | // Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
| import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.payment;
/**
* This object contains information about an incoming shipping query.
*/
@ToString
@Getter @Setter
public class ShippingQuery {
/**
* Unique query identifier
*/
private String id;
/**
* User who sent the query
*/ | // Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
// Path: src/com/cadiducho/minegram/api/payment/ShippingQuery.java
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.payment;
/**
* This object contains information about an incoming shipping query.
*/
@ToString
@Getter @Setter
public class ShippingQuery {
/**
* Unique query identifier
*/
private String id;
/**
* User who sent the query
*/ | private User from; |
Cadiducho/Minegram | src/com/cadiducho/minegram/MinegramPlugin.java | // Path: src/com/cadiducho/minegram/api/exception/TelegramException.java
// public class TelegramException extends Exception {
//
// public TelegramException() {
// }
//
// public TelegramException(String message) {
// super(message);
// }
//
// public TelegramException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public TelegramException(Throwable cause) {
// super(cause);
// }
//
// public TelegramException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
| import com.cadiducho.minegram.api.exception.TelegramException;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram;
public class MinegramPlugin extends JavaPlugin {
public static HashMap<BotAPI, Plugin> bots = new HashMap<>();
public static MinegramPlugin instance;
@Override
public void onLoad() {
log("Minegram loaded. Waiting for bots.");
}
@Override
public void onEnable() {
instance = this;
log("Enabling Minegram " + getDescription().getVersion() + " by Cadiducho");
File config = new File(getDataFolder() + File.separator + "config.yml");
if (!config.exists()) {
getConfig().options().copyDefaults(true);
saveConfig();
}
new BukkitRunnable() {
@Override
public void run() {
if (!bots.isEmpty()) {
bots.forEach((bot, pluginLoader) -> {
try {
log("@" + bot.getMe().getUsername() + " loaded by " + pluginLoader.getName()); | // Path: src/com/cadiducho/minegram/api/exception/TelegramException.java
// public class TelegramException extends Exception {
//
// public TelegramException() {
// }
//
// public TelegramException(String message) {
// super(message);
// }
//
// public TelegramException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public TelegramException(Throwable cause) {
// super(cause);
// }
//
// public TelegramException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
// Path: src/com/cadiducho/minegram/MinegramPlugin.java
import com.cadiducho.minegram.api.exception.TelegramException;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram;
public class MinegramPlugin extends JavaPlugin {
public static HashMap<BotAPI, Plugin> bots = new HashMap<>();
public static MinegramPlugin instance;
@Override
public void onLoad() {
log("Minegram loaded. Waiting for bots.");
}
@Override
public void onEnable() {
instance = this;
log("Enabling Minegram " + getDescription().getVersion() + " by Cadiducho");
File config = new File(getDataFolder() + File.separator + "config.yml");
if (!config.exists()) {
getConfig().options().copyDefaults(true);
saveConfig();
}
new BukkitRunnable() {
@Override
public void run() {
if (!bots.isEmpty()) {
bots.forEach((bot, pluginLoader) -> {
try {
log("@" + bot.getMe().getUsername() + " loaded by " + pluginLoader.getName()); | } catch (TelegramException ex) { |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/Message.java | // Path: src/com/cadiducho/minegram/api/payment/Invoice.java
// @ToString
// @Getter @Setter
// public class Invoice {
//
// /**
// * Product name
// */
// private String title;
//
// /**
// * Product description
// */
// private String description;
//
// /**
// * Unique bot deep-linking parameter that can be used to generate this invoice
// */
// private String start_parameter;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/SuccessfulPayment.java
// @ToString
// @Getter @Setter
// public class SuccessfulPayment {
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// /**
// * Telegram payment identifier
// */
// private String telegram_payment_charge_id;
//
// /**
// * Provider payment identifier
// */
// private String provider_payment_charge_id;
//
// }
| import com.cadiducho.minegram.api.payment.Invoice;
import com.cadiducho.minegram.api.payment.SuccessfulPayment;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | private Boolean group_chat_created;
/**
* Optional. Informs that the supergroup has been created
*/
private Boolean supergroup_chat_created;
/**
* Optional. Informs that the channel has been created
*/
private Boolean channel_chat_created;
/**
* Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_to_chat_id;
/**
* Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_from_chat_id;
/**
* Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
*/
private Message pinned_message;
/**
* Optional. Message is an invoice for a payment, information about the invoice. More about payments »
*/ | // Path: src/com/cadiducho/minegram/api/payment/Invoice.java
// @ToString
// @Getter @Setter
// public class Invoice {
//
// /**
// * Product name
// */
// private String title;
//
// /**
// * Product description
// */
// private String description;
//
// /**
// * Unique bot deep-linking parameter that can be used to generate this invoice
// */
// private String start_parameter;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/SuccessfulPayment.java
// @ToString
// @Getter @Setter
// public class SuccessfulPayment {
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// /**
// * Telegram payment identifier
// */
// private String telegram_payment_charge_id;
//
// /**
// * Provider payment identifier
// */
// private String provider_payment_charge_id;
//
// }
// Path: src/com/cadiducho/minegram/api/Message.java
import com.cadiducho.minegram.api.payment.Invoice;
import com.cadiducho.minegram.api.payment.SuccessfulPayment;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
private Boolean group_chat_created;
/**
* Optional. Informs that the supergroup has been created
*/
private Boolean supergroup_chat_created;
/**
* Optional. Informs that the channel has been created
*/
private Boolean channel_chat_created;
/**
* Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_to_chat_id;
/**
* Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_from_chat_id;
/**
* Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
*/
private Message pinned_message;
/**
* Optional. Message is an invoice for a payment, information about the invoice. More about payments »
*/ | private Invoice invoice; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/Message.java | // Path: src/com/cadiducho/minegram/api/payment/Invoice.java
// @ToString
// @Getter @Setter
// public class Invoice {
//
// /**
// * Product name
// */
// private String title;
//
// /**
// * Product description
// */
// private String description;
//
// /**
// * Unique bot deep-linking parameter that can be used to generate this invoice
// */
// private String start_parameter;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/SuccessfulPayment.java
// @ToString
// @Getter @Setter
// public class SuccessfulPayment {
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// /**
// * Telegram payment identifier
// */
// private String telegram_payment_charge_id;
//
// /**
// * Provider payment identifier
// */
// private String provider_payment_charge_id;
//
// }
| import com.cadiducho.minegram.api.payment.Invoice;
import com.cadiducho.minegram.api.payment.SuccessfulPayment;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | private Boolean supergroup_chat_created;
/**
* Optional. Informs that the channel has been created
*/
private Boolean channel_chat_created;
/**
* Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_to_chat_id;
/**
* Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_from_chat_id;
/**
* Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
*/
private Message pinned_message;
/**
* Optional. Message is an invoice for a payment, information about the invoice. More about payments »
*/
private Invoice invoice;
/**
* Optional. Message is a service message about a successful payment, information about the payment
*/ | // Path: src/com/cadiducho/minegram/api/payment/Invoice.java
// @ToString
// @Getter @Setter
// public class Invoice {
//
// /**
// * Product name
// */
// private String title;
//
// /**
// * Product description
// */
// private String description;
//
// /**
// * Unique bot deep-linking parameter that can be used to generate this invoice
// */
// private String start_parameter;
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// }
//
// Path: src/com/cadiducho/minegram/api/payment/SuccessfulPayment.java
// @ToString
// @Getter @Setter
// public class SuccessfulPayment {
//
// /**
// * Three-letter ISO 4217 currency code
// */
// private String currency;
//
// /**
// * Total price in the smallest units of the currency (integer, not float/double).
// * For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in https://core.telegram.org/bots/payments/currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).
// */
// private Integer total_amount;
//
// /**
// * Bot specified invoice payload
// */
// private String invoce_payload;
//
// /**
// * Optional. Identifier of the shipping option chosen by the user
// */
// private String shipping_option_id;
//
// /**
// * Optional. Order info provided by the user
// */
// private OrderInfo order_info;
//
// /**
// * Telegram payment identifier
// */
// private String telegram_payment_charge_id;
//
// /**
// * Provider payment identifier
// */
// private String provider_payment_charge_id;
//
// }
// Path: src/com/cadiducho/minegram/api/Message.java
import com.cadiducho.minegram.api.payment.Invoice;
import com.cadiducho.minegram.api.payment.SuccessfulPayment;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
private Boolean supergroup_chat_created;
/**
* Optional. Informs that the channel has been created
*/
private Boolean channel_chat_created;
/**
* Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_to_chat_id;
/**
* Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value
*/
private Integer migrate_from_chat_id;
/**
* Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply.
*/
private Message pinned_message;
/**
* Optional. Message is an invoice for a payment, information about the invoice. More about payments »
*/
private Invoice invoice;
/**
* Optional. Message is a service message about a successful payment, information about the payment
*/ | private SuccessfulPayment successful_payment; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java | // Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
| import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.payment;
/**
* This object contains information about an incoming pre-checkout query.
*/
@ToString
@Getter @Setter
public class PreCheckoutQuery {
/**
* Unique query identifier
*/
private String id;
/**
* User who sent the query
*/ | // Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
// Path: src/com/cadiducho/minegram/api/payment/PreCheckoutQuery.java
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.payment;
/**
* This object contains information about an incoming pre-checkout query.
*/
@ToString
@Getter @Setter
public class PreCheckoutQuery {
/**
* Unique query identifier
*/
private String id;
/**
* User who sent the query
*/ | private User from; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
| import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents a result of an inline query that was chosen by the user and sent to their chat partner.
*/
@ToString
@Getter @Setter
public class ChosenInlineResult {
/**
* The unique identifier for the result that was chosen.
*/
private String result_id;
/**
* The user that chose the result.
*/ | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
// Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents a result of an inline query that was chosen by the user and sent to their chat partner.
*/
@ToString
@Getter @Setter
public class ChosenInlineResult {
/**
* The unique identifier for the result that was chosen.
*/
private String result_id;
/**
* The user that chose the result.
*/ | private User from; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
| import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents a result of an inline query that was chosen by the user and sent to their chat partner.
*/
@ToString
@Getter @Setter
public class ChosenInlineResult {
/**
* The unique identifier for the result that was chosen.
*/
private String result_id;
/**
* The user that chose the result.
*/
private User from;
/**
* Optional. Sender location, only for bots that require user location
*/ | // Path: src/com/cadiducho/minegram/api/Location.java
// @ToString
// @Getter @Setter
// public class Location {
//
// /**
// * Longitude as defined by sender
// */
// private Float longitude;
//
// /**
// * Latitude as defined by sender
// */
// private Float latitude;
// }
//
// Path: src/com/cadiducho/minegram/api/User.java
// @ToString
// @Getter @Setter
// public class User {
//
// /**
// * Unique identifier for this user or bot
// */
// private Integer id;
//
// /**
// * User‘s or bot’s first name
// */
// private String first_name;
//
// /**
// * Optional. User‘s or bot’s last name
// */
// private String last_name;
//
// /**
// * Optional. User‘s or bot’s username
// */
// private String username;
//
// /**
// * Optional. IETF language tag of the user's language
// */
// private String language_code;
//
// }
// Path: src/com/cadiducho/minegram/api/inline/ChosenInlineResult.java
import com.cadiducho.minegram.api.Location;
import com.cadiducho.minegram.api.User;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.inline;
/**
* This object represents a result of an inline query that was chosen by the user and sent to their chat partner.
*/
@ToString
@Getter @Setter
public class ChosenInlineResult {
/**
* The unique identifier for the result that was chosen.
*/
private String result_id;
/**
* The user that chose the result.
*/
private User from;
/**
* Optional. Sender location, only for bots that require user location
*/ | private Location location; |
Cadiducho/Minegram | src/com/cadiducho/minegram/api/events/TelegramCommandEvent.java | // Path: src/com/cadiducho/minegram/api/Update.java
// @ToString
// @Getter @Setter
// public class Update {
//
// /**
// * The update‘s unique identifier.
// * Update identifiers start from a certain positive number and increase sequentially.
// * This ID becomes especially handy if you’re using Webhooks,
// * since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
// */
// private Integer update_id;
//
// /**
// * Optional. New incoming message of any kind — text, photo, sticker, etc.
// */
// private Message message;
//
// /**
// * Optional. New version of a message that is known to the bot and was edited
// */
// private Message edited_message;
//
// /**
// * Optional. New incoming channel post of any kind — text, photo, sticker, etc.
// */
// private Message channel_post;
//
// /**
// * Optional. New version of a channel post that is known to the bot and was edited
// */
// private Message edited_channel_post;
// /**
// * Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
// */
// private InlineQuery inline_query;
//
// /**
// * Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
// */
// private ChosenInlineResult chosen_inline_result;
//
// /**
// * Optional. New incoming callback query
// */
// private CallbackQuery callback_query;
//
// /**
// * Optional. New incoming shipping query. Only for invoices with flexible price
// */
// private ShippingQuery shipping_query;
//
// /**
// * Optional. New incoming pre-checkout query. Contains full information about checkout
// */
// private PreCheckoutQuery pre_checkout_query;
//
// }
| import com.cadiducho.minegram.api.Update;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; | /*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.events;
@Getter @Setter
public class TelegramCommandEvent extends Event { | // Path: src/com/cadiducho/minegram/api/Update.java
// @ToString
// @Getter @Setter
// public class Update {
//
// /**
// * The update‘s unique identifier.
// * Update identifiers start from a certain positive number and increase sequentially.
// * This ID becomes especially handy if you’re using Webhooks,
// * since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.
// */
// private Integer update_id;
//
// /**
// * Optional. New incoming message of any kind — text, photo, sticker, etc.
// */
// private Message message;
//
// /**
// * Optional. New version of a message that is known to the bot and was edited
// */
// private Message edited_message;
//
// /**
// * Optional. New incoming channel post of any kind — text, photo, sticker, etc.
// */
// private Message channel_post;
//
// /**
// * Optional. New version of a channel post that is known to the bot and was edited
// */
// private Message edited_channel_post;
// /**
// * Optional. New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query
// */
// private InlineQuery inline_query;
//
// /**
// * Optional. The result of an New incoming <a href="https://core.telegram.org/bots/api#inline-mode" >inline</a> query query that was chosen by a user and sent to their chat partner.
// */
// private ChosenInlineResult chosen_inline_result;
//
// /**
// * Optional. New incoming callback query
// */
// private CallbackQuery callback_query;
//
// /**
// * Optional. New incoming shipping query. Only for invoices with flexible price
// */
// private ShippingQuery shipping_query;
//
// /**
// * Optional. New incoming pre-checkout query. Contains full information about checkout
// */
// private PreCheckoutQuery pre_checkout_query;
//
// }
// Path: src/com/cadiducho/minegram/api/events/TelegramCommandEvent.java
import com.cadiducho.minegram.api.Update;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/*
* The MIT License
*
* Copyright 2017 Cadiducho.
* Read more in https://github.com/Cadiducho/Minegram/blob/master/LICENSE
*/
package com.cadiducho.minegram.api.events;
@Getter @Setter
public class TelegramCommandEvent extends Event { | private Update update; |
sagemath/android | src/org/sagemath/droid/models/gson/InteractReply.java | // Path: src/org/sagemath/droid/constants/ControlType.java
// public class ControlType {
//
// public static final int CONTROL_ERROR = 0x000400;
//
// public static final int CONTROL_SLIDER = 0x000401;
// public static final int CONTROL_SELECTOR = 0x000402;
//
// public static final int SLIDER_DISCRETE = 0x000403;
// public static final int SLIDER_CONTINUOUS = 0x000404;
// }
| import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import org.sagemath.droid.constants.ControlType;
import java.util.ArrayList; | private int _default;
private int[] range;
private String subtype;
private String label;
private int step;
public InteractControl() {
gson = new Gson();
}
public String toString() {
//TODO, Try and use the gson from BaseReply
return gson.toJson(this);
}
public boolean isUpdate() {
return update;
}
public boolean isRaw() {
return raw;
}
public String getStringControlType() {
return control_type;
}
public int getControlType() {
if (control_type.equalsIgnoreCase(STR_SELECTOR)) | // Path: src/org/sagemath/droid/constants/ControlType.java
// public class ControlType {
//
// public static final int CONTROL_ERROR = 0x000400;
//
// public static final int CONTROL_SLIDER = 0x000401;
// public static final int CONTROL_SELECTOR = 0x000402;
//
// public static final int SLIDER_DISCRETE = 0x000403;
// public static final int SLIDER_CONTINUOUS = 0x000404;
// }
// Path: src/org/sagemath/droid/models/gson/InteractReply.java
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import org.sagemath.droid.constants.ControlType;
import java.util.ArrayList;
private int _default;
private int[] range;
private String subtype;
private String label;
private int step;
public InteractControl() {
gson = new Gson();
}
public String toString() {
//TODO, Try and use the gson from BaseReply
return gson.toJson(this);
}
public boolean isUpdate() {
return update;
}
public boolean isRaw() {
return raw;
}
public String getStringControlType() {
return control_type;
}
public int getControlType() {
if (control_type.equalsIgnoreCase(STR_SELECTOR)) | return ControlType.CONTROL_SELECTOR; |
sagemath/android | src/org/sagemath/droid/fragments/HelpHtmlFragment.java | // Path: libs/html-textview/src/main/java/org/sufficientlysecure/htmltextview/HtmlTextView.java
// public class HtmlTextView extends JellyBeanSpanFixTextView {
//
// public static final String TAG = "HtmlTextView";
// public static final boolean DEBUG = false;
//
// public HtmlTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public HtmlTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public HtmlTextView(Context context) {
// super(context);
// }
//
// /**
// * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
// *
// * @param is
// * @return
// */
// static private String convertStreamToString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
// return s.hasNext() ? s.next() : "";
// }
//
// /**
// * Loads HTML from a raw resource, i.e., a HTML file in res/raw/.
// * This allows translatable resource (e.g., res/raw-de/ for german).
// * The containing HTML is parsed to Android's Spannable format and then displayed.
// *
// * @param context
// * @param id for example: R.raw.help
// */
// public void setHtmlFromRawResource(Context context, int id, boolean useLocalDrawables) {
// // load html from html file from /res/raw
// InputStream inputStreamText = context.getResources().openRawResource(id);
//
// setHtmlFromString(convertStreamToString(inputStreamText), useLocalDrawables);
// }
//
// /**
// * Parses String containing HTML to Android's Spannable format and displays it in this TextView.
// *
// * @param html String containing HTML, for example: "<b>Hello world!</b>"
// */
// public void setHtmlFromString(String html, boolean useLocalDrawables) {
// Html.ImageGetter imgGetter;
// if (useLocalDrawables) {
// imgGetter = new LocalImageGetter(getContext());
// } else {
// imgGetter = new UrlImageGetter(this, getContext());
// }
// // this uses Android's Html class for basic parsing, and HtmlTagHandler
// setText(Html.fromHtml(html, imgGetter, new HtmlTagHandler()));
//
// // make links work
// setMovementMethod(LinkMovementMethod.getInstance());
//
// // no flickering when clicking textview for Android < 4, but overriders color...
// // text.setTextColor(getResources().getColor(android.R.color.secondary_text_dark_nodisable));
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import org.sufficientlysecure.htmltextview.HtmlTextView; | package org.sagemath.droid.fragments;
/**
* Fragment which displays an html file loaded from raw
* @author Nikhil Peter Raj
*/
public class HelpHtmlFragment extends Fragment {
public static final String ARG_HTML_FILE = "htmlFile";
Activity activity;
int htmlFile;
public static HelpHtmlFragment newInstance(int htmlFile) {
HelpHtmlFragment f = new HelpHtmlFragment();
// Supply html raw file input as an argument.
Bundle args = new Bundle();
args.putInt(ARG_HTML_FILE, htmlFile);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = getActivity();
htmlFile = getArguments().getInt(ARG_HTML_FILE);
ScrollView scroller = new ScrollView(activity); | // Path: libs/html-textview/src/main/java/org/sufficientlysecure/htmltextview/HtmlTextView.java
// public class HtmlTextView extends JellyBeanSpanFixTextView {
//
// public static final String TAG = "HtmlTextView";
// public static final boolean DEBUG = false;
//
// public HtmlTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public HtmlTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public HtmlTextView(Context context) {
// super(context);
// }
//
// /**
// * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
// *
// * @param is
// * @return
// */
// static private String convertStreamToString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
// return s.hasNext() ? s.next() : "";
// }
//
// /**
// * Loads HTML from a raw resource, i.e., a HTML file in res/raw/.
// * This allows translatable resource (e.g., res/raw-de/ for german).
// * The containing HTML is parsed to Android's Spannable format and then displayed.
// *
// * @param context
// * @param id for example: R.raw.help
// */
// public void setHtmlFromRawResource(Context context, int id, boolean useLocalDrawables) {
// // load html from html file from /res/raw
// InputStream inputStreamText = context.getResources().openRawResource(id);
//
// setHtmlFromString(convertStreamToString(inputStreamText), useLocalDrawables);
// }
//
// /**
// * Parses String containing HTML to Android's Spannable format and displays it in this TextView.
// *
// * @param html String containing HTML, for example: "<b>Hello world!</b>"
// */
// public void setHtmlFromString(String html, boolean useLocalDrawables) {
// Html.ImageGetter imgGetter;
// if (useLocalDrawables) {
// imgGetter = new LocalImageGetter(getContext());
// } else {
// imgGetter = new UrlImageGetter(this, getContext());
// }
// // this uses Android's Html class for basic parsing, and HtmlTagHandler
// setText(Html.fromHtml(html, imgGetter, new HtmlTagHandler()));
//
// // make links work
// setMovementMethod(LinkMovementMethod.getInstance());
//
// // no flickering when clicking textview for Android < 4, but overriders color...
// // text.setTextColor(getResources().getColor(android.R.color.secondary_text_dark_nodisable));
// }
// }
// Path: src/org/sagemath/droid/fragments/HelpHtmlFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import org.sufficientlysecure.htmltextview.HtmlTextView;
package org.sagemath.droid.fragments;
/**
* Fragment which displays an html file loaded from raw
* @author Nikhil Peter Raj
*/
public class HelpHtmlFragment extends Fragment {
public static final String ARG_HTML_FILE = "htmlFile";
Activity activity;
int htmlFile;
public static HelpHtmlFragment newInstance(int htmlFile) {
HelpHtmlFragment f = new HelpHtmlFragment();
// Supply html raw file input as an argument.
Bundle args = new Bundle();
args.putInt(ARG_HTML_FILE, htmlFile);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = getActivity();
htmlFile = getArguments().getInt(ARG_HTML_FILE);
ScrollView scroller = new ScrollView(activity); | HtmlTextView text = new HtmlTextView(activity); |
sagemath/android | src/org/sagemath/droid/models/gson/ImageReply.java | // Path: src/org/sagemath/droid/utils/UrlUtils.java
// public class UrlUtils {
//
// private static final String TAG = "SageDroid:UrlUtils";
//
// public static String getInitialKernelURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTP)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_KERNEL)
// .build();
//
// Log.i(TAG, "Initial Kernal URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getPermalinkURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTPS)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_PERMALINK)
// .build();
//
// Log.i(TAG, "Permalink URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getShellURL(String kernel_id, String webSocketUrl) {
// Uri shellURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_SHELL)
// .build();
//
// Log.i(TAG, "Shell URL: " + shellURL.toString());
//
// return shellURL.toString();
// }
//
// public static String getIoPubURL(String kernel_id, String webSocketUrl) {
// Uri ioPubURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_IOPUB)
// .build();
//
// Log.i(TAG, "IOPub URL: " + ioPubURL.toString());
//
// return ioPubURL.toString();
// }
//
// }
| import android.net.Uri;
import android.util.Log;
import com.google.gson.annotations.SerializedName;
import org.sagemath.droid.utils.UrlUtils; | package org.sagemath.droid.models.gson;
/**
* Reply containing an Image URL.
*
* @author Nikhil Peter Raj
*/
public class ImageReply extends BaseReply {
private static final String TAG = "SageDroid:ImageReply";
private static final String PATH_FILE = "files";
private static final String SUFFIX_PNG = ".png";
private static final String SUFFIX_JPG = ".jpg";
private static final String SUFFIX_JPEG = ".jpeg";
private static final String SUFFIX_SVG = ".svg";
public static final String MIME_IMAGE_PNG = "image/png";
public static final String MIME_IMAGE_SVG = "image/svg";
public ImageReply() {
super();
}
public String toString() {
return gson.toJson(this);
}
private ImageContent content;
public ImageContent getContent() {
return content;
}
private transient String kernelID;
public String getKernelID() {
return kernelID;
}
public void setKernelID(String kernelID) {
this.kernelID = kernelID;
}
public String getImageURL() { | // Path: src/org/sagemath/droid/utils/UrlUtils.java
// public class UrlUtils {
//
// private static final String TAG = "SageDroid:UrlUtils";
//
// public static String getInitialKernelURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTP)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_KERNEL)
// .build();
//
// Log.i(TAG, "Initial Kernal URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getPermalinkURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTPS)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_PERMALINK)
// .build();
//
// Log.i(TAG, "Permalink URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getShellURL(String kernel_id, String webSocketUrl) {
// Uri shellURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_SHELL)
// .build();
//
// Log.i(TAG, "Shell URL: " + shellURL.toString());
//
// return shellURL.toString();
// }
//
// public static String getIoPubURL(String kernel_id, String webSocketUrl) {
// Uri ioPubURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_IOPUB)
// .build();
//
// Log.i(TAG, "IOPub URL: " + ioPubURL.toString());
//
// return ioPubURL.toString();
// }
//
// }
// Path: src/org/sagemath/droid/models/gson/ImageReply.java
import android.net.Uri;
import android.util.Log;
import com.google.gson.annotations.SerializedName;
import org.sagemath.droid.utils.UrlUtils;
package org.sagemath.droid.models.gson;
/**
* Reply containing an Image URL.
*
* @author Nikhil Peter Raj
*/
public class ImageReply extends BaseReply {
private static final String TAG = "SageDroid:ImageReply";
private static final String PATH_FILE = "files";
private static final String SUFFIX_PNG = ".png";
private static final String SUFFIX_JPG = ".jpg";
private static final String SUFFIX_JPEG = ".jpeg";
private static final String SUFFIX_SVG = ".svg";
public static final String MIME_IMAGE_PNG = "image/png";
public static final String MIME_IMAGE_SVG = "image/svg";
public ImageReply() {
super();
}
public String toString() {
return gson.toJson(this);
}
private ImageContent content;
public ImageContent getContent() {
return content;
}
private transient String kernelID;
public String getKernelID() {
return kernelID;
}
public void setKernelID(String kernelID) {
this.kernelID = kernelID;
}
public String getImageURL() { | String kernelURL = UrlUtils.getInitialKernelURL(); |
sagemath/android | src/org/sagemath/droid/deserializers/InteractContentDeserializer.java | // Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class InteractContent {
//
// private InteractData data;
// private String source;
//
// public InteractData getData() {
// return data;
// }
//
// public void setData(InteractData data) {
// this.data = data;
// }
//
// public String getSource() {
// return source;
// }
//
// public void setSource(String source) {
// this.source = source;
// }
// }
//
// Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class InteractData {
// //---POSSIBLE SAGE REPLIES---
// @SerializedName("application/sage-interact")
// private SageInteract sageInteract;
//
// @SerializedName("text/plain")
// private String descText;
//
// public SageInteract getInteract() {
// return sageInteract;
// }
//
// public void setInteract(SageInteract sageInteract) {
// this.sageInteract = sageInteract;
// }
//
// public String getDescText() {
// return descText;
// }
//
// public void setDescText(String descText) {
// this.descText = descText;
// }
// }
| import com.google.gson.*;
import org.sagemath.droid.models.gson.InteractReply.InteractContent;
import org.sagemath.droid.models.gson.InteractReply.InteractData;
import java.lang.reflect.Type; | package org.sagemath.droid.deserializers;
/**
* Deserializer for {@link org.sagemath.droid.models.gson.InteractReply.InteractContent}
*
* @author Nikhil Peter Raj
*/
public class InteractContentDeserializer implements JsonDeserializer<InteractContent> {
private static String KEY_SOURCE = "source";
private static String KEY_DATA = "data";
@Override
public InteractContent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String source = jsonObject.get(KEY_SOURCE).getAsString();
JsonElement data = jsonObject.get(KEY_DATA);
| // Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class InteractContent {
//
// private InteractData data;
// private String source;
//
// public InteractData getData() {
// return data;
// }
//
// public void setData(InteractData data) {
// this.data = data;
// }
//
// public String getSource() {
// return source;
// }
//
// public void setSource(String source) {
// this.source = source;
// }
// }
//
// Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class InteractData {
// //---POSSIBLE SAGE REPLIES---
// @SerializedName("application/sage-interact")
// private SageInteract sageInteract;
//
// @SerializedName("text/plain")
// private String descText;
//
// public SageInteract getInteract() {
// return sageInteract;
// }
//
// public void setInteract(SageInteract sageInteract) {
// this.sageInteract = sageInteract;
// }
//
// public String getDescText() {
// return descText;
// }
//
// public void setDescText(String descText) {
// this.descText = descText;
// }
// }
// Path: src/org/sagemath/droid/deserializers/InteractContentDeserializer.java
import com.google.gson.*;
import org.sagemath.droid.models.gson.InteractReply.InteractContent;
import org.sagemath.droid.models.gson.InteractReply.InteractData;
import java.lang.reflect.Type;
package org.sagemath.droid.deserializers;
/**
* Deserializer for {@link org.sagemath.droid.models.gson.InteractReply.InteractContent}
*
* @author Nikhil Peter Raj
*/
public class InteractContentDeserializer implements JsonDeserializer<InteractContent> {
private static String KEY_SOURCE = "source";
private static String KEY_DATA = "data";
@Override
public InteractContent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String source = jsonObject.get(KEY_SOURCE).getAsString();
JsonElement data = jsonObject.get(KEY_DATA);
| InteractData interactData = context.deserialize(data, InteractData.class); |
sagemath/android | src/org/sagemath/droid/utils/SimpleEula.java | // Path: src/org/sagemath/droid/exceptions/SageInterruptedException.java
// public class SageInterruptedException extends Exception {
// private static final long serialVersionUID = -5638564842011063160L;
// }
| import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.sagemath.droid.R;
import org.sagemath.droid.exceptions.SageInterruptedException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException; | /*
int port = 10080;
URI termsURI = new URI(tosURI.getScheme(), tosURI.getUserInfo(), tosURI.getHost(), port,
tosURI.getPath(), tosURI.getQuery(), tosURI.getFragment());
Log.i(TAG, "Terms URI: " + termsURI.toString());
*/
HttpGet termsGet = new HttpGet();
termsGet.setURI(tosURI);
DefaultHttpClient termsHttpClient = new DefaultHttpClient();
HttpResponse termsResponse = termsHttpClient.execute(termsGet);
InputStream termsStream = termsResponse.getEntity().getContent();
termsString = streamToString(termsStream);
} catch (Exception e) {
Log.e(TAG, "Error while getting EULA text." + e.getLocalizedMessage());
}
return termsString;
}
protected void onPostExecute(String html) {
try {
show(html);
} catch (Exception e) {
Log.e(TAG, "Error showing terms: " + e.getLocalizedMessage());
}
}
}
| // Path: src/org/sagemath/droid/exceptions/SageInterruptedException.java
// public class SageInterruptedException extends Exception {
// private static final long serialVersionUID = -5638564842011063160L;
// }
// Path: src/org/sagemath/droid/utils/SimpleEula.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.sagemath.droid.R;
import org.sagemath.droid.exceptions.SageInterruptedException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
/*
int port = 10080;
URI termsURI = new URI(tosURI.getScheme(), tosURI.getUserInfo(), tosURI.getHost(), port,
tosURI.getPath(), tosURI.getQuery(), tosURI.getFragment());
Log.i(TAG, "Terms URI: " + termsURI.toString());
*/
HttpGet termsGet = new HttpGet();
termsGet.setURI(tosURI);
DefaultHttpClient termsHttpClient = new DefaultHttpClient();
HttpResponse termsResponse = termsHttpClient.execute(termsGet);
InputStream termsStream = termsResponse.getEntity().getContent();
termsString = streamToString(termsStream);
} catch (Exception e) {
Log.e(TAG, "Error while getting EULA text." + e.getLocalizedMessage());
}
return termsString;
}
protected void onPostExecute(String html) {
try {
show(html);
} catch (Exception e) {
Log.e(TAG, "Error showing terms: " + e.getLocalizedMessage());
}
}
}
| public void show(String termsHTML) throws IOException, SageInterruptedException, JSONException, URISyntaxException { |
sagemath/android | src/org/sagemath/droid/models/gson/Header.java | // Path: src/org/sagemath/droid/constants/MessageType.java
// public class MessageType {
// public static final int ERROR = 0x000100;
// public static final int PYOUT = 0x000101;
// public static final int PYIN = 0x000102;
// public static final int STATUS = 0x000103;
// public static final int DISPLAY_DATA = 0x000104;
// public static final int STREAM = 0x000105;
// public static final int PYERR = 0x000106;
// public static final int EXECUTE_REQUEST = 0x000107;
// public static final int EXECUTE_REPLY = 0x000108;
// public static final int HTML_FILES = 0x000109;
// public static final int INTERACT_PREPARE = 0x000110;
// public static final int EXTENSION = 0x000111;
// public static final int TEXT_FILENAME = 0x000112;
// public static final int IMAGE_FILENAME = 0x000113;
// public static final int INTERACT = 0x000114;
// public static final int SAGE_CLEAR = 0x000115;
// }
| import android.os.Parcel;
import android.os.Parcelable;
import org.sagemath.droid.constants.MessageType;
import java.util.UUID; | }
//--SETTERS AND GETTERS
public String getMessageID() {
return msg_id;
}
public void setMessageID(String msg_id) {
this.msg_id = msg_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
//Possibly redundant, now that we check from BaseReply directly
public int getMessageType() {
if (msg_type.equalsIgnoreCase(STR_EXECUTE_REPLY)) | // Path: src/org/sagemath/droid/constants/MessageType.java
// public class MessageType {
// public static final int ERROR = 0x000100;
// public static final int PYOUT = 0x000101;
// public static final int PYIN = 0x000102;
// public static final int STATUS = 0x000103;
// public static final int DISPLAY_DATA = 0x000104;
// public static final int STREAM = 0x000105;
// public static final int PYERR = 0x000106;
// public static final int EXECUTE_REQUEST = 0x000107;
// public static final int EXECUTE_REPLY = 0x000108;
// public static final int HTML_FILES = 0x000109;
// public static final int INTERACT_PREPARE = 0x000110;
// public static final int EXTENSION = 0x000111;
// public static final int TEXT_FILENAME = 0x000112;
// public static final int IMAGE_FILENAME = 0x000113;
// public static final int INTERACT = 0x000114;
// public static final int SAGE_CLEAR = 0x000115;
// }
// Path: src/org/sagemath/droid/models/gson/Header.java
import android.os.Parcel;
import android.os.Parcelable;
import org.sagemath.droid.constants.MessageType;
import java.util.UUID;
}
//--SETTERS AND GETTERS
public String getMessageID() {
return msg_id;
}
public void setMessageID(String msg_id) {
this.msg_id = msg_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
//Possibly redundant, now that we check from BaseReply directly
public int getMessageType() {
if (msg_type.equalsIgnoreCase(STR_EXECUTE_REPLY)) | return MessageType.EXECUTE_REPLY; |
sagemath/android | src/org/sagemath/droid/dialogs/ShareDialogFragment.java | // Path: src/org/sagemath/droid/utils/BusProvider.java
// public class BusProvider {
//
// private static Bus bus;
//
// public static Bus getInstance() {
// if (bus == null) {
// bus = new Bus();
// }
//
// return bus;
// }
// }
| import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.*;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
import org.sagemath.droid.R;
import org.sagemath.droid.utils.BusProvider; | package org.sagemath.droid.dialogs;
/**
* <p>The {@link android.support.v4.app.DialogFragment} which displays the share options</p>
* @author Nikhil Peter Raj
*/
public class ShareDialogFragment extends DialogFragment {
private static final String TAG = "SageDroid:ShareDialogFragment";
public static interface OnRequestOutputListener {
public void onRequestOutput();
}
private OnRequestOutputListener listener;
private String shareUrl;
private int selected = -1;
private static final String ARG_URL = "shareURL";
public static ShareDialogFragment getInstance(String permalinkUrl) {
ShareDialogFragment fragment = new ShareDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_URL, permalinkUrl);
fragment.setArguments(args);
return fragment;
}
@Override
public void onPause() {
super.onPause(); | // Path: src/org/sagemath/droid/utils/BusProvider.java
// public class BusProvider {
//
// private static Bus bus;
//
// public static Bus getInstance() {
// if (bus == null) {
// bus = new Bus();
// }
//
// return bus;
// }
// }
// Path: src/org/sagemath/droid/dialogs/ShareDialogFragment.java
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.*;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
import org.sagemath.droid.R;
import org.sagemath.droid.utils.BusProvider;
package org.sagemath.droid.dialogs;
/**
* <p>The {@link android.support.v4.app.DialogFragment} which displays the share options</p>
* @author Nikhil Peter Raj
*/
public class ShareDialogFragment extends DialogFragment {
private static final String TAG = "SageDroid:ShareDialogFragment";
public static interface OnRequestOutputListener {
public void onRequestOutput();
}
private OnRequestOutputListener listener;
private String shareUrl;
private int selected = -1;
private static final String ARG_URL = "shareURL";
public static ShareDialogFragment getInstance(String permalinkUrl) {
ShareDialogFragment fragment = new ShareDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_URL, permalinkUrl);
fragment.setArguments(args);
return fragment;
}
@Override
public void onPause() {
super.onPause(); | BusProvider.getInstance().register(this); |
sagemath/android | src/org/sagemath/droid/models/gson/PermalinkResponse.java | // Path: src/org/sagemath/droid/utils/UrlUtils.java
// public class UrlUtils {
//
// private static final String TAG = "SageDroid:UrlUtils";
//
// public static String getInitialKernelURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTP)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_KERNEL)
// .build();
//
// Log.i(TAG, "Initial Kernal URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getPermalinkURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTPS)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_PERMALINK)
// .build();
//
// Log.i(TAG, "Permalink URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getShellURL(String kernel_id, String webSocketUrl) {
// Uri shellURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_SHELL)
// .build();
//
// Log.i(TAG, "Shell URL: " + shellURL.toString());
//
// return shellURL.toString();
// }
//
// public static String getIoPubURL(String kernel_id, String webSocketUrl) {
// Uri ioPubURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_IOPUB)
// .build();
//
// Log.i(TAG, "IOPub URL: " + ioPubURL.toString());
//
// return ioPubURL.toString();
// }
//
// }
| import android.net.Uri;
import org.sagemath.droid.utils.UrlUtils; | package org.sagemath.droid.models.gson;
/**
* Response from server containing the permalink paths.
*
* @author Nikhil Peter Raj
*/
public class PermalinkResponse extends BaseResponse {
private String query;
private String zip;
public String getQueryID() {
return query;
}
public String getZip() {
return zip;
}
public String getQueryURL() { | // Path: src/org/sagemath/droid/utils/UrlUtils.java
// public class UrlUtils {
//
// private static final String TAG = "SageDroid:UrlUtils";
//
// public static String getInitialKernelURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTP)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_KERNEL)
// .build();
//
// Log.i(TAG, "Initial Kernal URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getPermalinkURL() {
// Uri.Builder builder = new Uri.Builder();
// builder
// .scheme(SCHEME_HTTPS)
// .authority(BASE_SERVER_URL)
// .appendPath(PATH_PERMALINK)
// .build();
//
// Log.i(TAG, "Permalink URL: " + builder.toString());
//
// return builder.toString();
// }
//
// public static String getShellURL(String kernel_id, String webSocketUrl) {
// Uri shellURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_SHELL)
// .build();
//
// Log.i(TAG, "Shell URL: " + shellURL.toString());
//
// return shellURL.toString();
// }
//
// public static String getIoPubURL(String kernel_id, String webSocketUrl) {
// Uri ioPubURL = Uri.parse(webSocketUrl).buildUpon()
// .appendPath(PATH_KERNEL)
// .appendPath(kernel_id)
// .appendPath(PATH_IOPUB)
// .build();
//
// Log.i(TAG, "IOPub URL: " + ioPubURL.toString());
//
// return ioPubURL.toString();
// }
//
// }
// Path: src/org/sagemath/droid/models/gson/PermalinkResponse.java
import android.net.Uri;
import org.sagemath.droid.utils.UrlUtils;
package org.sagemath.droid.models.gson;
/**
* Response from server containing the permalink paths.
*
* @author Nikhil Peter Raj
*/
public class PermalinkResponse extends BaseResponse {
private String query;
private String zip;
public String getQueryID() {
return query;
}
public String getZip() {
return zip;
}
public String getQueryURL() { | Uri queryUri = Uri.parse(UrlUtils.getPermalinkURL()) |
sagemath/android | src/org/sagemath/droid/deserializers/InteractDataDeserializer.java | // Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class InteractData {
// //---POSSIBLE SAGE REPLIES---
// @SerializedName("application/sage-interact")
// private SageInteract sageInteract;
//
// @SerializedName("text/plain")
// private String descText;
//
// public SageInteract getInteract() {
// return sageInteract;
// }
//
// public void setInteract(SageInteract sageInteract) {
// this.sageInteract = sageInteract;
// }
//
// public String getDescText() {
// return descText;
// }
//
// public void setDescText(String descText) {
// this.descText = descText;
// }
// }
//
// Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class SageInteract {
//
// private String new_interact_id;
// private ArrayList<InteractControl> controls;
// private boolean readonly;
// private String locations;
// private ArrayList<ArrayList<ArrayList<String>>> layout;
//
// public String getNewInteractID() {
// return new_interact_id;
// }
//
// public void setNewInteractID(String new_interact_id) {
// this.new_interact_id = new_interact_id;
// }
//
// public ArrayList<InteractControl> getControls() {
// return controls;
// }
//
// public void setControls(ArrayList<InteractControl> controls) {
// this.controls = controls;
// }
//
// public boolean isReadonly() {
// return readonly;
// }
//
// public void setReadonly(boolean readonly) {
// this.readonly = readonly;
// }
//
// public String getLocations() {
// return locations;
// }
//
// public void setLocations(String locations) {
// this.locations = locations;
// }
//
// public ArrayList<ArrayList<ArrayList<String>>> getLayout() {
// return layout;
// }
//
// public void setLayout(ArrayList<ArrayList<ArrayList<String>>> layout) {
// this.layout = layout;
// }
// }
| import com.google.gson.*;
import org.sagemath.droid.models.gson.InteractReply.InteractData;
import org.sagemath.droid.models.gson.InteractReply.SageInteract;
import java.lang.reflect.Type; | package org.sagemath.droid.deserializers;
/**
* Deserializer for {@link org.sagemath.droid.models.gson.InteractReply.InteractData}
* @author Nikhil Peter Raj
*/
public class InteractDataDeserializer implements JsonDeserializer<InteractData> {
private static final String KEY_INTERACT="application/sage-interact";
private static final String KEY_DESC_TEXT="text/plain";
@Override
public InteractData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonElement interact = jsonObject.get(KEY_INTERACT);
String descText = jsonObject.get(KEY_DESC_TEXT).getAsString();
| // Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class InteractData {
// //---POSSIBLE SAGE REPLIES---
// @SerializedName("application/sage-interact")
// private SageInteract sageInteract;
//
// @SerializedName("text/plain")
// private String descText;
//
// public SageInteract getInteract() {
// return sageInteract;
// }
//
// public void setInteract(SageInteract sageInteract) {
// this.sageInteract = sageInteract;
// }
//
// public String getDescText() {
// return descText;
// }
//
// public void setDescText(String descText) {
// this.descText = descText;
// }
// }
//
// Path: src/org/sagemath/droid/models/gson/InteractReply.java
// public static class SageInteract {
//
// private String new_interact_id;
// private ArrayList<InteractControl> controls;
// private boolean readonly;
// private String locations;
// private ArrayList<ArrayList<ArrayList<String>>> layout;
//
// public String getNewInteractID() {
// return new_interact_id;
// }
//
// public void setNewInteractID(String new_interact_id) {
// this.new_interact_id = new_interact_id;
// }
//
// public ArrayList<InteractControl> getControls() {
// return controls;
// }
//
// public void setControls(ArrayList<InteractControl> controls) {
// this.controls = controls;
// }
//
// public boolean isReadonly() {
// return readonly;
// }
//
// public void setReadonly(boolean readonly) {
// this.readonly = readonly;
// }
//
// public String getLocations() {
// return locations;
// }
//
// public void setLocations(String locations) {
// this.locations = locations;
// }
//
// public ArrayList<ArrayList<ArrayList<String>>> getLayout() {
// return layout;
// }
//
// public void setLayout(ArrayList<ArrayList<ArrayList<String>>> layout) {
// this.layout = layout;
// }
// }
// Path: src/org/sagemath/droid/deserializers/InteractDataDeserializer.java
import com.google.gson.*;
import org.sagemath.droid.models.gson.InteractReply.InteractData;
import org.sagemath.droid.models.gson.InteractReply.SageInteract;
import java.lang.reflect.Type;
package org.sagemath.droid.deserializers;
/**
* Deserializer for {@link org.sagemath.droid.models.gson.InteractReply.InteractData}
* @author Nikhil Peter Raj
*/
public class InteractDataDeserializer implements JsonDeserializer<InteractData> {
private static final String KEY_INTERACT="application/sage-interact";
private static final String KEY_DESC_TEXT="text/plain";
@Override
public InteractData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonElement interact = jsonObject.get(KEY_INTERACT);
String descText = jsonObject.get(KEY_DESC_TEXT).getAsString();
| SageInteract sageInteract = context.deserialize(interact,SageInteract.class); |
sagemath/android | src/org/sagemath/droid/views/SageJavascriptInterface.java | // Path: src/org/sagemath/droid/events/CodeReceivedEvent.java
// public class CodeReceivedEvent {
// private String receivedCode;
// private boolean forRun;
//
// public boolean isForRun() {
// return forRun;
// }
//
// public void setForRun(boolean forRun) {
// this.forRun = forRun;
// }
//
// public CodeReceivedEvent(String receivedCode) {
// this.receivedCode = receivedCode;
// }
//
// public String getReceivedCode() {
// return receivedCode;
// }
// }
//
// Path: src/org/sagemath/droid/utils/BusProvider.java
// public class BusProvider {
//
// private static Bus bus;
//
// public static Bus getInstance() {
// if (bus == null) {
// bus = new Bus();
// }
//
// return bus;
// }
// }
| import android.app.Activity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import org.sagemath.droid.events.CodeReceivedEvent;
import org.sagemath.droid.utils.BusProvider; | package org.sagemath.droid.views;
/**
* The JavaScript Interface to communicate with CodeMirror.
*
* @author Nikhil Peter Raj
*/
public class SageJavascriptInterface {
private static String TAG = "SageDroid:JavaScriptInterface";
private boolean forRun = false;
private Activity activity;
public SageJavascriptInterface(Activity activity) {
this.activity = activity;
}
public boolean isForRun() {
return forRun;
}
public void setForRun(boolean forRun) {
this.forRun = forRun;
}
/**
* Obtain the text in the CodeMirror editor via the Javascript function of the same name.
*
* @param html
*/
@JavascriptInterface
public void getHtml(String html) {
Log.i(TAG, "Got Text from Editor: " + html);
if (html != null) { | // Path: src/org/sagemath/droid/events/CodeReceivedEvent.java
// public class CodeReceivedEvent {
// private String receivedCode;
// private boolean forRun;
//
// public boolean isForRun() {
// return forRun;
// }
//
// public void setForRun(boolean forRun) {
// this.forRun = forRun;
// }
//
// public CodeReceivedEvent(String receivedCode) {
// this.receivedCode = receivedCode;
// }
//
// public String getReceivedCode() {
// return receivedCode;
// }
// }
//
// Path: src/org/sagemath/droid/utils/BusProvider.java
// public class BusProvider {
//
// private static Bus bus;
//
// public static Bus getInstance() {
// if (bus == null) {
// bus = new Bus();
// }
//
// return bus;
// }
// }
// Path: src/org/sagemath/droid/views/SageJavascriptInterface.java
import android.app.Activity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import org.sagemath.droid.events.CodeReceivedEvent;
import org.sagemath.droid.utils.BusProvider;
package org.sagemath.droid.views;
/**
* The JavaScript Interface to communicate with CodeMirror.
*
* @author Nikhil Peter Raj
*/
public class SageJavascriptInterface {
private static String TAG = "SageDroid:JavaScriptInterface";
private boolean forRun = false;
private Activity activity;
public SageJavascriptInterface(Activity activity) {
this.activity = activity;
}
public boolean isForRun() {
return forRun;
}
public void setForRun(boolean forRun) {
this.forRun = forRun;
}
/**
* Obtain the text in the CodeMirror editor via the Javascript function of the same name.
*
* @param html
*/
@JavascriptInterface
public void getHtml(String html) {
Log.i(TAG, "Got Text from Editor: " + html);
if (html != null) { | final CodeReceivedEvent event = new CodeReceivedEvent(html); |
sagemath/android | src/org/sagemath/droid/views/SageJavascriptInterface.java | // Path: src/org/sagemath/droid/events/CodeReceivedEvent.java
// public class CodeReceivedEvent {
// private String receivedCode;
// private boolean forRun;
//
// public boolean isForRun() {
// return forRun;
// }
//
// public void setForRun(boolean forRun) {
// this.forRun = forRun;
// }
//
// public CodeReceivedEvent(String receivedCode) {
// this.receivedCode = receivedCode;
// }
//
// public String getReceivedCode() {
// return receivedCode;
// }
// }
//
// Path: src/org/sagemath/droid/utils/BusProvider.java
// public class BusProvider {
//
// private static Bus bus;
//
// public static Bus getInstance() {
// if (bus == null) {
// bus = new Bus();
// }
//
// return bus;
// }
// }
| import android.app.Activity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import org.sagemath.droid.events.CodeReceivedEvent;
import org.sagemath.droid.utils.BusProvider; | package org.sagemath.droid.views;
/**
* The JavaScript Interface to communicate with CodeMirror.
*
* @author Nikhil Peter Raj
*/
public class SageJavascriptInterface {
private static String TAG = "SageDroid:JavaScriptInterface";
private boolean forRun = false;
private Activity activity;
public SageJavascriptInterface(Activity activity) {
this.activity = activity;
}
public boolean isForRun() {
return forRun;
}
public void setForRun(boolean forRun) {
this.forRun = forRun;
}
/**
* Obtain the text in the CodeMirror editor via the Javascript function of the same name.
*
* @param html
*/
@JavascriptInterface
public void getHtml(String html) {
Log.i(TAG, "Got Text from Editor: " + html);
if (html != null) {
final CodeReceivedEvent event = new CodeReceivedEvent(html);
event.setForRun(forRun);
activity.runOnUiThread(new Runnable() {
@Override
public void run() { | // Path: src/org/sagemath/droid/events/CodeReceivedEvent.java
// public class CodeReceivedEvent {
// private String receivedCode;
// private boolean forRun;
//
// public boolean isForRun() {
// return forRun;
// }
//
// public void setForRun(boolean forRun) {
// this.forRun = forRun;
// }
//
// public CodeReceivedEvent(String receivedCode) {
// this.receivedCode = receivedCode;
// }
//
// public String getReceivedCode() {
// return receivedCode;
// }
// }
//
// Path: src/org/sagemath/droid/utils/BusProvider.java
// public class BusProvider {
//
// private static Bus bus;
//
// public static Bus getInstance() {
// if (bus == null) {
// bus = new Bus();
// }
//
// return bus;
// }
// }
// Path: src/org/sagemath/droid/views/SageJavascriptInterface.java
import android.app.Activity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import org.sagemath.droid.events.CodeReceivedEvent;
import org.sagemath.droid.utils.BusProvider;
package org.sagemath.droid.views;
/**
* The JavaScript Interface to communicate with CodeMirror.
*
* @author Nikhil Peter Raj
*/
public class SageJavascriptInterface {
private static String TAG = "SageDroid:JavaScriptInterface";
private boolean forRun = false;
private Activity activity;
public SageJavascriptInterface(Activity activity) {
this.activity = activity;
}
public boolean isForRun() {
return forRun;
}
public void setForRun(boolean forRun) {
this.forRun = forRun;
}
/**
* Obtain the text in the CodeMirror editor via the Javascript function of the same name.
*
* @param html
*/
@JavascriptInterface
public void getHtml(String html) {
Log.i(TAG, "Got Text from Editor: " + html);
if (html != null) {
final CodeReceivedEvent event = new CodeReceivedEvent(html);
event.setForRun(forRun);
activity.runOnUiThread(new Runnable() {
@Override
public void run() { | BusProvider.getInstance().post(event); |
sagemath/android | src/org/sagemath/droid/dialogs/DeleteCellDialogFragment.java | // Path: src/org/sagemath/droid/models/database/Cell.java
// public class Cell implements Parcelable {
//
// Long _id;
// String uuid;
// Group cellGroup;
// String title;
// String description;
// String input;
// int rank;
// boolean favorite;
//
// public Cell() {
// setUUID(UUID.randomUUID());
// //This id should be unique since UUID is inherently unique.
// _id = Long.valueOf(uuid.hashCode());
// favorite = false;
// }
//
// //---For Parcelable---
//
// private Cell(Parcel in) {
// _id = in.readLong();
// uuid = in.readString();
// cellGroup = in.readParcelable(Group.class.getClassLoader());
// title = in.readString();
// description = in.readString();
// input = in.readString();
// rank = in.readInt();
// favorite = in.readByte() != 0;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeLong(_id);
// dest.writeString(uuid);
// dest.writeParcelable(cellGroup, flags);
// dest.writeString(title);
// dest.writeString(description);
// dest.writeString(input);
// dest.writeInt(rank);
// dest.writeByte((byte) (favorite ? 1 : 0));
// }
//
// public static final Creator<Cell> CREATOR = new Creator<Cell>() {
// @Override
// public Cell createFromParcel(Parcel source) {
// return new Cell(source);
// }
//
// @Override
// public Cell[] newArray(int size) {
// return new Cell[size];
// }
// };
//
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("ID" + _id);
// builder.append("\t");
// builder.append("UUID:" + uuid + "\t");
// builder.append("Group:" + cellGroup + "\t");
// builder.append("Title" + title + "\t");
// builder.append("Description" + description + "\t");
// builder.append("Input" + input + "\t");
// builder.append("Rank" + rank);
// builder.append("\t");
// builder.append(favorite);
//
// return builder.toString();
// }
//
// //--Setters & Getters
//
// public long getID() {
// return _id;
// }
//
// public void setID(long _id) {
// this._id = _id;
// }
//
// public UUID getUUID() {
// return UUID.fromString(uuid);
// }
//
// public void setUUID(UUID uuid) {
// this.uuid = uuid.toString();
// }
//
// public Group getGroup() {
// return cellGroup;
// }
//
// public void setGroup(Group cellGroup) {
// this.cellGroup = cellGroup;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getInput() {
// return input;
// }
//
// public void setInput(String input) {
// this.input = input;
// }
//
// public int getRank() {
// return rank;
// }
//
// public void setRank(int rank) {
// this.rank = rank;
// }
//
// public boolean isFavorite() {
// return favorite;
// }
//
// public void setFavorite(boolean favorite) {
// this.favorite = favorite;
// }
//
// public static class CellComparator implements Comparator<Cell> {
// @Override
// public int compare(Cell lhs, Cell rhs) {
// int cmp = Boolean.valueOf(lhs.isFavorite())
// .compareTo(rhs.isFavorite());
// if (cmp != 0)
// return cmp;
// cmp = Integer.valueOf(rhs.getRank()).compareTo(lhs.getRank());
// if (cmp != 0) {
// return cmp;
// }
// return lhs.getTitle().compareToIgnoreCase(rhs.getTitle());
// }
// }
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import org.sagemath.droid.R;
import org.sagemath.droid.models.database.Cell;
import java.util.ArrayList; | package org.sagemath.droid.dialogs;
/**
* <p>The {@link android.support.v4.app.DialogFragment} used to delete a cell</p>
*
* @author Nikhil Peter Raj
*/
public class DeleteCellDialogFragment extends BaseDeleteDialogFragment {
private static final String TAG = "SageDroid:DeleteCellDialogFragment";
private static final String ARG_CELL = "cell";
| // Path: src/org/sagemath/droid/models/database/Cell.java
// public class Cell implements Parcelable {
//
// Long _id;
// String uuid;
// Group cellGroup;
// String title;
// String description;
// String input;
// int rank;
// boolean favorite;
//
// public Cell() {
// setUUID(UUID.randomUUID());
// //This id should be unique since UUID is inherently unique.
// _id = Long.valueOf(uuid.hashCode());
// favorite = false;
// }
//
// //---For Parcelable---
//
// private Cell(Parcel in) {
// _id = in.readLong();
// uuid = in.readString();
// cellGroup = in.readParcelable(Group.class.getClassLoader());
// title = in.readString();
// description = in.readString();
// input = in.readString();
// rank = in.readInt();
// favorite = in.readByte() != 0;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeLong(_id);
// dest.writeString(uuid);
// dest.writeParcelable(cellGroup, flags);
// dest.writeString(title);
// dest.writeString(description);
// dest.writeString(input);
// dest.writeInt(rank);
// dest.writeByte((byte) (favorite ? 1 : 0));
// }
//
// public static final Creator<Cell> CREATOR = new Creator<Cell>() {
// @Override
// public Cell createFromParcel(Parcel source) {
// return new Cell(source);
// }
//
// @Override
// public Cell[] newArray(int size) {
// return new Cell[size];
// }
// };
//
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append("ID" + _id);
// builder.append("\t");
// builder.append("UUID:" + uuid + "\t");
// builder.append("Group:" + cellGroup + "\t");
// builder.append("Title" + title + "\t");
// builder.append("Description" + description + "\t");
// builder.append("Input" + input + "\t");
// builder.append("Rank" + rank);
// builder.append("\t");
// builder.append(favorite);
//
// return builder.toString();
// }
//
// //--Setters & Getters
//
// public long getID() {
// return _id;
// }
//
// public void setID(long _id) {
// this._id = _id;
// }
//
// public UUID getUUID() {
// return UUID.fromString(uuid);
// }
//
// public void setUUID(UUID uuid) {
// this.uuid = uuid.toString();
// }
//
// public Group getGroup() {
// return cellGroup;
// }
//
// public void setGroup(Group cellGroup) {
// this.cellGroup = cellGroup;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getInput() {
// return input;
// }
//
// public void setInput(String input) {
// this.input = input;
// }
//
// public int getRank() {
// return rank;
// }
//
// public void setRank(int rank) {
// this.rank = rank;
// }
//
// public boolean isFavorite() {
// return favorite;
// }
//
// public void setFavorite(boolean favorite) {
// this.favorite = favorite;
// }
//
// public static class CellComparator implements Comparator<Cell> {
// @Override
// public int compare(Cell lhs, Cell rhs) {
// int cmp = Boolean.valueOf(lhs.isFavorite())
// .compareTo(rhs.isFavorite());
// if (cmp != 0)
// return cmp;
// cmp = Integer.valueOf(rhs.getRank()).compareTo(lhs.getRank());
// if (cmp != 0) {
// return cmp;
// }
// return lhs.getTitle().compareToIgnoreCase(rhs.getTitle());
// }
// }
// }
// Path: src/org/sagemath/droid/dialogs/DeleteCellDialogFragment.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import org.sagemath.droid.R;
import org.sagemath.droid.models.database.Cell;
import java.util.ArrayList;
package org.sagemath.droid.dialogs;
/**
* <p>The {@link android.support.v4.app.DialogFragment} used to delete a cell</p>
*
* @author Nikhil Peter Raj
*/
public class DeleteCellDialogFragment extends BaseDeleteDialogFragment {
private static final String TAG = "SageDroid:DeleteCellDialogFragment";
private static final String ARG_CELL = "cell";
| public static DeleteCellDialogFragment newInstance(ArrayList<Cell> cells) { |
sagemath/android | src/org/sagemath/droid/models/gson/StatusReply.java | // Path: src/org/sagemath/droid/constants/ExecutionState.java
// public class ExecutionState {
// public static final int ERROR = 0x000300;
// public static final int IDLE = 0x000301;
// public static final int BUSY = 0x000302;
// public static final int DEAD = 0x000303;
// public static final int OK = 0x000304;
// }
| import org.sagemath.droid.constants.ExecutionState; | package org.sagemath.droid.models.gson;
/**
* Reply corresponding to server status.
*
* @author Nikhil Peter Raj
*/
public class StatusReply extends BaseReply {
private StatusContent content;
public StatusReply() {
super();
}
public String toString() {
return gson.toJson(this);
}
public StatusContent getContent() {
return content;
}
public static class StatusContent {
public static final String STR_BUSY = "busy";
public static final String STR_IDLE = "idle";
public static final String STR_DEAD = "dead";
public static final String STR_OK = "ok"; //Not sure if this status exists
private String execution_state;
public String getStringExecutionState() {
return execution_state;
}
public int getExecutionState() {
if (execution_state.equalsIgnoreCase(STR_BUSY)) | // Path: src/org/sagemath/droid/constants/ExecutionState.java
// public class ExecutionState {
// public static final int ERROR = 0x000300;
// public static final int IDLE = 0x000301;
// public static final int BUSY = 0x000302;
// public static final int DEAD = 0x000303;
// public static final int OK = 0x000304;
// }
// Path: src/org/sagemath/droid/models/gson/StatusReply.java
import org.sagemath.droid.constants.ExecutionState;
package org.sagemath.droid.models.gson;
/**
* Reply corresponding to server status.
*
* @author Nikhil Peter Raj
*/
public class StatusReply extends BaseReply {
private StatusContent content;
public StatusReply() {
super();
}
public String toString() {
return gson.toJson(this);
}
public StatusContent getContent() {
return content;
}
public static class StatusContent {
public static final String STR_BUSY = "busy";
public static final String STR_IDLE = "idle";
public static final String STR_DEAD = "dead";
public static final String STR_OK = "ok"; //Not sure if this status exists
private String execution_state;
public String getStringExecutionState() {
return execution_state;
}
public int getExecutionState() {
if (execution_state.equalsIgnoreCase(STR_BUSY)) | return ExecutionState.BUSY; |
sagemath/android | src/org/sagemath/droid/models/gson/BaseReply.java | // Path: src/org/sagemath/droid/constants/ExecutionState.java
// public class ExecutionState {
// public static final int ERROR = 0x000300;
// public static final int IDLE = 0x000301;
// public static final int BUSY = 0x000302;
// public static final int DEAD = 0x000303;
// public static final int OK = 0x000304;
// }
//
// Path: src/org/sagemath/droid/constants/MessageType.java
// public class MessageType {
// public static final int ERROR = 0x000100;
// public static final int PYOUT = 0x000101;
// public static final int PYIN = 0x000102;
// public static final int STATUS = 0x000103;
// public static final int DISPLAY_DATA = 0x000104;
// public static final int STREAM = 0x000105;
// public static final int PYERR = 0x000106;
// public static final int EXECUTE_REQUEST = 0x000107;
// public static final int EXECUTE_REPLY = 0x000108;
// public static final int HTML_FILES = 0x000109;
// public static final int INTERACT_PREPARE = 0x000110;
// public static final int EXTENSION = 0x000111;
// public static final int TEXT_FILENAME = 0x000112;
// public static final int IMAGE_FILENAME = 0x000113;
// public static final int INTERACT = 0x000114;
// public static final int SAGE_CLEAR = 0x000115;
// }
| import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.sagemath.droid.constants.ExecutionState;
import org.sagemath.droid.constants.MessageType;
import org.sagemath.droid.deserializers.*; | }
public void setJsonData(String jsonData) {
this.jsonData = jsonData;
}
//---UTILITY METHODS---
public boolean isReplyTo(Request request) {
return (request != null) && getHeader().getSession().equals(request.getHeader().getSession());
}
public String toString() {
return gson.toJson(this);
}
public static BaseReply parse(String jsonString) throws Exception {
Gson gson = new GsonBuilder()
.registerTypeAdapter(BaseReply.class, new BaseReplyDeserializer())
.registerTypeAdapter(InteractReply.InteractContent.class, new InteractContentDeserializer())
.registerTypeAdapter(InteractReply.InteractData.class, new InteractDataDeserializer())
.registerTypeAdapter(InteractReply.SageInteract.class, new SageInteractDeserializer())
.registerTypeAdapter(Values.class, new ValueDeserializer())
.create();
//Return the appropriate BaseReply
BaseReply baseReply = gson.fromJson(jsonString, BaseReply.class);
reply = baseReply;
switch (baseReply.getMessageType()) { | // Path: src/org/sagemath/droid/constants/ExecutionState.java
// public class ExecutionState {
// public static final int ERROR = 0x000300;
// public static final int IDLE = 0x000301;
// public static final int BUSY = 0x000302;
// public static final int DEAD = 0x000303;
// public static final int OK = 0x000304;
// }
//
// Path: src/org/sagemath/droid/constants/MessageType.java
// public class MessageType {
// public static final int ERROR = 0x000100;
// public static final int PYOUT = 0x000101;
// public static final int PYIN = 0x000102;
// public static final int STATUS = 0x000103;
// public static final int DISPLAY_DATA = 0x000104;
// public static final int STREAM = 0x000105;
// public static final int PYERR = 0x000106;
// public static final int EXECUTE_REQUEST = 0x000107;
// public static final int EXECUTE_REPLY = 0x000108;
// public static final int HTML_FILES = 0x000109;
// public static final int INTERACT_PREPARE = 0x000110;
// public static final int EXTENSION = 0x000111;
// public static final int TEXT_FILENAME = 0x000112;
// public static final int IMAGE_FILENAME = 0x000113;
// public static final int INTERACT = 0x000114;
// public static final int SAGE_CLEAR = 0x000115;
// }
// Path: src/org/sagemath/droid/models/gson/BaseReply.java
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.sagemath.droid.constants.ExecutionState;
import org.sagemath.droid.constants.MessageType;
import org.sagemath.droid.deserializers.*;
}
public void setJsonData(String jsonData) {
this.jsonData = jsonData;
}
//---UTILITY METHODS---
public boolean isReplyTo(Request request) {
return (request != null) && getHeader().getSession().equals(request.getHeader().getSession());
}
public String toString() {
return gson.toJson(this);
}
public static BaseReply parse(String jsonString) throws Exception {
Gson gson = new GsonBuilder()
.registerTypeAdapter(BaseReply.class, new BaseReplyDeserializer())
.registerTypeAdapter(InteractReply.InteractContent.class, new InteractContentDeserializer())
.registerTypeAdapter(InteractReply.InteractData.class, new InteractDataDeserializer())
.registerTypeAdapter(InteractReply.SageInteract.class, new SageInteractDeserializer())
.registerTypeAdapter(Values.class, new ValueDeserializer())
.create();
//Return the appropriate BaseReply
BaseReply baseReply = gson.fromJson(jsonString, BaseReply.class);
reply = baseReply;
switch (baseReply.getMessageType()) { | case MessageType.PYIN: |
sagemath/android | src/org/sagemath/droid/models/gson/BaseReply.java | // Path: src/org/sagemath/droid/constants/ExecutionState.java
// public class ExecutionState {
// public static final int ERROR = 0x000300;
// public static final int IDLE = 0x000301;
// public static final int BUSY = 0x000302;
// public static final int DEAD = 0x000303;
// public static final int OK = 0x000304;
// }
//
// Path: src/org/sagemath/droid/constants/MessageType.java
// public class MessageType {
// public static final int ERROR = 0x000100;
// public static final int PYOUT = 0x000101;
// public static final int PYIN = 0x000102;
// public static final int STATUS = 0x000103;
// public static final int DISPLAY_DATA = 0x000104;
// public static final int STREAM = 0x000105;
// public static final int PYERR = 0x000106;
// public static final int EXECUTE_REQUEST = 0x000107;
// public static final int EXECUTE_REPLY = 0x000108;
// public static final int HTML_FILES = 0x000109;
// public static final int INTERACT_PREPARE = 0x000110;
// public static final int EXTENSION = 0x000111;
// public static final int TEXT_FILENAME = 0x000112;
// public static final int IMAGE_FILENAME = 0x000113;
// public static final int INTERACT = 0x000114;
// public static final int SAGE_CLEAR = 0x000115;
// }
| import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.sagemath.droid.constants.ExecutionState;
import org.sagemath.droid.constants.MessageType;
import org.sagemath.droid.deserializers.*; | StatusReply statusReply = gson.fromJson(jsonString, StatusReply.class);
saveStatus(statusReply);
return statusReply;
case MessageType.STREAM:
Log.i(TAG, "Returning Stream");
return gson.fromJson(jsonString, StreamReply.class);
case MessageType.PYERR:
Log.i(TAG, "Returning Pyerr");
return gson.fromJson(jsonString, PythonErrorReply.class);
case MessageType.EXECUTE_REPLY:
Log.i(TAG, "Returning execute reply");
return gson.fromJson(jsonString, SageExecuteReply.class);
case MessageType.INTERACT:
Log.i(TAG, "Returning Interact");
return gson.fromJson(jsonString, InteractReply.class);
case MessageType.SAGE_CLEAR:
Log.i(TAG, "Returning Sage Clear");
return gson.fromJson(jsonString, SageClearReply.class);
case MessageType.HTML_FILES:
Log.i(TAG, "Returning an HTML Reply");
return gson.fromJson(jsonString, HtmlReply.class);
case MessageType.IMAGE_FILENAME:
Log.i(TAG, "Returning Image Reply");
return gson.fromJson(jsonString, ImageReply.class);
default:
throw new Exception("Unknown Message Type");
}
}
private static void saveStatus(StatusReply statusReply) { | // Path: src/org/sagemath/droid/constants/ExecutionState.java
// public class ExecutionState {
// public static final int ERROR = 0x000300;
// public static final int IDLE = 0x000301;
// public static final int BUSY = 0x000302;
// public static final int DEAD = 0x000303;
// public static final int OK = 0x000304;
// }
//
// Path: src/org/sagemath/droid/constants/MessageType.java
// public class MessageType {
// public static final int ERROR = 0x000100;
// public static final int PYOUT = 0x000101;
// public static final int PYIN = 0x000102;
// public static final int STATUS = 0x000103;
// public static final int DISPLAY_DATA = 0x000104;
// public static final int STREAM = 0x000105;
// public static final int PYERR = 0x000106;
// public static final int EXECUTE_REQUEST = 0x000107;
// public static final int EXECUTE_REPLY = 0x000108;
// public static final int HTML_FILES = 0x000109;
// public static final int INTERACT_PREPARE = 0x000110;
// public static final int EXTENSION = 0x000111;
// public static final int TEXT_FILENAME = 0x000112;
// public static final int IMAGE_FILENAME = 0x000113;
// public static final int INTERACT = 0x000114;
// public static final int SAGE_CLEAR = 0x000115;
// }
// Path: src/org/sagemath/droid/models/gson/BaseReply.java
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.sagemath.droid.constants.ExecutionState;
import org.sagemath.droid.constants.MessageType;
import org.sagemath.droid.deserializers.*;
StatusReply statusReply = gson.fromJson(jsonString, StatusReply.class);
saveStatus(statusReply);
return statusReply;
case MessageType.STREAM:
Log.i(TAG, "Returning Stream");
return gson.fromJson(jsonString, StreamReply.class);
case MessageType.PYERR:
Log.i(TAG, "Returning Pyerr");
return gson.fromJson(jsonString, PythonErrorReply.class);
case MessageType.EXECUTE_REPLY:
Log.i(TAG, "Returning execute reply");
return gson.fromJson(jsonString, SageExecuteReply.class);
case MessageType.INTERACT:
Log.i(TAG, "Returning Interact");
return gson.fromJson(jsonString, InteractReply.class);
case MessageType.SAGE_CLEAR:
Log.i(TAG, "Returning Sage Clear");
return gson.fromJson(jsonString, SageClearReply.class);
case MessageType.HTML_FILES:
Log.i(TAG, "Returning an HTML Reply");
return gson.fromJson(jsonString, HtmlReply.class);
case MessageType.IMAGE_FILENAME:
Log.i(TAG, "Returning Image Reply");
return gson.fromJson(jsonString, ImageReply.class);
default:
throw new Exception("Unknown Message Type");
}
}
private static void saveStatus(StatusReply statusReply) { | if (statusReply.getContent().getExecutionState() == ExecutionState.DEAD) { |
sagemath/android | src/org/sagemath/droid/adapters/CellGroupsAdapter.java | // Path: src/org/sagemath/droid/models/database/Group.java
// public class Group implements Parcelable {
// private static final String TAG = "SageDroid:Groups";
//
// Long _id;
// String cellGroup;
//
// public Group() {
// }
//
// public Group(String group) {
// this.cellGroup = group;
// }
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long _id) {
// this._id = _id;
// }
//
// public String getCellGroup() {
// return cellGroup;
// }
//
// public void setCellGroup(String cellGroup) {
// this.cellGroup = cellGroup;
// }
//
// public String toString() {
// return "Group: " + cellGroup;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Group) {
// Group compare = (Group) o;
// return compare.getCellGroup().equals(cellGroup);
// } else {
// return false;
// }
// }
//
// private Group(Parcel in) {
// _id = in.readLong();
// cellGroup = in.readString();
// }
//
// public static final Creator<Group> CREATOR = new Creator<Group>() {
// @Override
// public Group createFromParcel(Parcel source) {
// return new Group(source);
// }
//
// @Override
// public Group[] newArray(int size) {
// return new Group[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeLong(_id);
// dest.writeString(cellGroup);
// }
// }
| import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import org.sagemath.droid.R;
import org.sagemath.droid.models.database.Group;
import java.util.List; | package org.sagemath.droid.adapters;
/**
* Adapter which is responsible for the Cell Groups
*
* @author Rasmi.Elasmar
* @author Ralf.Stephan
* @author Nikhil Peter Raj
*/
public class CellGroupsAdapter extends BaseAdapter {
private final Context context;
| // Path: src/org/sagemath/droid/models/database/Group.java
// public class Group implements Parcelable {
// private static final String TAG = "SageDroid:Groups";
//
// Long _id;
// String cellGroup;
//
// public Group() {
// }
//
// public Group(String group) {
// this.cellGroup = group;
// }
//
// public Long getId() {
// return _id;
// }
//
// public void setId(Long _id) {
// this._id = _id;
// }
//
// public String getCellGroup() {
// return cellGroup;
// }
//
// public void setCellGroup(String cellGroup) {
// this.cellGroup = cellGroup;
// }
//
// public String toString() {
// return "Group: " + cellGroup;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o instanceof Group) {
// Group compare = (Group) o;
// return compare.getCellGroup().equals(cellGroup);
// } else {
// return false;
// }
// }
//
// private Group(Parcel in) {
// _id = in.readLong();
// cellGroup = in.readString();
// }
//
// public static final Creator<Group> CREATOR = new Creator<Group>() {
// @Override
// public Group createFromParcel(Parcel source) {
// return new Group(source);
// }
//
// @Override
// public Group[] newArray(int size) {
// return new Group[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeLong(_id);
// dest.writeString(cellGroup);
// }
// }
// Path: src/org/sagemath/droid/adapters/CellGroupsAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import org.sagemath.droid.R;
import org.sagemath.droid.models.database.Group;
import java.util.List;
package org.sagemath.droid.adapters;
/**
* Adapter which is responsible for the Cell Groups
*
* @author Rasmi.Elasmar
* @author Ralf.Stephan
* @author Nikhil Peter Raj
*/
public class CellGroupsAdapter extends BaseAdapter {
private final Context context;
| private List<Group> groups; |
sagemath/android | src/org/sagemath/droid/fragments/HelpAboutFragment.java | // Path: libs/html-textview/src/main/java/org/sufficientlysecure/htmltextview/HtmlTextView.java
// public class HtmlTextView extends JellyBeanSpanFixTextView {
//
// public static final String TAG = "HtmlTextView";
// public static final boolean DEBUG = false;
//
// public HtmlTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public HtmlTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public HtmlTextView(Context context) {
// super(context);
// }
//
// /**
// * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
// *
// * @param is
// * @return
// */
// static private String convertStreamToString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
// return s.hasNext() ? s.next() : "";
// }
//
// /**
// * Loads HTML from a raw resource, i.e., a HTML file in res/raw/.
// * This allows translatable resource (e.g., res/raw-de/ for german).
// * The containing HTML is parsed to Android's Spannable format and then displayed.
// *
// * @param context
// * @param id for example: R.raw.help
// */
// public void setHtmlFromRawResource(Context context, int id, boolean useLocalDrawables) {
// // load html from html file from /res/raw
// InputStream inputStreamText = context.getResources().openRawResource(id);
//
// setHtmlFromString(convertStreamToString(inputStreamText), useLocalDrawables);
// }
//
// /**
// * Parses String containing HTML to Android's Spannable format and displays it in this TextView.
// *
// * @param html String containing HTML, for example: "<b>Hello world!</b>"
// */
// public void setHtmlFromString(String html, boolean useLocalDrawables) {
// Html.ImageGetter imgGetter;
// if (useLocalDrawables) {
// imgGetter = new LocalImageGetter(getContext());
// } else {
// imgGetter = new UrlImageGetter(this, getContext());
// }
// // this uses Android's Html class for basic parsing, and HtmlTagHandler
// setText(Html.fromHtml(html, imgGetter, new HtmlTagHandler()));
//
// // make links work
// setMovementMethod(LinkMovementMethod.getInstance());
//
// // no flickering when clicking textview for Android < 4, but overriders color...
// // text.setTextColor(getResources().getColor(android.R.color.secondary_text_dark_nodisable));
// }
// }
| import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.sagemath.droid.R;
import org.sufficientlysecure.htmltextview.HtmlTextView; | package org.sagemath.droid.fragments;
/**
* Fragment which displays the Help About page
* @author Nikhil Peter Raj
*/
public class HelpAboutFragment extends Fragment {
private static final String TAG = "SageDroid:HelpAboutFragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_help_about, container, false);
TextView versionText = (TextView) view.findViewById(R.id.helpAboutVersion);
TextView gitIconText = (TextView) view.findViewById(R.id.gitIconText); | // Path: libs/html-textview/src/main/java/org/sufficientlysecure/htmltextview/HtmlTextView.java
// public class HtmlTextView extends JellyBeanSpanFixTextView {
//
// public static final String TAG = "HtmlTextView";
// public static final boolean DEBUG = false;
//
// public HtmlTextView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// public HtmlTextView(Context context, AttributeSet attrs) {
// super(context, attrs);
// }
//
// public HtmlTextView(Context context) {
// super(context);
// }
//
// /**
// * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
// *
// * @param is
// * @return
// */
// static private String convertStreamToString(java.io.InputStream is) {
// java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
// return s.hasNext() ? s.next() : "";
// }
//
// /**
// * Loads HTML from a raw resource, i.e., a HTML file in res/raw/.
// * This allows translatable resource (e.g., res/raw-de/ for german).
// * The containing HTML is parsed to Android's Spannable format and then displayed.
// *
// * @param context
// * @param id for example: R.raw.help
// */
// public void setHtmlFromRawResource(Context context, int id, boolean useLocalDrawables) {
// // load html from html file from /res/raw
// InputStream inputStreamText = context.getResources().openRawResource(id);
//
// setHtmlFromString(convertStreamToString(inputStreamText), useLocalDrawables);
// }
//
// /**
// * Parses String containing HTML to Android's Spannable format and displays it in this TextView.
// *
// * @param html String containing HTML, for example: "<b>Hello world!</b>"
// */
// public void setHtmlFromString(String html, boolean useLocalDrawables) {
// Html.ImageGetter imgGetter;
// if (useLocalDrawables) {
// imgGetter = new LocalImageGetter(getContext());
// } else {
// imgGetter = new UrlImageGetter(this, getContext());
// }
// // this uses Android's Html class for basic parsing, and HtmlTagHandler
// setText(Html.fromHtml(html, imgGetter, new HtmlTagHandler()));
//
// // make links work
// setMovementMethod(LinkMovementMethod.getInstance());
//
// // no flickering when clicking textview for Android < 4, but overriders color...
// // text.setTextColor(getResources().getColor(android.R.color.secondary_text_dark_nodisable));
// }
// }
// Path: src/org/sagemath/droid/fragments/HelpAboutFragment.java
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.sagemath.droid.R;
import org.sufficientlysecure.htmltextview.HtmlTextView;
package org.sagemath.droid.fragments;
/**
* Fragment which displays the Help About page
* @author Nikhil Peter Raj
*/
public class HelpAboutFragment extends Fragment {
private static final String TAG = "SageDroid:HelpAboutFragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_help_about, container, false);
TextView versionText = (TextView) view.findViewById(R.id.helpAboutVersion);
TextView gitIconText = (TextView) view.findViewById(R.id.gitIconText); | HtmlTextView gitLinkText = (HtmlTextView) view.findViewById(R.id.gitLinkText); |
pentaho/big-data-plugin | s3-vfs/src/test/java/org/pentaho/s3n/vfs/S3NFileSystemTest.java | // Path: s3-vfs/src/test/java/org/pentaho/s3common/S3CommonFileSystemTestUtil.java
// public class S3CommonFileSystemTestUtil {
//
// public static S3CommonFileSystem stubRegionUnSet( S3CommonFileSystem fileSystem ) {
// S3CommonFileSystem fileSystemSpy = Mockito.spy( fileSystem );
// doReturn(false).when(fileSystemSpy).isRegionSet();
// return fileSystemSpy;
// }
// }
| import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.UserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.pentaho.s3.vfs.S3FileName;
import org.pentaho.s3.vfs.S3FileNameTest;
import org.pentaho.s3common.S3CommonFileSystemTestUtil;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | FileType.FOLDER );
fileSystem = new S3NFileSystem( fileName, new FileSystemOptions() );
}
@Test
public void testCreateFile() throws Exception {
assertNotNull( fileSystem.createFile( new S3FileName( "s3n", "bucketName", "/bucketName/key", FileType.FILE ) ) );
}
@Test
public void testGetS3Service() throws Exception {
assertNotNull( fileSystem.getS3Client() );
FileSystemOptions options = new FileSystemOptions();
UserAuthenticator authenticator = mock( UserAuthenticator.class );
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator( options, authenticator );
fileSystem = new S3NFileSystem( fileName, options );
assertNotNull( fileSystem.getS3Client() );
}
@Test
public void getS3ClientWithDefaultRegion() {
FileSystemOptions options = new FileSystemOptions();
try ( MockedStatic<Regions> regionsMockedStatic = Mockito.mockStatic( Regions.class ) ) {
regionsMockedStatic.when( Regions::getCurrentRegion ).thenReturn( null );
//Not under an EC2 instance - getCurrentRegion returns null
when( Regions.getCurrentRegion() ).thenReturn( null );
fileSystem = new S3NFileSystem( fileName, options ); | // Path: s3-vfs/src/test/java/org/pentaho/s3common/S3CommonFileSystemTestUtil.java
// public class S3CommonFileSystemTestUtil {
//
// public static S3CommonFileSystem stubRegionUnSet( S3CommonFileSystem fileSystem ) {
// S3CommonFileSystem fileSystemSpy = Mockito.spy( fileSystem );
// doReturn(false).when(fileSystemSpy).isRegionSet();
// return fileSystemSpy;
// }
// }
// Path: s3-vfs/src/test/java/org/pentaho/s3n/vfs/S3NFileSystemTest.java
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.UserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.pentaho.s3.vfs.S3FileName;
import org.pentaho.s3.vfs.S3FileNameTest;
import org.pentaho.s3common.S3CommonFileSystemTestUtil;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
FileType.FOLDER );
fileSystem = new S3NFileSystem( fileName, new FileSystemOptions() );
}
@Test
public void testCreateFile() throws Exception {
assertNotNull( fileSystem.createFile( new S3FileName( "s3n", "bucketName", "/bucketName/key", FileType.FILE ) ) );
}
@Test
public void testGetS3Service() throws Exception {
assertNotNull( fileSystem.getS3Client() );
FileSystemOptions options = new FileSystemOptions();
UserAuthenticator authenticator = mock( UserAuthenticator.class );
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator( options, authenticator );
fileSystem = new S3NFileSystem( fileName, options );
assertNotNull( fileSystem.getS3Client() );
}
@Test
public void getS3ClientWithDefaultRegion() {
FileSystemOptions options = new FileSystemOptions();
try ( MockedStatic<Regions> regionsMockedStatic = Mockito.mockStatic( Regions.class ) ) {
regionsMockedStatic.when( Regions::getCurrentRegion ).thenReturn( null );
//Not under an EC2 instance - getCurrentRegion returns null
when( Regions.getCurrentRegion() ).thenReturn( null );
fileSystem = new S3NFileSystem( fileName, options ); | fileSystem = (S3NFileSystem) S3CommonFileSystemTestUtil.stubRegionUnSet( fileSystem ); |
pentaho/big-data-plugin | legacy-amazon/src/main/java/org/pentaho/amazon/AbstractAmazonJobExecutor.java | // Path: legacy-amazon/src/main/java/org/pentaho/amazon/client/ClientFactoriesManager.java
// public class ClientFactoriesManager {
//
// private Map<ClientType, AbstractClientFactory> clientFactoryMap;
// private static ClientFactoriesManager instance;
//
// private ClientFactoriesManager() {
// clientFactoryMap = new HashMap<>();
// clientFactoryMap.put( ClientType.S3, new S3ClientFactory() );
// clientFactoryMap.put( ClientType.EMR, new EmrClientFactory() );
// clientFactoryMap.put( ClientType.AIM, new AimClientFactory() );
// clientFactoryMap.put( ClientType.PRICING, new PricingClientFactory() );
// }
//
// public static ClientFactoriesManager getInstance() {
// if ( instance == null ) {
// instance = new ClientFactoriesManager();
// }
// return instance;
// }
//
// public <T> T createClient( String accessKey, String secretKey, String sessionToken, String region, ClientType clientType ) {
// AbstractClientFactory clientFactory = getClientFactory( clientType );
// T amazonClient = (T) clientFactory.createClient( accessKey, secretKey, sessionToken, region );
// return amazonClient;
// }
//
// private AbstractClientFactory getClientFactory( ClientType clientType ) {
// if ( clientFactoryMap.containsKey( clientType ) ) {
// return clientFactoryMap.get( clientType );
// }
// return null;
// }
// }
| import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.auth.StaticUserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.pentaho.amazon.client.ClientFactoriesManager;
import org.pentaho.amazon.client.ClientType;
import org.pentaho.amazon.client.api.EmrClient;
import org.pentaho.amazon.client.api.S3Client;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.logging.log4j.Log4jKettleLayout;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.platform.api.util.LogUtil;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map; | }
public String buildFilename( String filename ) {
filename = environmentSubstitute( filename );
return filename;
}
public abstract File createStagingFile() throws IOException, KettleException;
public abstract String getStepBootstrapActions();
public abstract String getMainClass() throws Exception;
public abstract String getStepType();
private void runNewJobFlow( String stagingS3FileUrl, String stagingS3BucketUrl ) throws Exception {
emrClient
.runJobFlow( stagingS3FileUrl, stagingS3BucketUrl, getStepType(), getMainClass(), getStepBootstrapActions(),
this );
}
private void addStepToExistingJobFlow( String stagingS3FileUrl, String stagingS3BucketUrl ) throws Exception {
emrClient.addStepToExistingJobFlow( stagingS3FileUrl, stagingS3BucketUrl, getStepType(), getMainClass(), this );
}
private void logError( String stagingBucketName, String stepId ) {
logError( s3Client.readStepLogsFromS3( stagingBucketName, hadoopJobFlowId, stepId ) );
}
private void initAmazonClients() { | // Path: legacy-amazon/src/main/java/org/pentaho/amazon/client/ClientFactoriesManager.java
// public class ClientFactoriesManager {
//
// private Map<ClientType, AbstractClientFactory> clientFactoryMap;
// private static ClientFactoriesManager instance;
//
// private ClientFactoriesManager() {
// clientFactoryMap = new HashMap<>();
// clientFactoryMap.put( ClientType.S3, new S3ClientFactory() );
// clientFactoryMap.put( ClientType.EMR, new EmrClientFactory() );
// clientFactoryMap.put( ClientType.AIM, new AimClientFactory() );
// clientFactoryMap.put( ClientType.PRICING, new PricingClientFactory() );
// }
//
// public static ClientFactoriesManager getInstance() {
// if ( instance == null ) {
// instance = new ClientFactoriesManager();
// }
// return instance;
// }
//
// public <T> T createClient( String accessKey, String secretKey, String sessionToken, String region, ClientType clientType ) {
// AbstractClientFactory clientFactory = getClientFactory( clientType );
// T amazonClient = (T) clientFactory.createClient( accessKey, secretKey, sessionToken, region );
// return amazonClient;
// }
//
// private AbstractClientFactory getClientFactory( ClientType clientType ) {
// if ( clientFactoryMap.containsKey( clientType ) ) {
// return clientFactoryMap.get( clientType );
// }
// return null;
// }
// }
// Path: legacy-amazon/src/main/java/org/pentaho/amazon/AbstractAmazonJobExecutor.java
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.auth.StaticUserAuthenticator;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.pentaho.amazon.client.ClientFactoriesManager;
import org.pentaho.amazon.client.ClientType;
import org.pentaho.amazon.client.api.EmrClient;
import org.pentaho.amazon.client.api.S3Client;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.logging.log4j.Log4jKettleLayout;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.platform.api.util.LogUtil;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
}
public String buildFilename( String filename ) {
filename = environmentSubstitute( filename );
return filename;
}
public abstract File createStagingFile() throws IOException, KettleException;
public abstract String getStepBootstrapActions();
public abstract String getMainClass() throws Exception;
public abstract String getStepType();
private void runNewJobFlow( String stagingS3FileUrl, String stagingS3BucketUrl ) throws Exception {
emrClient
.runJobFlow( stagingS3FileUrl, stagingS3BucketUrl, getStepType(), getMainClass(), getStepBootstrapActions(),
this );
}
private void addStepToExistingJobFlow( String stagingS3FileUrl, String stagingS3BucketUrl ) throws Exception {
emrClient.addStepToExistingJobFlow( stagingS3FileUrl, stagingS3BucketUrl, getStepType(), getMainClass(), this );
}
private void logError( String stagingBucketName, String stepId ) {
logError( s3Client.readStepLogsFromS3( stagingBucketName, hadoopJobFlowId, stepId ) );
}
private void initAmazonClients() { | ClientFactoriesManager manager = ClientFactoriesManager.getInstance(); |
pentaho/big-data-plugin | kettle-plugins/sqoop/src/main/java/org/pentaho/big/data/kettle/plugins/sqoop/AbstractSqoopJobEntry.java | // Path: kettle-plugins/common/job/src/main/java/org/pentaho/big/data/kettle/plugins/job/JobEntryUtils.java
// public class JobEntryUtils {
//
// /**
// * @return {@code true} if {@link Boolean#parseBoolean(String)} returns {@code true} for
// * {@link #isBlockingExecution()}
// */
// /**
// * Determine if the string equates to {@link Boolean#TRUE} after performing a variable substitution.
// *
// * @param s
// * String-encoded boolean value or variable expression
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Boolean#parseBoolean(String) Boolean.parseBoolean(s)} after substitution
// */
// public static boolean asBoolean( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return Boolean.parseBoolean( value );
// }
//
// /**
// * Parse the string as a {@link Long} after variable substitution.
// *
// * @param s
// * String-encoded {@link Long} value or variable expression that should resolve to a {@link Long} value
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Long#parseLong(String, int) Long.parseLong(s, 10)} after substitution
// */
// public static Long asLong( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return value == null ? null : Long.valueOf( value, 10 );
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Filter;
import org.pentaho.big.data.kettle.plugins.job.AbstractJobEntry;
import org.pentaho.big.data.kettle.plugins.job.JobEntryMode;
import org.pentaho.big.data.kettle.plugins.job.JobEntryUtils;
import org.pentaho.big.data.kettle.plugins.job.PropertyEntry;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseInterface;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.log4j.KettleLogChannelAppender;
import org.pentaho.di.core.logging.log4j.Log4jKettleLayout;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.hadoop.shim.api.HadoopClientServices;
import org.pentaho.hadoop.shim.api.cluster.NamedCluster;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterService;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterServiceLocator;
import org.pentaho.hadoop.shim.api.core.ShimIdentifierInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.pentaho.platform.api.util.LogUtil;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.runtime.test.RuntimeTester;
import org.pentaho.runtime.test.action.RuntimeTestActionService;
import org.w3c.dom.Node;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors; | Logger sqoopLogger = LogManager.getLogger( LOGS_TO_MONITOR[0] );
LogUtil.removeAppender( sqoopToKettleAppender, sqoopLogger );
sqoopToKettleAppender = null;
}
if ( stdErrProxy != null ) {
System.setErr( stdErrProxy.getWrappedStream() );
stdErrProxy = null;
}
} catch ( Exception ex ) {
logError( getString( "ErrorDetachingLogging" ) );
logDebug( Throwables.getStackTraceAsString( ex ) );
}
}
/**
* Validate any configuration option we use directly that could be invalid at runtime.
*
* @param config
* Configuration to validate
* @return List of warning messages for any invalid configuration options we use directly in this job entry.
*/
@Override
public List<String> getValidationWarnings( SqoopConfig config ) {
List<String> warnings = new ArrayList<String>();
if ( StringUtil.isEmpty( config.getConnect() ) ) {
warnings.add( getString( "ValidationError.Connect.Message", config.getConnect() ) );
}
try { | // Path: kettle-plugins/common/job/src/main/java/org/pentaho/big/data/kettle/plugins/job/JobEntryUtils.java
// public class JobEntryUtils {
//
// /**
// * @return {@code true} if {@link Boolean#parseBoolean(String)} returns {@code true} for
// * {@link #isBlockingExecution()}
// */
// /**
// * Determine if the string equates to {@link Boolean#TRUE} after performing a variable substitution.
// *
// * @param s
// * String-encoded boolean value or variable expression
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Boolean#parseBoolean(String) Boolean.parseBoolean(s)} after substitution
// */
// public static boolean asBoolean( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return Boolean.parseBoolean( value );
// }
//
// /**
// * Parse the string as a {@link Long} after variable substitution.
// *
// * @param s
// * String-encoded {@link Long} value or variable expression that should resolve to a {@link Long} value
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Long#parseLong(String, int) Long.parseLong(s, 10)} after substitution
// */
// public static Long asLong( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return value == null ? null : Long.valueOf( value, 10 );
// }
// }
// Path: kettle-plugins/sqoop/src/main/java/org/pentaho/big/data/kettle/plugins/sqoop/AbstractSqoopJobEntry.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Filter;
import org.pentaho.big.data.kettle.plugins.job.AbstractJobEntry;
import org.pentaho.big.data.kettle.plugins.job.JobEntryMode;
import org.pentaho.big.data.kettle.plugins.job.JobEntryUtils;
import org.pentaho.big.data.kettle.plugins.job.PropertyEntry;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.database.DatabaseInterface;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.log4j.KettleLogChannelAppender;
import org.pentaho.di.core.logging.log4j.Log4jKettleLayout;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.hadoop.shim.api.HadoopClientServices;
import org.pentaho.hadoop.shim.api.cluster.NamedCluster;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterService;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterServiceLocator;
import org.pentaho.hadoop.shim.api.core.ShimIdentifierInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.pentaho.platform.api.util.LogUtil;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.runtime.test.RuntimeTester;
import org.pentaho.runtime.test.action.RuntimeTestActionService;
import org.w3c.dom.Node;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
Logger sqoopLogger = LogManager.getLogger( LOGS_TO_MONITOR[0] );
LogUtil.removeAppender( sqoopToKettleAppender, sqoopLogger );
sqoopToKettleAppender = null;
}
if ( stdErrProxy != null ) {
System.setErr( stdErrProxy.getWrappedStream() );
stdErrProxy = null;
}
} catch ( Exception ex ) {
logError( getString( "ErrorDetachingLogging" ) );
logDebug( Throwables.getStackTraceAsString( ex ) );
}
}
/**
* Validate any configuration option we use directly that could be invalid at runtime.
*
* @param config
* Configuration to validate
* @return List of warning messages for any invalid configuration options we use directly in this job entry.
*/
@Override
public List<String> getValidationWarnings( SqoopConfig config ) {
List<String> warnings = new ArrayList<String>();
if ( StringUtil.isEmpty( config.getConnect() ) ) {
warnings.add( getString( "ValidationError.Connect.Message", config.getConnect() ) );
}
try { | JobEntryUtils.asLong( config.getBlockingPollingInterval(), variables ); |
pentaho/big-data-plugin | kettle-plugins/oozie/src/main/java/org/pentaho/big/data/kettle/plugins/oozie/OozieJobExecutorJobEntry.java | // Path: kettle-plugins/common/job/src/main/java/org/pentaho/big/data/kettle/plugins/job/JobEntryUtils.java
// public class JobEntryUtils {
//
// /**
// * @return {@code true} if {@link Boolean#parseBoolean(String)} returns {@code true} for
// * {@link #isBlockingExecution()}
// */
// /**
// * Determine if the string equates to {@link Boolean#TRUE} after performing a variable substitution.
// *
// * @param s
// * String-encoded boolean value or variable expression
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Boolean#parseBoolean(String) Boolean.parseBoolean(s)} after substitution
// */
// public static boolean asBoolean( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return Boolean.parseBoolean( value );
// }
//
// /**
// * Parse the string as a {@link Long} after variable substitution.
// *
// * @param s
// * String-encoded {@link Long} value or variable expression that should resolve to a {@link Long} value
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Long#parseLong(String, int) Long.parseLong(s, 10)} after substitution
// */
// public static Long asLong( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return value == null ? null : Long.valueOf( value, 10 );
// }
// }
| import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang.StringUtils;
import org.pentaho.big.data.kettle.plugins.job.JobEntryUtils;
import org.pentaho.hadoop.shim.api.HadoopClientServices;
import org.pentaho.hadoop.shim.api.HadoopClientServicesException;
import org.pentaho.hadoop.shim.api.cluster.NamedCluster;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterService;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterServiceLocator;
import org.pentaho.hadoop.shim.api.cluster.ClusterInitializationException;
import org.pentaho.big.data.kettle.plugins.job.AbstractJobEntry;
import org.pentaho.big.data.kettle.plugins.job.JobEntryMode;
import org.pentaho.big.data.kettle.plugins.job.PropertyEntry;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.annotations.JobEntry;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.hadoop.shim.api.oozie.OozieJobInfo;
import org.pentaho.hadoop.shim.api.oozie.OozieServiceException;
import org.pentaho.metastore.api.exceptions.MetaStoreException;
import org.pentaho.runtime.test.RuntimeTester;
import org.pentaho.runtime.test.action.RuntimeTestActionService; | return new OozieJobExecutorConfig();
}
public List<String> getValidationWarnings( OozieJobExecutorConfig config, boolean checkOozieConnection ) {
List<String> messages = new ArrayList<>();
// verify there is a job name
if ( StringUtil.isEmpty( config.getJobEntryName() ) ) {
messages.add( BaseMessages.getString( OozieJobExecutorJobEntry.class, "ValidationMessages.Missing.JobName" ) );
}
NamedCluster nc = null;
try {
nc = getNamedCluster( config );
} catch ( MetaStoreException e ) {
messages
.add( BaseMessages.getString( OozieJobExecutorJobEntry.class, VALIDATION_MESSAGES_MISSING_CONFIGURATION ) );
}
if ( null == nc || nc.getName().equals( "" ) || nc.getShimIdentifier().equals( "" ) ) {
messages.add(
BaseMessages.getString( OozieJobExecutorJobEntry.class, "ValidationMessages.Missing.NamedCluster", config.getClusterName() ) );
return messages;
}
verifyOozieUrl( config, checkOozieConnection, messages, nc );
checkOozieConnection( config, checkOozieConnection, messages );
verifyJobConfiguration( config, checkOozieConnection, messages );
boolean pollingIntervalValid = false;
try { | // Path: kettle-plugins/common/job/src/main/java/org/pentaho/big/data/kettle/plugins/job/JobEntryUtils.java
// public class JobEntryUtils {
//
// /**
// * @return {@code true} if {@link Boolean#parseBoolean(String)} returns {@code true} for
// * {@link #isBlockingExecution()}
// */
// /**
// * Determine if the string equates to {@link Boolean#TRUE} after performing a variable substitution.
// *
// * @param s
// * String-encoded boolean value or variable expression
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Boolean#parseBoolean(String) Boolean.parseBoolean(s)} after substitution
// */
// public static boolean asBoolean( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return Boolean.parseBoolean( value );
// }
//
// /**
// * Parse the string as a {@link Long} after variable substitution.
// *
// * @param s
// * String-encoded {@link Long} value or variable expression that should resolve to a {@link Long} value
// * @param variableSpace
// * Context for variables so we can substitute {@code s}
// * @return the value returned by {@link Long#parseLong(String, int) Long.parseLong(s, 10)} after substitution
// */
// public static Long asLong( String s, VariableSpace variableSpace ) {
// String value = variableSpace.environmentSubstitute( s );
// return value == null ? null : Long.valueOf( value, 10 );
// }
// }
// Path: kettle-plugins/oozie/src/main/java/org/pentaho/big/data/kettle/plugins/oozie/OozieJobExecutorJobEntry.java
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang.StringUtils;
import org.pentaho.big.data.kettle.plugins.job.JobEntryUtils;
import org.pentaho.hadoop.shim.api.HadoopClientServices;
import org.pentaho.hadoop.shim.api.HadoopClientServicesException;
import org.pentaho.hadoop.shim.api.cluster.NamedCluster;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterService;
import org.pentaho.hadoop.shim.api.cluster.NamedClusterServiceLocator;
import org.pentaho.hadoop.shim.api.cluster.ClusterInitializationException;
import org.pentaho.big.data.kettle.plugins.job.AbstractJobEntry;
import org.pentaho.big.data.kettle.plugins.job.JobEntryMode;
import org.pentaho.big.data.kettle.plugins.job.PropertyEntry;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.annotations.JobEntry;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.hadoop.shim.api.oozie.OozieJobInfo;
import org.pentaho.hadoop.shim.api.oozie.OozieServiceException;
import org.pentaho.metastore.api.exceptions.MetaStoreException;
import org.pentaho.runtime.test.RuntimeTester;
import org.pentaho.runtime.test.action.RuntimeTestActionService;
return new OozieJobExecutorConfig();
}
public List<String> getValidationWarnings( OozieJobExecutorConfig config, boolean checkOozieConnection ) {
List<String> messages = new ArrayList<>();
// verify there is a job name
if ( StringUtil.isEmpty( config.getJobEntryName() ) ) {
messages.add( BaseMessages.getString( OozieJobExecutorJobEntry.class, "ValidationMessages.Missing.JobName" ) );
}
NamedCluster nc = null;
try {
nc = getNamedCluster( config );
} catch ( MetaStoreException e ) {
messages
.add( BaseMessages.getString( OozieJobExecutorJobEntry.class, VALIDATION_MESSAGES_MISSING_CONFIGURATION ) );
}
if ( null == nc || nc.getName().equals( "" ) || nc.getShimIdentifier().equals( "" ) ) {
messages.add(
BaseMessages.getString( OozieJobExecutorJobEntry.class, "ValidationMessages.Missing.NamedCluster", config.getClusterName() ) );
return messages;
}
verifyOozieUrl( config, checkOozieConnection, messages, nc );
checkOozieConnection( config, checkOozieConnection, messages );
verifyJobConfiguration( config, checkOozieConnection, messages );
boolean pollingIntervalValid = false;
try { | long pollingInterval = JobEntryUtils.asLong( config.getBlockingPollingInterval(), variables ); |
montimaj/Remouse | app/src/main/java/project/android/CustomAdapter.java | // Path: app/src/main/java/project/android/net/ServerInfo.java
// public class ServerInfo {
// private byte[] mServerPubKey;
// private String mServerInfo;
// private String mAddress;
// private String mPairingKey;
// private boolean mStopFlag;
//
// static final int SERVER_INFO_LENGTH = 600;
//
// /**
// * Constructor.
// * Initializes this <code>ServerInfo</code>.
// *
// * @param publicKey public key of the server.
// * @param serverInfo canonical hostname of the server.
// */
// public ServerInfo(byte[] publicKey, String serverInfo) {
// mServerPubKey = publicKey;
// mServerInfo = serverInfo;
// mStopFlag = false;
// }
//
// /**
// * Compares two <code>ServerInfo</code> objects.
// *
// * @param obj the object to be compared.
// * @return <code>true</code>, if the two objects are equal, <br/>
// * <code>false</code>, otherwise.
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// ServerInfo other = (ServerInfo) obj;
// return mAddress.equals(other.mAddress);
// }
//
// /**
// * Sets the IPv4 server address.
// * @param address IPv4 server address.
// */
// void setServerAddress(String address) { mAddress = address; }
//
// /**
// * Sets the pairing key used during client-server authentication.
// * @param pairingKey the pairing key.
// */
// public void setPairingKey(String pairingKey) { mPairingKey = pairingKey; }
//
// /**
// * Returns the status of the server.
// * @return server status.
// */
// boolean getStopFlag() { return mStopFlag; }
//
// /**
// * Returns the server public key.
// * @return server public key.
// */
// byte[] getServerPubKey() { return mServerPubKey; }
//
// /**
// * Returns the canonical host name of the server.
// * @return the canonical host name.
// */
// public String getServerInfo() { return mServerInfo; }
//
// /**
// * Returns the IPv4 address of the server.
// * @return the IPv4 server address.
// */
// public String getAddress() { return mAddress; }
//
// /**
// * Returns the pairing key used during client-server authentication.
// * @return the pairing key.
// */
// String getPairingKey() { return mPairingKey; }
// }
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import project.android.net.ServerInfo;
import static project.android.ConnectionFragment.sConnectionAlive; | * position in the data set.
*
* @param position the position of the item within the adapter's data
* set of the item whose view is required.
* @param convertView The old view to reuse, if possible.
* @param parent The parent that this view will eventually be attached to.
* @return A <code>View</code> corresponding to the data at the specified
* position.
*/
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
convertView = layoutInflater.inflate(R.layout.local_devices, parent, false);
viewHolder = new ViewHolder();
viewHolder.mTextView = (TextView) convertView.findViewById(R.id.code);
viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.connectIcon);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
ArrayList<ServerInfo> serverList = mConnectionFragment.getNetworkList();
if(!serverList.isEmpty()) {
ServerInfo serverInfo = serverList.get(position);
viewHolder.mTextView.setText(serverInfo.getServerInfo() + " (" + serverInfo.getAddress() + ")"); | // Path: app/src/main/java/project/android/net/ServerInfo.java
// public class ServerInfo {
// private byte[] mServerPubKey;
// private String mServerInfo;
// private String mAddress;
// private String mPairingKey;
// private boolean mStopFlag;
//
// static final int SERVER_INFO_LENGTH = 600;
//
// /**
// * Constructor.
// * Initializes this <code>ServerInfo</code>.
// *
// * @param publicKey public key of the server.
// * @param serverInfo canonical hostname of the server.
// */
// public ServerInfo(byte[] publicKey, String serverInfo) {
// mServerPubKey = publicKey;
// mServerInfo = serverInfo;
// mStopFlag = false;
// }
//
// /**
// * Compares two <code>ServerInfo</code> objects.
// *
// * @param obj the object to be compared.
// * @return <code>true</code>, if the two objects are equal, <br/>
// * <code>false</code>, otherwise.
// */
// @Override
// public boolean equals(Object obj) {
// if (this == obj) return true;
// if (obj == null) return false;
// if (getClass() != obj.getClass()) return false;
// ServerInfo other = (ServerInfo) obj;
// return mAddress.equals(other.mAddress);
// }
//
// /**
// * Sets the IPv4 server address.
// * @param address IPv4 server address.
// */
// void setServerAddress(String address) { mAddress = address; }
//
// /**
// * Sets the pairing key used during client-server authentication.
// * @param pairingKey the pairing key.
// */
// public void setPairingKey(String pairingKey) { mPairingKey = pairingKey; }
//
// /**
// * Returns the status of the server.
// * @return server status.
// */
// boolean getStopFlag() { return mStopFlag; }
//
// /**
// * Returns the server public key.
// * @return server public key.
// */
// byte[] getServerPubKey() { return mServerPubKey; }
//
// /**
// * Returns the canonical host name of the server.
// * @return the canonical host name.
// */
// public String getServerInfo() { return mServerInfo; }
//
// /**
// * Returns the IPv4 address of the server.
// * @return the IPv4 server address.
// */
// public String getAddress() { return mAddress; }
//
// /**
// * Returns the pairing key used during client-server authentication.
// * @return the pairing key.
// */
// String getPairingKey() { return mPairingKey; }
// }
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
// Path: app/src/main/java/project/android/CustomAdapter.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import project.android.net.ServerInfo;
import static project.android.ConnectionFragment.sConnectionAlive;
* position in the data set.
*
* @param position the position of the item within the adapter's data
* set of the item whose view is required.
* @param convertView The old view to reuse, if possible.
* @param parent The parent that this view will eventually be attached to.
* @return A <code>View</code> corresponding to the data at the specified
* position.
*/
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
convertView = layoutInflater.inflate(R.layout.local_devices, parent, false);
viewHolder = new ViewHolder();
viewHolder.mTextView = (TextView) convertView.findViewById(R.id.code);
viewHolder.mImageView = (ImageView) convertView.findViewById(R.id.connectIcon);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
ArrayList<ServerInfo> serverList = mConnectionFragment.getNetworkList();
if(!serverList.isEmpty()) {
ServerInfo serverInfo = serverList.get(position);
viewHolder.mTextView.setText(serverInfo.getServerInfo() + " (" + serverInfo.getAddress() + ")"); | if(sConnectionAlive.get(serverInfo.getAddress())) { |
montimaj/Remouse | app/src/main/java/project/android/KeyboardFragment.java | // Path: app/src/main/java/project/android/net/KeyboardThread.java
// public class KeyboardThread implements Runnable {
//
// private boolean mStopFlag;
// private LinkedBlockingQueue<Pair<String, Boolean>> mBuffer;
//
// private static final long POLL_TIMEOUT = 100;
// private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
//
// /**
// * Constructor.
// *
// * Initializes this thread.
// */
// public KeyboardThread() {
// mStopFlag = false;
// mBuffer = new LinkedBlockingQueue<>();
// }
//
// /**
// * Inserts keyboard data to the buffer.
// *
// * This data is sent to the server by this <code>KeyboardThread</code>.
// *
// * @param data the data to be sent.
// * @param isSpecialKey <code>true</code>, if <code>data</code> represents
// * special key, <br/>
// * <code>false</code>, otherwise.
// */
// public void addToBuffer(String data, boolean isSpecialKey) {
// try {
// mBuffer.put(Pair.create(data, isSpecialKey));
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
//
// /**
// * Sets stop flag.
// *
// * Used to exit from the {@link #run()} method.
// */
// public void setStopFlag() { mStopFlag = true; }
//
// /**
// * Performs the sending of keyboard data in the buffer to the server.
// *
// * <p>
// * It checks if data is available in the buffer.
// * <ul>
// * <li>If available, it sends the data.</li>
// * <li>Otherwise, it waits for the data to be available.</li>
// * </ul>
// * </p>
// */
// @Override
// public void run() {
// while(!mStopFlag) {
// try {
// Pair<String, Boolean> data = mBuffer.poll(POLL_TIMEOUT, TIME_UNIT);
// if(data != null) {
// if (data.second) {
// sSecuredClient.sendData(data.first);
// } else sSecuredClient.sendData("Key", data.first);
// // Log.d("Keyboard sent", data.first + "__>" + data.first.length());
// }
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
// }
// }
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
| import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import project.android.net.KeyboardThread;
import static project.android.ConnectionFragment.sConnectionAlive; | package project.android;
/**
* Class representing the <code>Fragment</code> for providing the
* GUI frontend for the keyboard module.
*
* <p>
* The following keyboard features are provided:
* <ul>
* <li>Predictive text input.</li>
* <li>Auto-correct feature.</li>
* <li>Hide sensitive text.</li>
* <li>Support for special keys like Ctrl, Alt etc. </li>
* </ul>
* </p>
*
* @see project.android.net.KeyboardThread
*/
public class KeyboardFragment extends Fragment implements View.OnKeyListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener, TextWatcher {
private String mLastInput;
private InputMethodManager mInput;
private String mLastWord; | // Path: app/src/main/java/project/android/net/KeyboardThread.java
// public class KeyboardThread implements Runnable {
//
// private boolean mStopFlag;
// private LinkedBlockingQueue<Pair<String, Boolean>> mBuffer;
//
// private static final long POLL_TIMEOUT = 100;
// private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
//
// /**
// * Constructor.
// *
// * Initializes this thread.
// */
// public KeyboardThread() {
// mStopFlag = false;
// mBuffer = new LinkedBlockingQueue<>();
// }
//
// /**
// * Inserts keyboard data to the buffer.
// *
// * This data is sent to the server by this <code>KeyboardThread</code>.
// *
// * @param data the data to be sent.
// * @param isSpecialKey <code>true</code>, if <code>data</code> represents
// * special key, <br/>
// * <code>false</code>, otherwise.
// */
// public void addToBuffer(String data, boolean isSpecialKey) {
// try {
// mBuffer.put(Pair.create(data, isSpecialKey));
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
//
// /**
// * Sets stop flag.
// *
// * Used to exit from the {@link #run()} method.
// */
// public void setStopFlag() { mStopFlag = true; }
//
// /**
// * Performs the sending of keyboard data in the buffer to the server.
// *
// * <p>
// * It checks if data is available in the buffer.
// * <ul>
// * <li>If available, it sends the data.</li>
// * <li>Otherwise, it waits for the data to be available.</li>
// * </ul>
// * </p>
// */
// @Override
// public void run() {
// while(!mStopFlag) {
// try {
// Pair<String, Boolean> data = mBuffer.poll(POLL_TIMEOUT, TIME_UNIT);
// if(data != null) {
// if (data.second) {
// sSecuredClient.sendData(data.first);
// } else sSecuredClient.sendData("Key", data.first);
// // Log.d("Keyboard sent", data.first + "__>" + data.first.length());
// }
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
// }
// }
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
// Path: app/src/main/java/project/android/KeyboardFragment.java
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import project.android.net.KeyboardThread;
import static project.android.ConnectionFragment.sConnectionAlive;
package project.android;
/**
* Class representing the <code>Fragment</code> for providing the
* GUI frontend for the keyboard module.
*
* <p>
* The following keyboard features are provided:
* <ul>
* <li>Predictive text input.</li>
* <li>Auto-correct feature.</li>
* <li>Hide sensitive text.</li>
* <li>Support for special keys like Ctrl, Alt etc. </li>
* </ul>
* </p>
*
* @see project.android.net.KeyboardThread
*/
public class KeyboardFragment extends Fragment implements View.OnKeyListener, View.OnClickListener,
CompoundButton.OnCheckedChangeListener, TextWatcher {
private String mLastInput;
private InputMethodManager mInput;
private String mLastWord; | private KeyboardThread mKeyboardThread; |
montimaj/Remouse | app/src/main/java/project/android/KeyboardFragment.java | // Path: app/src/main/java/project/android/net/KeyboardThread.java
// public class KeyboardThread implements Runnable {
//
// private boolean mStopFlag;
// private LinkedBlockingQueue<Pair<String, Boolean>> mBuffer;
//
// private static final long POLL_TIMEOUT = 100;
// private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
//
// /**
// * Constructor.
// *
// * Initializes this thread.
// */
// public KeyboardThread() {
// mStopFlag = false;
// mBuffer = new LinkedBlockingQueue<>();
// }
//
// /**
// * Inserts keyboard data to the buffer.
// *
// * This data is sent to the server by this <code>KeyboardThread</code>.
// *
// * @param data the data to be sent.
// * @param isSpecialKey <code>true</code>, if <code>data</code> represents
// * special key, <br/>
// * <code>false</code>, otherwise.
// */
// public void addToBuffer(String data, boolean isSpecialKey) {
// try {
// mBuffer.put(Pair.create(data, isSpecialKey));
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
//
// /**
// * Sets stop flag.
// *
// * Used to exit from the {@link #run()} method.
// */
// public void setStopFlag() { mStopFlag = true; }
//
// /**
// * Performs the sending of keyboard data in the buffer to the server.
// *
// * <p>
// * It checks if data is available in the buffer.
// * <ul>
// * <li>If available, it sends the data.</li>
// * <li>Otherwise, it waits for the data to be available.</li>
// * </ul>
// * </p>
// */
// @Override
// public void run() {
// while(!mStopFlag) {
// try {
// Pair<String, Boolean> data = mBuffer.poll(POLL_TIMEOUT, TIME_UNIT);
// if(data != null) {
// if (data.second) {
// sSecuredClient.sendData(data.first);
// } else sSecuredClient.sendData("Key", data.first);
// // Log.d("Keyboard sent", data.first + "__>" + data.first.length());
// }
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
// }
// }
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
| import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import project.android.net.KeyboardThread;
import static project.android.ConnectionFragment.sConnectionAlive; | R.id.upArrow, //24
R.id.downArrow, //25
R.id.leftArrow, //26
R.id.rightArrow //27
};
/**
* Overrides the
* <code>Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle)</code>
* of the Android API.
*
* Called to have the fragment instantiate its user interface view.
*
* @param inflater The <code>LayoutInflater</code> object that can be
* used to inflate any views in the fragment.
* @param container If non-null, this is the parent view that the
* fragment's UI is attached to. The fragment should
* not add the view itself, but this can be used to
* generate the <code>LayoutParams</code> of the view.
* @param savedInstanceState If non-null, this fragment is being
* re-constructed from a previous saved
* state as given here.
* @return the <code>View</code> for the fragment's UI, or <code>null</code>.
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_keyboard, container, false);
mInput = null;
mLastInput = null; | // Path: app/src/main/java/project/android/net/KeyboardThread.java
// public class KeyboardThread implements Runnable {
//
// private boolean mStopFlag;
// private LinkedBlockingQueue<Pair<String, Boolean>> mBuffer;
//
// private static final long POLL_TIMEOUT = 100;
// private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
//
// /**
// * Constructor.
// *
// * Initializes this thread.
// */
// public KeyboardThread() {
// mStopFlag = false;
// mBuffer = new LinkedBlockingQueue<>();
// }
//
// /**
// * Inserts keyboard data to the buffer.
// *
// * This data is sent to the server by this <code>KeyboardThread</code>.
// *
// * @param data the data to be sent.
// * @param isSpecialKey <code>true</code>, if <code>data</code> represents
// * special key, <br/>
// * <code>false</code>, otherwise.
// */
// public void addToBuffer(String data, boolean isSpecialKey) {
// try {
// mBuffer.put(Pair.create(data, isSpecialKey));
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
//
// /**
// * Sets stop flag.
// *
// * Used to exit from the {@link #run()} method.
// */
// public void setStopFlag() { mStopFlag = true; }
//
// /**
// * Performs the sending of keyboard data in the buffer to the server.
// *
// * <p>
// * It checks if data is available in the buffer.
// * <ul>
// * <li>If available, it sends the data.</li>
// * <li>Otherwise, it waits for the data to be available.</li>
// * </ul>
// * </p>
// */
// @Override
// public void run() {
// while(!mStopFlag) {
// try {
// Pair<String, Boolean> data = mBuffer.poll(POLL_TIMEOUT, TIME_UNIT);
// if(data != null) {
// if (data.second) {
// sSecuredClient.sendData(data.first);
// } else sSecuredClient.sendData("Key", data.first);
// // Log.d("Keyboard sent", data.first + "__>" + data.first.length());
// }
// } catch (InterruptedException e) { e.printStackTrace(); }
// }
// }
// }
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
// Path: app/src/main/java/project/android/KeyboardFragment.java
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import project.android.net.KeyboardThread;
import static project.android.ConnectionFragment.sConnectionAlive;
R.id.upArrow, //24
R.id.downArrow, //25
R.id.leftArrow, //26
R.id.rightArrow //27
};
/**
* Overrides the
* <code>Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle)</code>
* of the Android API.
*
* Called to have the fragment instantiate its user interface view.
*
* @param inflater The <code>LayoutInflater</code> object that can be
* used to inflate any views in the fragment.
* @param container If non-null, this is the parent view that the
* fragment's UI is attached to. The fragment should
* not add the view itself, but this can be used to
* generate the <code>LayoutParams</code> of the view.
* @param savedInstanceState If non-null, this fragment is being
* re-constructed from a previous saved
* state as given here.
* @return the <code>View</code> for the fragment's UI, or <code>null</code>.
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_keyboard, container, false);
mInput = null;
mLastInput = null; | if(sConnectionAlive.containsValue(true)) { |
montimaj/Remouse | app/src/main/java/project/android/TouchpadFragment.java | // Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static Client sSecuredClient;
| import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import static project.android.ConnectionFragment.sConnectionAlive;
import static project.android.ConnectionFragment.sSecuredClient; | /**
* Overrides the <code>Fragment.onPause()</code>
* method of the Android API.
*
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onPause() {
super.onPause();
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
/**
* Overrides the
* <code>View.onTouchListener.onTouch(View, MotionEvent)</code>
* method of the Android API.
*
* Called when a touch event is dispatched to a <code>View</code>.
* This allows listeners to get a chance to respond before the
* target <code>View</code>.
*
* @param view the view the touch event has been dispatched to.
* @param motionEvent the <code>MotionEvent</code> object containing
* full information about the event.
* @return <code>true</code>, if the listener has consumed the event,<br/>
* <code>false</code>, otherwise.
*/
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (view.getId() == R.id.button_touch) { | // Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static Client sSecuredClient;
// Path: app/src/main/java/project/android/TouchpadFragment.java
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import static project.android.ConnectionFragment.sConnectionAlive;
import static project.android.ConnectionFragment.sSecuredClient;
/**
* Overrides the <code>Fragment.onPause()</code>
* method of the Android API.
*
* Called when the system is about to start resuming a previous activity.
*/
@Override
public void onPause() {
super.onPause();
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
/**
* Overrides the
* <code>View.onTouchListener.onTouch(View, MotionEvent)</code>
* method of the Android API.
*
* Called when a touch event is dispatched to a <code>View</code>.
* This allows listeners to get a chance to respond before the
* target <code>View</code>.
*
* @param view the view the touch event has been dispatched to.
* @param motionEvent the <code>MotionEvent</code> object containing
* full information about the event.
* @return <code>true</code>, if the listener has consumed the event,<br/>
* <code>false</code>, otherwise.
*/
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (view.getId() == R.id.button_touch) { | if (sConnectionAlive.containsValue(true)) processTouch(motionEvent); |
montimaj/Remouse | app/src/main/java/project/android/TouchpadFragment.java | // Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static Client sSecuredClient;
| import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import static project.android.ConnectionFragment.sConnectionAlive;
import static project.android.ConnectionFragment.sSecuredClient; | * @param view the view that was clicked.
*/
@Override
public void onClick(View view) {
String data = "";
switch (view.getId()) {
case R.id.button_touch_right:
data = "right";
break;
case R.id.button_touch_middle:
data = "middle";
break;
case R.id.touch_upscroll:
data = "upscroll";
break;
case R.id.touch_downscroll:
data = "downscroll";
}
sendMouseButtonData(data);
}
private void sendMouseButtonData(final String data) {
new Thread(new Runnable() {
@Override
public void run() {
if (sConnectionAlive.containsValue(true)) { | // Path: app/src/main/java/project/android/ConnectionFragment.java
// public static HashMap<String, Boolean> sConnectionAlive = new HashMap<>();
//
// Path: app/src/main/java/project/android/ConnectionFragment.java
// public static Client sSecuredClient;
// Path: app/src/main/java/project/android/TouchpadFragment.java
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import static project.android.ConnectionFragment.sConnectionAlive;
import static project.android.ConnectionFragment.sSecuredClient;
* @param view the view that was clicked.
*/
@Override
public void onClick(View view) {
String data = "";
switch (view.getId()) {
case R.id.button_touch_right:
data = "right";
break;
case R.id.button_touch_middle:
data = "middle";
break;
case R.id.touch_upscroll:
data = "upscroll";
break;
case R.id.touch_downscroll:
data = "downscroll";
}
sendMouseButtonData(data);
}
private void sendMouseButtonData(final String data) {
new Thread(new Runnable() {
@Override
public void run() {
if (sConnectionAlive.containsValue(true)) { | sSecuredClient.sendData("Mouse_Button", data); |
montimaj/Remouse | app/src/main/java/project/android/security/KeyStoreManager.java | // Path: app/src/main/java/project/android/MainActivity.java
// public static File sRemouseDir = null;
//
// Path: app/src/main/java/project/android/MainActivity.java
// public static SharedPreferences sSharedPrefs;
| import android.content.SharedPreferences;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import static project.android.MainActivity.sRemouseDir;
import static project.android.MainActivity.sSharedPrefs; | package project.android.security;
/**
* Manages the operations on the <code>KeyStore</code>.
*
* <p>
* This class provides a {@link java.security.KeyStore} which stores :
* <ul>
* <li> The private key ({@link java.security.PrivateKey}).</li>
* <li>
* A self-signed certificate ({@link java.security.cert.Certificate})
* that contains the public key and the digital signature.
* </li>
* </ul>
* The <code>KeyStore</code> is protected by a randomly generated
* password.
* </p>
*
* @see project.android.security.EKEProvider
* @see java.security.KeyStore
* @see java.security.KeyPair
* @see java.security.cert.Certificate
*/
class KeyStoreManager {
private KeyStore mKeyStore;
private static final String KEY_STORE_TYPE = "pkcs12";
private static final String KEY_STORE_ALIAS = "Remouse KeyStore";
private static final String KEY_STORE_PASSWORD = generateKSPassword(); | // Path: app/src/main/java/project/android/MainActivity.java
// public static File sRemouseDir = null;
//
// Path: app/src/main/java/project/android/MainActivity.java
// public static SharedPreferences sSharedPrefs;
// Path: app/src/main/java/project/android/security/KeyStoreManager.java
import android.content.SharedPreferences;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import static project.android.MainActivity.sRemouseDir;
import static project.android.MainActivity.sSharedPrefs;
package project.android.security;
/**
* Manages the operations on the <code>KeyStore</code>.
*
* <p>
* This class provides a {@link java.security.KeyStore} which stores :
* <ul>
* <li> The private key ({@link java.security.PrivateKey}).</li>
* <li>
* A self-signed certificate ({@link java.security.cert.Certificate})
* that contains the public key and the digital signature.
* </li>
* </ul>
* The <code>KeyStore</code> is protected by a randomly generated
* password.
* </p>
*
* @see project.android.security.EKEProvider
* @see java.security.KeyStore
* @see java.security.KeyPair
* @see java.security.cert.Certificate
*/
class KeyStoreManager {
private KeyStore mKeyStore;
private static final String KEY_STORE_TYPE = "pkcs12";
private static final String KEY_STORE_ALIAS = "Remouse KeyStore";
private static final String KEY_STORE_PASSWORD = generateKSPassword(); | private static final String KEY_STORE_NAME = sRemouseDir + "/remouse_keystore"; |
montimaj/Remouse | app/src/main/java/project/android/security/KeyStoreManager.java | // Path: app/src/main/java/project/android/MainActivity.java
// public static File sRemouseDir = null;
//
// Path: app/src/main/java/project/android/MainActivity.java
// public static SharedPreferences sSharedPrefs;
| import android.content.SharedPreferences;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import static project.android.MainActivity.sRemouseDir;
import static project.android.MainActivity.sSharedPrefs; | package project.android.security;
/**
* Manages the operations on the <code>KeyStore</code>.
*
* <p>
* This class provides a {@link java.security.KeyStore} which stores :
* <ul>
* <li> The private key ({@link java.security.PrivateKey}).</li>
* <li>
* A self-signed certificate ({@link java.security.cert.Certificate})
* that contains the public key and the digital signature.
* </li>
* </ul>
* The <code>KeyStore</code> is protected by a randomly generated
* password.
* </p>
*
* @see project.android.security.EKEProvider
* @see java.security.KeyStore
* @see java.security.KeyPair
* @see java.security.cert.Certificate
*/
class KeyStoreManager {
private KeyStore mKeyStore;
private static final String KEY_STORE_TYPE = "pkcs12";
private static final String KEY_STORE_ALIAS = "Remouse KeyStore";
private static final String KEY_STORE_PASSWORD = generateKSPassword();
private static final String KEY_STORE_NAME = sRemouseDir + "/remouse_keystore";
/**
* Constructor.
* Initializes this <code>KeyStoreManager</code>.
*
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws IOException
*/
KeyStoreManager() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
mKeyStore = KeyStore.getInstance(KEY_STORE_TYPE);
mKeyStore.load(null, KEY_STORE_PASSWORD.toCharArray());
}
/**
* Checks if a <code>KeyStore</code> exists.
*
* @return <code>true</code>, if the <code>KeyStore</code> exists, <br/>
* <code>false</code>, otherwise.
*/
static boolean keyStoreExists() { return new File(KEY_STORE_NAME).exists(); }
/**
* Method to store the private key and the certificate in the
* <code>KeyStore</code>.
*
* @param privateKey the {@link java.security.PrivateKey} object.
* @param cert the {@link java.security.cert.Certificate} object(s).
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
void setMasterKey(PrivateKey privateKey, Certificate ...cert) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
KeyStore.PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry(privateKey, cert);
mKeyStore.setEntry(KEY_STORE_ALIAS, privateKeyEntry,new KeyStore.PasswordProtection(KEY_STORE_PASSWORD.toCharArray()));
mKeyStore.store(new FileOutputStream(KEY_STORE_NAME), KEY_STORE_PASSWORD.toCharArray());
}
/**
* Returns the private-public key pair.
*
* @return {@link java.security.KeyPair} object.
* @throws IOException
* @throws KeyStoreException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws UnrecoverableEntryException
*/
static KeyPair getKSKeyPair() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableEntryException {
FileInputStream fis = new FileInputStream(KEY_STORE_NAME);
KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
keyStore.load(fis, KEY_STORE_PASSWORD.toCharArray());
Key key = keyStore.getKey(KEY_STORE_ALIAS, KEY_STORE_PASSWORD.toCharArray());
if(key instanceof PrivateKey) {
Certificate certificate = keyStore.getCertificate(KEY_STORE_ALIAS);
PublicKey publicKey = certificate.getPublicKey();
return new KeyPair(publicKey, (PrivateKey) key);
}
return null;
}
private static String generateKSPassword() { | // Path: app/src/main/java/project/android/MainActivity.java
// public static File sRemouseDir = null;
//
// Path: app/src/main/java/project/android/MainActivity.java
// public static SharedPreferences sSharedPrefs;
// Path: app/src/main/java/project/android/security/KeyStoreManager.java
import android.content.SharedPreferences;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import static project.android.MainActivity.sRemouseDir;
import static project.android.MainActivity.sSharedPrefs;
package project.android.security;
/**
* Manages the operations on the <code>KeyStore</code>.
*
* <p>
* This class provides a {@link java.security.KeyStore} which stores :
* <ul>
* <li> The private key ({@link java.security.PrivateKey}).</li>
* <li>
* A self-signed certificate ({@link java.security.cert.Certificate})
* that contains the public key and the digital signature.
* </li>
* </ul>
* The <code>KeyStore</code> is protected by a randomly generated
* password.
* </p>
*
* @see project.android.security.EKEProvider
* @see java.security.KeyStore
* @see java.security.KeyPair
* @see java.security.cert.Certificate
*/
class KeyStoreManager {
private KeyStore mKeyStore;
private static final String KEY_STORE_TYPE = "pkcs12";
private static final String KEY_STORE_ALIAS = "Remouse KeyStore";
private static final String KEY_STORE_PASSWORD = generateKSPassword();
private static final String KEY_STORE_NAME = sRemouseDir + "/remouse_keystore";
/**
* Constructor.
* Initializes this <code>KeyStoreManager</code>.
*
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws IOException
*/
KeyStoreManager() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
mKeyStore = KeyStore.getInstance(KEY_STORE_TYPE);
mKeyStore.load(null, KEY_STORE_PASSWORD.toCharArray());
}
/**
* Checks if a <code>KeyStore</code> exists.
*
* @return <code>true</code>, if the <code>KeyStore</code> exists, <br/>
* <code>false</code>, otherwise.
*/
static boolean keyStoreExists() { return new File(KEY_STORE_NAME).exists(); }
/**
* Method to store the private key and the certificate in the
* <code>KeyStore</code>.
*
* @param privateKey the {@link java.security.PrivateKey} object.
* @param cert the {@link java.security.cert.Certificate} object(s).
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
void setMasterKey(PrivateKey privateKey, Certificate ...cert) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
KeyStore.PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry(privateKey, cert);
mKeyStore.setEntry(KEY_STORE_ALIAS, privateKeyEntry,new KeyStore.PasswordProtection(KEY_STORE_PASSWORD.toCharArray()));
mKeyStore.store(new FileOutputStream(KEY_STORE_NAME), KEY_STORE_PASSWORD.toCharArray());
}
/**
* Returns the private-public key pair.
*
* @return {@link java.security.KeyPair} object.
* @throws IOException
* @throws KeyStoreException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws UnrecoverableEntryException
*/
static KeyPair getKSKeyPair() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableEntryException {
FileInputStream fis = new FileInputStream(KEY_STORE_NAME);
KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
keyStore.load(fis, KEY_STORE_PASSWORD.toCharArray());
Key key = keyStore.getKey(KEY_STORE_ALIAS, KEY_STORE_PASSWORD.toCharArray());
if(key instanceof PrivateKey) {
Certificate certificate = keyStore.getCertificate(KEY_STORE_ALIAS);
PublicKey publicKey = certificate.getPublicKey();
return new KeyPair(publicKey, (PrivateKey) key);
}
return null;
}
private static String generateKSPassword() { | String password = sSharedPrefs.getString("Password", null); |
montimaj/Remouse | app/src/main/java/project/android/net/KeyboardThread.java | // Path: app/src/main/java/project/android/ConnectionFragment.java
// public static Client sSecuredClient;
| import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import static project.android.ConnectionFragment.sSecuredClient; | package project.android.net;
/**
* Implementation of the <code>java.lang.Runnable</code> for the thread responsible
* for sending keyboard data to the server.
*
* <p>
* This thread maintains a buffer to store the data to be sent to the server. It
* is implemented as a <code>java.util.concurrent.LinkedBlockingQueue</code>. The
* data contains two fields :
* <ul>
* <li>
* A data field which represents the data to be sent, and
* </li>
* <li>
* A boolean flag which determines if the data represents a special key.
* </li>
* </ul>
* </p>
* <p>
* The data is inserted to the buffer by the listener methods defined in the
* {@link project.android.KeyboardFragment} class. This thread continuously
* monitors the buffer to check if data is available. If available, it sends
* the data.
* </p>
* <p>
* This thread is started when the keyboard UI is loaded and the
* {@link project.android.KeyboardFragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}
* method is called. It is stopped by invoking the {@link #setStopFlag()}
* method when the keyboard UI is destroyed and the
* {@link project.android.KeyboardFragment#onDestroyView()} method is called.
* </p>
*
* @see java.lang.Runnable
* @see java.util.concurrent.LinkedBlockingQueue
* @see project.android.KeyboardFragment
* @see project.android.KeyboardFragment#onCreateView(LayoutInflater, ViewGroup, Bundle)
* @see project.android.KeyboardFragment#onDestroyView()
* @see #setStopFlag()
*/
public class KeyboardThread implements Runnable {
private boolean mStopFlag;
private LinkedBlockingQueue<Pair<String, Boolean>> mBuffer;
private static final long POLL_TIMEOUT = 100;
private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
/**
* Constructor.
*
* Initializes this thread.
*/
public KeyboardThread() {
mStopFlag = false;
mBuffer = new LinkedBlockingQueue<>();
}
/**
* Inserts keyboard data to the buffer.
*
* This data is sent to the server by this <code>KeyboardThread</code>.
*
* @param data the data to be sent.
* @param isSpecialKey <code>true</code>, if <code>data</code> represents
* special key, <br/>
* <code>false</code>, otherwise.
*/
public void addToBuffer(String data, boolean isSpecialKey) {
try {
mBuffer.put(Pair.create(data, isSpecialKey));
} catch (InterruptedException e) { e.printStackTrace(); }
}
/**
* Sets stop flag.
*
* Used to exit from the {@link #run()} method.
*/
public void setStopFlag() { mStopFlag = true; }
/**
* Performs the sending of keyboard data in the buffer to the server.
*
* <p>
* It checks if data is available in the buffer.
* <ul>
* <li>If available, it sends the data.</li>
* <li>Otherwise, it waits for the data to be available.</li>
* </ul>
* </p>
*/
@Override
public void run() {
while(!mStopFlag) {
try {
Pair<String, Boolean> data = mBuffer.poll(POLL_TIMEOUT, TIME_UNIT);
if(data != null) {
if (data.second) { | // Path: app/src/main/java/project/android/ConnectionFragment.java
// public static Client sSecuredClient;
// Path: app/src/main/java/project/android/net/KeyboardThread.java
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import static project.android.ConnectionFragment.sSecuredClient;
package project.android.net;
/**
* Implementation of the <code>java.lang.Runnable</code> for the thread responsible
* for sending keyboard data to the server.
*
* <p>
* This thread maintains a buffer to store the data to be sent to the server. It
* is implemented as a <code>java.util.concurrent.LinkedBlockingQueue</code>. The
* data contains two fields :
* <ul>
* <li>
* A data field which represents the data to be sent, and
* </li>
* <li>
* A boolean flag which determines if the data represents a special key.
* </li>
* </ul>
* </p>
* <p>
* The data is inserted to the buffer by the listener methods defined in the
* {@link project.android.KeyboardFragment} class. This thread continuously
* monitors the buffer to check if data is available. If available, it sends
* the data.
* </p>
* <p>
* This thread is started when the keyboard UI is loaded and the
* {@link project.android.KeyboardFragment#onCreateView(LayoutInflater, ViewGroup, Bundle)}
* method is called. It is stopped by invoking the {@link #setStopFlag()}
* method when the keyboard UI is destroyed and the
* {@link project.android.KeyboardFragment#onDestroyView()} method is called.
* </p>
*
* @see java.lang.Runnable
* @see java.util.concurrent.LinkedBlockingQueue
* @see project.android.KeyboardFragment
* @see project.android.KeyboardFragment#onCreateView(LayoutInflater, ViewGroup, Bundle)
* @see project.android.KeyboardFragment#onDestroyView()
* @see #setStopFlag()
*/
public class KeyboardThread implements Runnable {
private boolean mStopFlag;
private LinkedBlockingQueue<Pair<String, Boolean>> mBuffer;
private static final long POLL_TIMEOUT = 100;
private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
/**
* Constructor.
*
* Initializes this thread.
*/
public KeyboardThread() {
mStopFlag = false;
mBuffer = new LinkedBlockingQueue<>();
}
/**
* Inserts keyboard data to the buffer.
*
* This data is sent to the server by this <code>KeyboardThread</code>.
*
* @param data the data to be sent.
* @param isSpecialKey <code>true</code>, if <code>data</code> represents
* special key, <br/>
* <code>false</code>, otherwise.
*/
public void addToBuffer(String data, boolean isSpecialKey) {
try {
mBuffer.put(Pair.create(data, isSpecialKey));
} catch (InterruptedException e) { e.printStackTrace(); }
}
/**
* Sets stop flag.
*
* Used to exit from the {@link #run()} method.
*/
public void setStopFlag() { mStopFlag = true; }
/**
* Performs the sending of keyboard data in the buffer to the server.
*
* <p>
* It checks if data is available in the buffer.
* <ul>
* <li>If available, it sends the data.</li>
* <li>Otherwise, it waits for the data to be available.</li>
* </ul>
* </p>
*/
@Override
public void run() {
while(!mStopFlag) {
try {
Pair<String, Boolean> data = mBuffer.poll(POLL_TIMEOUT, TIME_UNIT);
if(data != null) {
if (data.second) { | sSecuredClient.sendData(data.first); |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/ByteBufferWrapper.java | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
| import com.wizzardo.epoll.readable.ReadableData;
import java.nio.ByteBuffer; | package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 3/15/14
*/
public class ByteBufferWrapper {
private final ByteBuffer buffer;
private int offset = 0;
public final long address;
public ByteBufferWrapper(ByteBuffer buffer) {
if (!buffer.isDirect())
throw new IllegalArgumentException("byte buffer must be direct");
this.buffer = buffer;
address = EpollCore.address(buffer);
}
| // Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
// Path: src/main/java/com/wizzardo/epoll/ByteBufferWrapper.java
import com.wizzardo.epoll.readable.ReadableData;
import java.nio.ByteBuffer;
package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 3/15/14
*/
public class ByteBufferWrapper {
private final ByteBuffer buffer;
private int offset = 0;
public final long address;
public ByteBufferWrapper(ByteBuffer buffer) {
if (!buffer.isDirect())
throw new IllegalArgumentException("byte buffer must be direct");
this.buffer = buffer;
address = EpollCore.address(buffer);
}
| public ByteBufferWrapper(ReadableData data) { |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/EpollCore.java | // Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readInt(byte[] b, int offset) {
// // if (b.length - offset < 4 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 4 bytes");
//
// return ((b[offset] & 0xff) << 24) + ((b[offset + 1] & 0xff) << 16) + ((b[offset + 2] & 0xff) << 8) + ((b[offset + 3] & 0xff));
// }
//
// Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readShort(byte[] b, int offset) {
// // if (b.length - offset < 2 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 2 bytes");
//
// return ((b[offset] & 0xff) << 8) + ((b[offset + 1] & 0xff));
// }
| import com.wizzardo.tools.misc.Unchecked;
import com.wizzardo.tools.reflection.FieldReflection;
import com.wizzardo.tools.reflection.FieldReflectionFactory;
import com.wizzardo.tools.reflection.UnsafeTools;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
import static com.wizzardo.epoll.Utils.readInt;
import static com.wizzardo.epoll.Utils.readShort; | ioThreads[i].start();
}
ByteBuffer eventsBuffer = this.events;
byte[] events = new byte[eventsBuffer.capacity()];
byte[] newConnections = new byte[eventsBuffer.capacity()];
if (ioThreadsCount == 0) {
IOThread<? extends T> ioThread = createIOThread(1, 1);
ioThreadsCount = 1;
ioThread.scope = scope;
ioThreads = new IOThread[]{ioThread};
ioThreads[0].setTTL(ttl);
ioThreads[0].loadCertificates(sslConfig);
long prev = System.nanoTime();
while (running) {
try {
eventsBuffer.position(0);
long now = System.nanoTime() * 1000;
long nowMinusSecond = now - 1_000_000_000_000L; // 1 sec
int r = waitForEvents(500);
eventsBuffer.limit(r);
eventsBuffer.get(events, 0, r);
int i = 0;
while (i < r) {
int event = events[i];
if (event == 0) {
acceptConnections(newConnections);
} else { | // Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readInt(byte[] b, int offset) {
// // if (b.length - offset < 4 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 4 bytes");
//
// return ((b[offset] & 0xff) << 24) + ((b[offset + 1] & 0xff) << 16) + ((b[offset + 2] & 0xff) << 8) + ((b[offset + 3] & 0xff));
// }
//
// Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readShort(byte[] b, int offset) {
// // if (b.length - offset < 2 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 2 bytes");
//
// return ((b[offset] & 0xff) << 8) + ((b[offset + 1] & 0xff));
// }
// Path: src/main/java/com/wizzardo/epoll/EpollCore.java
import com.wizzardo.tools.misc.Unchecked;
import com.wizzardo.tools.reflection.FieldReflection;
import com.wizzardo.tools.reflection.FieldReflectionFactory;
import com.wizzardo.tools.reflection.UnsafeTools;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
import static com.wizzardo.epoll.Utils.readInt;
import static com.wizzardo.epoll.Utils.readShort;
ioThreads[i].start();
}
ByteBuffer eventsBuffer = this.events;
byte[] events = new byte[eventsBuffer.capacity()];
byte[] newConnections = new byte[eventsBuffer.capacity()];
if (ioThreadsCount == 0) {
IOThread<? extends T> ioThread = createIOThread(1, 1);
ioThreadsCount = 1;
ioThread.scope = scope;
ioThreads = new IOThread[]{ioThread};
ioThreads[0].setTTL(ttl);
ioThreads[0].loadCertificates(sslConfig);
long prev = System.nanoTime();
while (running) {
try {
eventsBuffer.position(0);
long now = System.nanoTime() * 1000;
long nowMinusSecond = now - 1_000_000_000_000L; // 1 sec
int r = waitForEvents(500);
eventsBuffer.limit(r);
eventsBuffer.get(events, 0, r);
int i = 0;
while (i < r) {
int event = events[i];
if (event == 0) {
acceptConnections(newConnections);
} else { | int fd = readInt(events, i + 1); |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/EpollCore.java | // Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readInt(byte[] b, int offset) {
// // if (b.length - offset < 4 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 4 bytes");
//
// return ((b[offset] & 0xff) << 24) + ((b[offset + 1] & 0xff) << 16) + ((b[offset + 2] & 0xff) << 8) + ((b[offset + 3] & 0xff));
// }
//
// Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readShort(byte[] b, int offset) {
// // if (b.length - offset < 2 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 2 bytes");
//
// return ((b[offset] & 0xff) << 8) + ((b[offset + 1] & 0xff));
// }
| import com.wizzardo.tools.misc.Unchecked;
import com.wizzardo.tools.reflection.FieldReflection;
import com.wizzardo.tools.reflection.FieldReflectionFactory;
import com.wizzardo.tools.reflection.UnsafeTools;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
import static com.wizzardo.epoll.Utils.readInt;
import static com.wizzardo.epoll.Utils.readShort; | public void setTTL(long milliseconds) {
ttl = milliseconds;
}
public long getTTL() {
return ttl;
}
public void close() {
synchronized (this) {
if (running) {
running = false;
stopListening(scope);
try {
join();
} catch (InterruptedException ignored) {
}
}
}
}
private void acceptConnections(byte[] buffer) throws IOException {
int k;
do {
events.position(0);
k = acceptConnections(scope, events.capacity() - 10);
events.limit(k);
events.get(buffer, 0, k);
// eventCounter.addAndGet(k / 10);
for (int j = 0; j < k; j += 10) { | // Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readInt(byte[] b, int offset) {
// // if (b.length - offset < 4 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 4 bytes");
//
// return ((b[offset] & 0xff) << 24) + ((b[offset + 1] & 0xff) << 16) + ((b[offset + 2] & 0xff) << 8) + ((b[offset + 3] & 0xff));
// }
//
// Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readShort(byte[] b, int offset) {
// // if (b.length - offset < 2 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 2 bytes");
//
// return ((b[offset] & 0xff) << 8) + ((b[offset + 1] & 0xff));
// }
// Path: src/main/java/com/wizzardo/epoll/EpollCore.java
import com.wizzardo.tools.misc.Unchecked;
import com.wizzardo.tools.reflection.FieldReflection;
import com.wizzardo.tools.reflection.FieldReflectionFactory;
import com.wizzardo.tools.reflection.UnsafeTools;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.regex.Pattern;
import static com.wizzardo.epoll.Utils.readInt;
import static com.wizzardo.epoll.Utils.readShort;
public void setTTL(long milliseconds) {
ttl = milliseconds;
}
public long getTTL() {
return ttl;
}
public void close() {
synchronized (this) {
if (running) {
running = false;
stopListening(scope);
try {
join();
} catch (InterruptedException ignored) {
}
}
}
}
private void acceptConnections(byte[] buffer) throws IOException {
int k;
do {
events.position(0);
k = acceptConnections(scope, events.capacity() - 10);
events.limit(k);
events.get(buffer, 0, k);
// eventCounter.addAndGet(k / 10);
for (int j = 0; j < k; j += 10) { | putConnection(createConnection(readInt(buffer, j), readInt(buffer, j + 4), readShort(buffer, j + 8))); |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/IOThread.java | // Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readInt(byte[] b, int offset) {
// // if (b.length - offset < 4 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 4 bytes");
//
// return ((b[offset] & 0xff) << 24) + ((b[offset + 1] & 0xff) << 16) + ((b[offset + 2] & 0xff) << 8) + ((b[offset + 3] & 0xff));
// }
| import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.wizzardo.epoll.Utils.readInt; | package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 6/25/14
*/
public class IOThread<T extends Connection> extends EpollCore<T> {
protected final int number;
protected final int divider;
protected T[] connections = (T[]) new Connection[1000];
protected Map<Integer, T> newConnections = new ConcurrentHashMap<Integer, T>();
protected LinkedHashMap<Long, T> timeouts = new LinkedHashMap<Long, T>();
public IOThread(int number, int divider) {
this.number = number;
this.divider = divider;
setName("IOThread-" + number);
}
@Override
public void run() {
byte[] events = new byte[this.events.capacity()];
// System.out.println("start new ioThread");
long prev = System.nanoTime();
while (running) {
this.events.position(0);
long now = System.nanoTime() * 1000;
long nowMinusSecond = now - 1_000_000_000_000L;// 1 sec
int r = waitForEvents(500);
// System.out.println("events length: "+r);
this.events.limit(r);
this.events.get(events, 0, r);
int i = 0;
while (i < r) {
int event = events[i]; | // Path: src/main/java/com/wizzardo/epoll/Utils.java
// public static int readInt(byte[] b, int offset) {
// // if (b.length - offset < 4 || offset < 0)
// // throw new IndexOutOfBoundsException("byte[].length = " + b.length + ", but offset = " + offset + " and we need 4 bytes");
//
// return ((b[offset] & 0xff) << 24) + ((b[offset + 1] & 0xff) << 16) + ((b[offset + 2] & 0xff) << 8) + ((b[offset + 3] & 0xff));
// }
// Path: src/main/java/com/wizzardo/epoll/IOThread.java
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.wizzardo.epoll.Utils.readInt;
package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 6/25/14
*/
public class IOThread<T extends Connection> extends EpollCore<T> {
protected final int number;
protected final int divider;
protected T[] connections = (T[]) new Connection[1000];
protected Map<Integer, T> newConnections = new ConcurrentHashMap<Integer, T>();
protected LinkedHashMap<Long, T> timeouts = new LinkedHashMap<Long, T>();
public IOThread(int number, int divider) {
this.number = number;
this.divider = divider;
setName("IOThread-" + number);
}
@Override
public void run() {
byte[] events = new byte[this.events.capacity()];
// System.out.println("start new ioThread");
long prev = System.nanoTime();
while (running) {
this.events.position(0);
long now = System.nanoTime() * 1000;
long nowMinusSecond = now - 1_000_000_000_000L;// 1 sec
int r = waitForEvents(500);
// System.out.println("events length: "+r);
this.events.limit(r);
this.events.get(events, 0, r);
int i = 0;
while (i < r) {
int event = events[i]; | int fd = readInt(events, i + 1); |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/readable/ReadableBuilder.java | // Path: src/main/java/com/wizzardo/epoll/ByteBufferProvider.java
// public interface ByteBufferProvider {
// ByteBufferWrapper getBuffer();
//
// /**
// * @return result of casting Thread.currentThread() to {@link ByteBufferProvider}
// * @throws ClassCastException if current thread doesn't implement {@link ByteBufferProvider}
// **/
// static ByteBufferProvider current() {
// return (ByteBufferProvider) Thread.currentThread();
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/ByteBufferWrapper.java
// public class ByteBufferWrapper {
//
// private final ByteBuffer buffer;
// private int offset = 0;
//
// public final long address;
//
// public ByteBufferWrapper(ByteBuffer buffer) {
// if (!buffer.isDirect())
// throw new IllegalArgumentException("byte buffer must be direct");
//
// this.buffer = buffer;
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(ReadableData data) {
// this.buffer = ByteBuffer.allocateDirect((int) data.length());
// address = EpollCore.address(buffer);
// data.read(buffer);
// flip();
// }
//
// public ByteBufferWrapper(int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ByteBufferWrapper(byte[] bytes, int offset, int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// put(bytes, offset, length);
// flip();
// }
//
// public int limit() {
// return buffer.limit();
// }
//
// public ByteBufferWrapper position(int r) {
// buffer.position(r);
// return this;
// }
//
// public ByteBufferWrapper flip() {
// buffer.flip();
// return this;
// }
//
// public ByteBufferWrapper put(byte[] b, int offset, int l) {
// buffer.put(b, offset, l);
// return this;
// }
//
// public int remaining() {
// return buffer.remaining();
// }
//
// public int position() {
// return buffer.position();
// }
//
// public void clear() {
// buffer.clear();
// }
//
// public ByteBuffer buffer() {
// return buffer;
// }
//
// public int capacity() {
// return buffer.capacity();
// }
//
// public int offset() {
// return offset;
// }
//
// public void offset(int offset) {
// //TODO check usage of offset
// this.offset = offset;
// }
//
// @Override
// public String toString() {
// int position = buffer.position();
// int limit = buffer.limit();
// buffer.position(0);
// buffer.limit(buffer.capacity());
// byte[] bytes = new byte[buffer.limit()];
// buffer.get(bytes);
//
// buffer.clear();
// buffer.limit(limit);
// buffer.position(position);
// return new String(bytes);
// }
// }
| import com.wizzardo.epoll.ByteBufferProvider;
import com.wizzardo.epoll.ByteBufferWrapper;
import java.io.IOException;
import java.nio.ByteBuffer; | return append(bytes, 0, bytes.length);
}
public ReadableBuilder append(byte[] bytes, int offset, int length) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = new ReadableByteArray(bytes, offset, length);
partsCount++;
return this;
}
public ReadableBuilder append(ReadableData readableData) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = readableData;
partsCount++;
return this;
}
protected void increaseSize() {
ReadableData[] temp = new ReadableData[Math.max(partsCount * 3 / 2, 2)];
System.arraycopy(parts, 0, temp, 0, partsCount);
parts = temp;
}
@Override | // Path: src/main/java/com/wizzardo/epoll/ByteBufferProvider.java
// public interface ByteBufferProvider {
// ByteBufferWrapper getBuffer();
//
// /**
// * @return result of casting Thread.currentThread() to {@link ByteBufferProvider}
// * @throws ClassCastException if current thread doesn't implement {@link ByteBufferProvider}
// **/
// static ByteBufferProvider current() {
// return (ByteBufferProvider) Thread.currentThread();
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/ByteBufferWrapper.java
// public class ByteBufferWrapper {
//
// private final ByteBuffer buffer;
// private int offset = 0;
//
// public final long address;
//
// public ByteBufferWrapper(ByteBuffer buffer) {
// if (!buffer.isDirect())
// throw new IllegalArgumentException("byte buffer must be direct");
//
// this.buffer = buffer;
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(ReadableData data) {
// this.buffer = ByteBuffer.allocateDirect((int) data.length());
// address = EpollCore.address(buffer);
// data.read(buffer);
// flip();
// }
//
// public ByteBufferWrapper(int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ByteBufferWrapper(byte[] bytes, int offset, int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// put(bytes, offset, length);
// flip();
// }
//
// public int limit() {
// return buffer.limit();
// }
//
// public ByteBufferWrapper position(int r) {
// buffer.position(r);
// return this;
// }
//
// public ByteBufferWrapper flip() {
// buffer.flip();
// return this;
// }
//
// public ByteBufferWrapper put(byte[] b, int offset, int l) {
// buffer.put(b, offset, l);
// return this;
// }
//
// public int remaining() {
// return buffer.remaining();
// }
//
// public int position() {
// return buffer.position();
// }
//
// public void clear() {
// buffer.clear();
// }
//
// public ByteBuffer buffer() {
// return buffer;
// }
//
// public int capacity() {
// return buffer.capacity();
// }
//
// public int offset() {
// return offset;
// }
//
// public void offset(int offset) {
// //TODO check usage of offset
// this.offset = offset;
// }
//
// @Override
// public String toString() {
// int position = buffer.position();
// int limit = buffer.limit();
// buffer.position(0);
// buffer.limit(buffer.capacity());
// byte[] bytes = new byte[buffer.limit()];
// buffer.get(bytes);
//
// buffer.clear();
// buffer.limit(limit);
// buffer.position(position);
// return new String(bytes);
// }
// }
// Path: src/main/java/com/wizzardo/epoll/readable/ReadableBuilder.java
import com.wizzardo.epoll.ByteBufferProvider;
import com.wizzardo.epoll.ByteBufferWrapper;
import java.io.IOException;
import java.nio.ByteBuffer;
return append(bytes, 0, bytes.length);
}
public ReadableBuilder append(byte[] bytes, int offset, int length) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = new ReadableByteArray(bytes, offset, length);
partsCount++;
return this;
}
public ReadableBuilder append(ReadableData readableData) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = readableData;
partsCount++;
return this;
}
protected void increaseSize() {
ReadableData[] temp = new ReadableData[Math.max(partsCount * 3 / 2, 2)];
System.arraycopy(parts, 0, temp, 0, partsCount);
parts = temp;
}
@Override | public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) { |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/readable/ReadableBuilder.java | // Path: src/main/java/com/wizzardo/epoll/ByteBufferProvider.java
// public interface ByteBufferProvider {
// ByteBufferWrapper getBuffer();
//
// /**
// * @return result of casting Thread.currentThread() to {@link ByteBufferProvider}
// * @throws ClassCastException if current thread doesn't implement {@link ByteBufferProvider}
// **/
// static ByteBufferProvider current() {
// return (ByteBufferProvider) Thread.currentThread();
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/ByteBufferWrapper.java
// public class ByteBufferWrapper {
//
// private final ByteBuffer buffer;
// private int offset = 0;
//
// public final long address;
//
// public ByteBufferWrapper(ByteBuffer buffer) {
// if (!buffer.isDirect())
// throw new IllegalArgumentException("byte buffer must be direct");
//
// this.buffer = buffer;
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(ReadableData data) {
// this.buffer = ByteBuffer.allocateDirect((int) data.length());
// address = EpollCore.address(buffer);
// data.read(buffer);
// flip();
// }
//
// public ByteBufferWrapper(int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ByteBufferWrapper(byte[] bytes, int offset, int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// put(bytes, offset, length);
// flip();
// }
//
// public int limit() {
// return buffer.limit();
// }
//
// public ByteBufferWrapper position(int r) {
// buffer.position(r);
// return this;
// }
//
// public ByteBufferWrapper flip() {
// buffer.flip();
// return this;
// }
//
// public ByteBufferWrapper put(byte[] b, int offset, int l) {
// buffer.put(b, offset, l);
// return this;
// }
//
// public int remaining() {
// return buffer.remaining();
// }
//
// public int position() {
// return buffer.position();
// }
//
// public void clear() {
// buffer.clear();
// }
//
// public ByteBuffer buffer() {
// return buffer;
// }
//
// public int capacity() {
// return buffer.capacity();
// }
//
// public int offset() {
// return offset;
// }
//
// public void offset(int offset) {
// //TODO check usage of offset
// this.offset = offset;
// }
//
// @Override
// public String toString() {
// int position = buffer.position();
// int limit = buffer.limit();
// buffer.position(0);
// buffer.limit(buffer.capacity());
// byte[] bytes = new byte[buffer.limit()];
// buffer.get(bytes);
//
// buffer.clear();
// buffer.limit(limit);
// buffer.position(position);
// return new String(bytes);
// }
// }
| import com.wizzardo.epoll.ByteBufferProvider;
import com.wizzardo.epoll.ByteBufferWrapper;
import java.io.IOException;
import java.nio.ByteBuffer; | return append(bytes, 0, bytes.length);
}
public ReadableBuilder append(byte[] bytes, int offset, int length) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = new ReadableByteArray(bytes, offset, length);
partsCount++;
return this;
}
public ReadableBuilder append(ReadableData readableData) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = readableData;
partsCount++;
return this;
}
protected void increaseSize() {
ReadableData[] temp = new ReadableData[Math.max(partsCount * 3 / 2, 2)];
System.arraycopy(parts, 0, temp, 0, partsCount);
parts = temp;
}
@Override | // Path: src/main/java/com/wizzardo/epoll/ByteBufferProvider.java
// public interface ByteBufferProvider {
// ByteBufferWrapper getBuffer();
//
// /**
// * @return result of casting Thread.currentThread() to {@link ByteBufferProvider}
// * @throws ClassCastException if current thread doesn't implement {@link ByteBufferProvider}
// **/
// static ByteBufferProvider current() {
// return (ByteBufferProvider) Thread.currentThread();
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/ByteBufferWrapper.java
// public class ByteBufferWrapper {
//
// private final ByteBuffer buffer;
// private int offset = 0;
//
// public final long address;
//
// public ByteBufferWrapper(ByteBuffer buffer) {
// if (!buffer.isDirect())
// throw new IllegalArgumentException("byte buffer must be direct");
//
// this.buffer = buffer;
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(ReadableData data) {
// this.buffer = ByteBuffer.allocateDirect((int) data.length());
// address = EpollCore.address(buffer);
// data.read(buffer);
// flip();
// }
//
// public ByteBufferWrapper(int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// }
//
// public ByteBufferWrapper(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ByteBufferWrapper(byte[] bytes, int offset, int length) {
// this.buffer = ByteBuffer.allocateDirect(length);
// address = EpollCore.address(buffer);
// put(bytes, offset, length);
// flip();
// }
//
// public int limit() {
// return buffer.limit();
// }
//
// public ByteBufferWrapper position(int r) {
// buffer.position(r);
// return this;
// }
//
// public ByteBufferWrapper flip() {
// buffer.flip();
// return this;
// }
//
// public ByteBufferWrapper put(byte[] b, int offset, int l) {
// buffer.put(b, offset, l);
// return this;
// }
//
// public int remaining() {
// return buffer.remaining();
// }
//
// public int position() {
// return buffer.position();
// }
//
// public void clear() {
// buffer.clear();
// }
//
// public ByteBuffer buffer() {
// return buffer;
// }
//
// public int capacity() {
// return buffer.capacity();
// }
//
// public int offset() {
// return offset;
// }
//
// public void offset(int offset) {
// //TODO check usage of offset
// this.offset = offset;
// }
//
// @Override
// public String toString() {
// int position = buffer.position();
// int limit = buffer.limit();
// buffer.position(0);
// buffer.limit(buffer.capacity());
// byte[] bytes = new byte[buffer.limit()];
// buffer.get(bytes);
//
// buffer.clear();
// buffer.limit(limit);
// buffer.position(position);
// return new String(bytes);
// }
// }
// Path: src/main/java/com/wizzardo/epoll/readable/ReadableBuilder.java
import com.wizzardo.epoll.ByteBufferProvider;
import com.wizzardo.epoll.ByteBufferWrapper;
import java.io.IOException;
import java.nio.ByteBuffer;
return append(bytes, 0, bytes.length);
}
public ReadableBuilder append(byte[] bytes, int offset, int length) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = new ReadableByteArray(bytes, offset, length);
partsCount++;
return this;
}
public ReadableBuilder append(ReadableData readableData) {
if (partsCount + 1 >= parts.length)
increaseSize();
parts[partsCount] = readableData;
partsCount++;
return this;
}
protected void increaseSize() {
ReadableData[] temp = new ReadableData[Math.max(partsCount * 3 / 2, 2)];
System.arraycopy(parts, 0, temp, 0, partsCount);
parts = temp;
}
@Override | public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) { |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/Connection.java | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableByteArray.java
// public class ReadableByteArray extends ReadableData {
// protected byte[] bytes;
// protected int offset, length, position;
//
// public ReadableByteArray(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ReadableByteArray(byte[] bytes, int offset, int length) {
// this.bytes = bytes;
// this.offset = offset;
// this.length = length;
// position = offset;
// }
//
// @Override
// public int read(ByteBuffer byteBuffer) {
// int r = Math.min(byteBuffer.remaining(), length + offset - position);
// byteBuffer.put(bytes, position, r);
// position += r;
// return r;
// }
//
// @Override
// public void unread(int i) {
// if (i < 0)
// throw new IllegalArgumentException("can't unread negative value: " + i);
// if (position - i < offset)
// throw new IllegalArgumentException("can't unread value bigger than offset (" + offset + "): " + i);
// position -= i;
// }
//
// @Override
// public boolean isComplete() {
// return length == position - offset;
// }
//
// @Override
// public long complete() {
// return position - offset;
// }
//
// @Override
// public long length() {
// return length;
// }
//
// public long remains() {
// return length + offset - position;
// }
//
// @Override
// public String toString() {
// return new String(bytes, offset, length);
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
| import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.tools.io.IOTools;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicReference; | package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 1/6/14
*/
public class Connection implements Cloneable, Closeable {
protected static final int EPOLLIN = 0x001;
protected static final int EPOLLOUT = 0x004;
protected int fd;
protected int ip, port; | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableByteArray.java
// public class ReadableByteArray extends ReadableData {
// protected byte[] bytes;
// protected int offset, length, position;
//
// public ReadableByteArray(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ReadableByteArray(byte[] bytes, int offset, int length) {
// this.bytes = bytes;
// this.offset = offset;
// this.length = length;
// position = offset;
// }
//
// @Override
// public int read(ByteBuffer byteBuffer) {
// int r = Math.min(byteBuffer.remaining(), length + offset - position);
// byteBuffer.put(bytes, position, r);
// position += r;
// return r;
// }
//
// @Override
// public void unread(int i) {
// if (i < 0)
// throw new IllegalArgumentException("can't unread negative value: " + i);
// if (position - i < offset)
// throw new IllegalArgumentException("can't unread value bigger than offset (" + offset + "): " + i);
// position -= i;
// }
//
// @Override
// public boolean isComplete() {
// return length == position - offset;
// }
//
// @Override
// public long complete() {
// return position - offset;
// }
//
// @Override
// public long length() {
// return length;
// }
//
// public long remains() {
// return length + offset - position;
// }
//
// @Override
// public String toString() {
// return new String(bytes, offset, length);
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
// Path: src/main/java/com/wizzardo/epoll/Connection.java
import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.tools.io.IOTools;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicReference;
package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 1/6/14
*/
public class Connection implements Cloneable, Closeable {
protected static final int EPOLLIN = 0x001;
protected static final int EPOLLOUT = 0x004;
protected int fd;
protected int ip, port; | protected volatile Deque<ReadableData> sending; |
wizzardo/epoll | src/main/java/com/wizzardo/epoll/Connection.java | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableByteArray.java
// public class ReadableByteArray extends ReadableData {
// protected byte[] bytes;
// protected int offset, length, position;
//
// public ReadableByteArray(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ReadableByteArray(byte[] bytes, int offset, int length) {
// this.bytes = bytes;
// this.offset = offset;
// this.length = length;
// position = offset;
// }
//
// @Override
// public int read(ByteBuffer byteBuffer) {
// int r = Math.min(byteBuffer.remaining(), length + offset - position);
// byteBuffer.put(bytes, position, r);
// position += r;
// return r;
// }
//
// @Override
// public void unread(int i) {
// if (i < 0)
// throw new IllegalArgumentException("can't unread negative value: " + i);
// if (position - i < offset)
// throw new IllegalArgumentException("can't unread value bigger than offset (" + offset + "): " + i);
// position -= i;
// }
//
// @Override
// public boolean isComplete() {
// return length == position - offset;
// }
//
// @Override
// public long complete() {
// return position - offset;
// }
//
// @Override
// public long length() {
// return length;
// }
//
// public long remains() {
// return length + offset - position;
// }
//
// @Override
// public String toString() {
// return new String(bytes, offset, length);
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
| import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.tools.io.IOTools;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicReference; | long last = this.lastEvent;
this.lastEvent = lastEvent;
return last;
}
long getLastEvent() {
return lastEvent;
}
public boolean isAlive() {
return alive;
}
protected synchronized void setIsAlive(boolean isAlive) {
alive = isAlive;
}
public boolean write(String s, ByteBufferProvider bufferProvider) {
try {
return write(s.getBytes("utf-8"), bufferProvider);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public boolean write(byte[] bytes, ByteBufferProvider bufferProvider) {
return write(bytes, 0, bytes.length, bufferProvider);
}
public boolean write(byte[] bytes, int offset, int length, ByteBufferProvider bufferProvider) { | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableByteArray.java
// public class ReadableByteArray extends ReadableData {
// protected byte[] bytes;
// protected int offset, length, position;
//
// public ReadableByteArray(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ReadableByteArray(byte[] bytes, int offset, int length) {
// this.bytes = bytes;
// this.offset = offset;
// this.length = length;
// position = offset;
// }
//
// @Override
// public int read(ByteBuffer byteBuffer) {
// int r = Math.min(byteBuffer.remaining(), length + offset - position);
// byteBuffer.put(bytes, position, r);
// position += r;
// return r;
// }
//
// @Override
// public void unread(int i) {
// if (i < 0)
// throw new IllegalArgumentException("can't unread negative value: " + i);
// if (position - i < offset)
// throw new IllegalArgumentException("can't unread value bigger than offset (" + offset + "): " + i);
// position -= i;
// }
//
// @Override
// public boolean isComplete() {
// return length == position - offset;
// }
//
// @Override
// public long complete() {
// return position - offset;
// }
//
// @Override
// public long length() {
// return length;
// }
//
// public long remains() {
// return length + offset - position;
// }
//
// @Override
// public String toString() {
// return new String(bytes, offset, length);
// }
// }
//
// Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
// Path: src/main/java/com/wizzardo/epoll/Connection.java
import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.tools.io.IOTools;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicReference;
long last = this.lastEvent;
this.lastEvent = lastEvent;
return last;
}
long getLastEvent() {
return lastEvent;
}
public boolean isAlive() {
return alive;
}
protected synchronized void setIsAlive(boolean isAlive) {
alive = isAlive;
}
public boolean write(String s, ByteBufferProvider bufferProvider) {
try {
return write(s.getBytes("utf-8"), bufferProvider);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public boolean write(byte[] bytes, ByteBufferProvider bufferProvider) {
return write(bytes, 0, bytes.length, bufferProvider);
}
public boolean write(byte[] bytes, int offset, int length, ByteBufferProvider bufferProvider) { | return write(new ReadableByteArray(bytes, offset, length), bufferProvider); |
wizzardo/epoll | src/test/java/com/wizzardo/epoll/SslServerTest.java | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
| import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.tools.http.*;
import com.wizzardo.tools.security.MD5;
import org.junit.Assert;
import org.junit.Test;
import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; | if (read >= image.length / 10) {
Thread.sleep(2000);
read = 0;
}
}
Assert.assertEquals(MD5.create().update(image).asString(), MD5.create().update(out.toByteArray()).asString());
// Thread.sleep(25 * 60 * 1000);
server.close();
}
@Test
public void testCloseReadable() throws NoSuchAlgorithmException, KeyManagementException {
int port = 9090;
final AtomicInteger onClose = new AtomicInteger();
final AtomicInteger onCloseResource = new AtomicInteger();
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onDisconnect(Connection connection) {
onClose.incrementAndGet();
}
@Override
public void onConnect(Connection connection) {
byte[] data = ("HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Length: " + (1024 * 1024 * 1024) + "\r\nContent-Type: image/gif\r\n\r\n").getBytes();
connection.write(data, this); | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableData.java
// public abstract class ReadableData implements Closeable {
//
// public ByteBufferWrapper getByteBuffer(ByteBufferProvider bufferProvider) {
// return bufferProvider.getBuffer();
// }
//
// public void close() throws IOException {
// }
//
// public abstract int read(ByteBuffer byteBuffer);
//
// public int read(ByteBufferWrapper wrapper) {
// return read(wrapper.buffer());
// }
//
// public abstract void unread(int i);
//
// public abstract boolean isComplete();
//
// public abstract long complete();
//
// public abstract long length();
//
// public abstract long remains();
//
// public boolean hasOwnBuffer() {
// return false;
// }
//
// public void onComplete() {
// }
// }
// Path: src/test/java/com/wizzardo/epoll/SslServerTest.java
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.tools.http.*;
import com.wizzardo.tools.security.MD5;
import org.junit.Assert;
import org.junit.Test;
import javax.net.ssl.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
if (read >= image.length / 10) {
Thread.sleep(2000);
read = 0;
}
}
Assert.assertEquals(MD5.create().update(image).asString(), MD5.create().update(out.toByteArray()).asString());
// Thread.sleep(25 * 60 * 1000);
server.close();
}
@Test
public void testCloseReadable() throws NoSuchAlgorithmException, KeyManagementException {
int port = 9090;
final AtomicInteger onClose = new AtomicInteger();
final AtomicInteger onCloseResource = new AtomicInteger();
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onDisconnect(Connection connection) {
onClose.incrementAndGet();
}
@Override
public void onConnect(Connection connection) {
byte[] data = ("HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Length: " + (1024 * 1024 * 1024) + "\r\nContent-Type: image/gif\r\n\r\n").getBytes();
connection.write(data, this); | connection.write(new ReadableData() { |
wizzardo/epoll | src/test/java/com/wizzardo/epoll/EpollClientTest.java | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableByteArray.java
// public class ReadableByteArray extends ReadableData {
// protected byte[] bytes;
// protected int offset, length, position;
//
// public ReadableByteArray(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ReadableByteArray(byte[] bytes, int offset, int length) {
// this.bytes = bytes;
// this.offset = offset;
// this.length = length;
// position = offset;
// }
//
// @Override
// public int read(ByteBuffer byteBuffer) {
// int r = Math.min(byteBuffer.remaining(), length + offset - position);
// byteBuffer.put(bytes, position, r);
// position += r;
// return r;
// }
//
// @Override
// public void unread(int i) {
// if (i < 0)
// throw new IllegalArgumentException("can't unread negative value: " + i);
// if (position - i < offset)
// throw new IllegalArgumentException("can't unread value bigger than offset (" + offset + "): " + i);
// position -= i;
// }
//
// @Override
// public boolean isComplete() {
// return length == position - offset;
// }
//
// @Override
// public long complete() {
// return position - offset;
// }
//
// @Override
// public long length() {
// return length;
// }
//
// public long remains() {
// return length + offset - position;
// }
//
// @Override
// public String toString() {
// return new String(bytes, offset, length);
// }
// }
| import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.tools.misc.Unchecked;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger; | package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 5/5/14
*/
public class EpollClientTest {
// @Test
public void simpleTest() throws UnknownHostException {
final EpollCore epoll = new EpollCore<Connection>() {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onRead(Connection connection) {
System.out.println("onRead " + connection);
byte[] b = new byte[1024];
int r = 0;
try {
r = connection.read(b, 0, b.length, this);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println(new String(b, 0, r));
}
};
}
};
epoll.start();
Connection connection = Unchecked.call(new Callable<Connection>() {
@Override
public Connection call() throws Exception {
return epoll.connect("localhost", 8082);
}
}); | // Path: src/main/java/com/wizzardo/epoll/readable/ReadableByteArray.java
// public class ReadableByteArray extends ReadableData {
// protected byte[] bytes;
// protected int offset, length, position;
//
// public ReadableByteArray(byte[] bytes) {
// this(bytes, 0, bytes.length);
// }
//
// public ReadableByteArray(byte[] bytes, int offset, int length) {
// this.bytes = bytes;
// this.offset = offset;
// this.length = length;
// position = offset;
// }
//
// @Override
// public int read(ByteBuffer byteBuffer) {
// int r = Math.min(byteBuffer.remaining(), length + offset - position);
// byteBuffer.put(bytes, position, r);
// position += r;
// return r;
// }
//
// @Override
// public void unread(int i) {
// if (i < 0)
// throw new IllegalArgumentException("can't unread negative value: " + i);
// if (position - i < offset)
// throw new IllegalArgumentException("can't unread value bigger than offset (" + offset + "): " + i);
// position -= i;
// }
//
// @Override
// public boolean isComplete() {
// return length == position - offset;
// }
//
// @Override
// public long complete() {
// return position - offset;
// }
//
// @Override
// public long length() {
// return length;
// }
//
// public long remains() {
// return length + offset - position;
// }
//
// @Override
// public String toString() {
// return new String(bytes, offset, length);
// }
// }
// Path: src/test/java/com/wizzardo/epoll/EpollClientTest.java
import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.tools.misc.Unchecked;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
package com.wizzardo.epoll;
/**
* @author: wizzardo
* Date: 5/5/14
*/
public class EpollClientTest {
// @Test
public void simpleTest() throws UnknownHostException {
final EpollCore epoll = new EpollCore<Connection>() {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onRead(Connection connection) {
System.out.println("onRead " + connection);
byte[] b = new byte[1024];
int r = 0;
try {
r = connection.read(b, 0, b.length, this);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println(new String(b, 0, r));
}
};
}
};
epoll.start();
Connection connection = Unchecked.call(new Callable<Connection>() {
@Override
public Connection call() throws Exception {
return epoll.connect("localhost", 8082);
}
}); | connection.write(new ReadableByteArray(("GET /1 HTTP/1.1\r\n" + |
basilgregory/ONAM4Android | demo/src/main/java/com/basilgregory/onamsample/AddPostActivity.java | // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User; | package com.basilgregory.onamsample;
public class AddPostActivity extends AppCompatActivity {
EditText postTitle,postDescription;
Button savePost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_post);
connectViews();
}
private void connectViews(){
savePost = (Button) findViewById(R.id.savePost);
savePost.setOnClickListener(savePostClick);
postTitle = (EditText) findViewById(R.id.postTitle);
postDescription = (EditText) findViewById(R.id.postDescription);
}
View.OnClickListener savePostClick = new View.OnClickListener() {
@Override
public void onClick(View v) { | // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
// Path: demo/src/main/java/com/basilgregory/onamsample/AddPostActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
package com.basilgregory.onamsample;
public class AddPostActivity extends AppCompatActivity {
EditText postTitle,postDescription;
Button savePost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_post);
connectViews();
}
private void connectViews(){
savePost = (Button) findViewById(R.id.savePost);
savePost.setOnClickListener(savePostClick);
postTitle = (EditText) findViewById(R.id.postTitle);
postDescription = (EditText) findViewById(R.id.postDescription);
}
View.OnClickListener savePostClick = new View.OnClickListener() {
@Override
public void onClick(View v) { | Post post = new Post(); |
basilgregory/ONAM4Android | demo/src/main/java/com/basilgregory/onamsample/AddPostActivity.java | // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User; | package com.basilgregory.onamsample;
public class AddPostActivity extends AppCompatActivity {
EditText postTitle,postDescription;
Button savePost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_post);
connectViews();
}
private void connectViews(){
savePost = (Button) findViewById(R.id.savePost);
savePost.setOnClickListener(savePostClick);
postTitle = (EditText) findViewById(R.id.postTitle);
postDescription = (EditText) findViewById(R.id.postDescription);
}
View.OnClickListener savePostClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
Post post = new Post();
post.setTitle(postTitle.getText().toString());
post.setPost(postDescription.getText().toString());
| // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
// Path: demo/src/main/java/com/basilgregory/onamsample/AddPostActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
package com.basilgregory.onamsample;
public class AddPostActivity extends AppCompatActivity {
EditText postTitle,postDescription;
Button savePost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_post);
connectViews();
}
private void connectViews(){
savePost = (Button) findViewById(R.id.savePost);
savePost.setOnClickListener(savePostClick);
postTitle = (EditText) findViewById(R.id.postTitle);
postDescription = (EditText) findViewById(R.id.postDescription);
}
View.OnClickListener savePostClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
Post post = new Post();
post.setTitle(postTitle.getText().toString());
post.setPost(postDescription.getText().toString());
| User registeredUser = User.find(User.class,1); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/annotations/OneToOne.java | // Path: onam/src/main/java/com/basilgregory/onam/android/FetchType.java
// public interface FetchType {
// public static final short LAZY = 0;
// public static final short EAGER = 1;
// }
| import com.basilgregory.onam.android.FetchType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; | package com.basilgregory.onam.annotations;
/**
* Created by donpeter on 8/29/17.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface OneToOne { | // Path: onam/src/main/java/com/basilgregory/onam/android/FetchType.java
// public interface FetchType {
// public static final short LAZY = 0;
// public static final short EAGER = 1;
// }
// Path: onam/src/main/java/com/basilgregory/onam/annotations/OneToOne.java
import com.basilgregory.onam.android.FetchType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
package com.basilgregory.onam.annotations;
/**
* Created by donpeter on 8/29/17.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface OneToOne { | short fetchType() default FetchType.LAZY; |
basilgregory/ONAM4Android | demo/src/main/java/com/basilgregory/onamsample/AddCommentActivity.java | // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Comment.java
// @Table
// public class Comment extends Entity {
// private String comment;
// private long createdAt;
//
// private Post post;
// private User user;
//
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @ManyToOne
// @Column(name = "post_id")
// public Post getPost() {
// return fetch(this.post,new Post(){});
// }
//
// public void setPost(Post post) {
// this.post = post;
// }
//
// @ManyToOne
// @Column(name = "creator_id")
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// /**
// * You may create any number of @BeforeCreate functions and will be executed before actual insertion to the database
// * The order of execution of @BeforeCreate functions (incase of more than one) will be random.
// */
// @BeforeCreate
// public void settingTimeStamps(){
// createdAt = System.currentTimeMillis();
// }
//
// /**
// * You may create any number of #{{@link AfterCreate}} functions and will be executed before actual insertion to the
// * database
// * The order of execution of #{{@link AfterCreate}} functions (incase of more than one) will be random.
// */
// @AfterCreate
// public void afterCreate(){
// this.comment = "Comment: "+this.comment;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.basilgregory.onamsample.entities.Comment;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User; | package com.basilgregory.onamsample;
public class AddCommentActivity extends AppCompatActivity {
EditText comment;
Button saveComment; | // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Comment.java
// @Table
// public class Comment extends Entity {
// private String comment;
// private long createdAt;
//
// private Post post;
// private User user;
//
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @ManyToOne
// @Column(name = "post_id")
// public Post getPost() {
// return fetch(this.post,new Post(){});
// }
//
// public void setPost(Post post) {
// this.post = post;
// }
//
// @ManyToOne
// @Column(name = "creator_id")
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// /**
// * You may create any number of @BeforeCreate functions and will be executed before actual insertion to the database
// * The order of execution of @BeforeCreate functions (incase of more than one) will be random.
// */
// @BeforeCreate
// public void settingTimeStamps(){
// createdAt = System.currentTimeMillis();
// }
//
// /**
// * You may create any number of #{{@link AfterCreate}} functions and will be executed before actual insertion to the
// * database
// * The order of execution of #{{@link AfterCreate}} functions (incase of more than one) will be random.
// */
// @AfterCreate
// public void afterCreate(){
// this.comment = "Comment: "+this.comment;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
// Path: demo/src/main/java/com/basilgregory/onamsample/AddCommentActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.basilgregory.onamsample.entities.Comment;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
package com.basilgregory.onamsample;
public class AddCommentActivity extends AppCompatActivity {
EditText comment;
Button saveComment; | Post post; |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
| import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find; | package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex( | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java
import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find;
package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex( | getMappingForeignColumnNameClass(collectionType))); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
| import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find; | package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex(
getMappingForeignColumnNameClass(collectionType))); | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java
import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find;
package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex(
getMappingForeignColumnNameClass(collectionType))); | Entity queriedEntity = find(collectionType,foreignKey); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
| import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find; | package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex(
getMappingForeignColumnNameClass(collectionType)));
Entity queriedEntity = find(collectionType,foreignKey);
if (queriedEntity == null) continue;
entities.add(queriedEntity);
}while (cursor.moveToNext());
return entities;
}
private static Entity convertToEntity(Class<Entity> cls,Cursor cursor,Field[] fields,Entity entity){
for (Field field: fields) {
try {
if (Modifier.isTransient(field.getModifiers())) continue; //Transient field are already omitted from database. | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java
import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find;
package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex(
getMappingForeignColumnNameClass(collectionType)));
Entity queriedEntity = find(collectionType,foreignKey);
if (queriedEntity == null) continue;
entities.add(queriedEntity);
}while (cursor.moveToNext());
return entities;
}
private static Entity convertToEntity(Class<Entity> cls,Cursor cursor,Field[] fields,Entity entity){
for (Field field: fields) {
try {
if (Modifier.isTransient(field.getModifiers())) continue; //Transient field are already omitted from database. | String columnName = getColumnName(field); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
| import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find; | package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex(
getMappingForeignColumnNameClass(collectionType)));
Entity queriedEntity = find(collectionType,foreignKey);
if (queriedEntity == null) continue;
entities.add(queriedEntity);
}while (cursor.moveToNext());
return entities;
}
private static Entity convertToEntity(Class<Entity> cls,Cursor cursor,Field[] fields,Entity entity){
for (Field field: fields) {
try {
if (Modifier.isTransient(field.getModifiers())) continue; //Transient field are already omitted from database.
String columnName = getColumnName(field);
if (columnName == null) continue; //No getter functions found. Getter is mandatory
String firstParameterType = field.getType().getSimpleName().toUpperCase();
entity = entity == null ? cls.newInstance() : entity; | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Method getMethod (String prefix, Field field) {
// if (field == null) return null;
// String name = prefix + field.getName();
// try {
// switch (prefix.toLowerCase()) {
// case "set":
// return findSetterMethod(name,field.getDeclaringClass(), field.getType());
// case "get" :
// return findGetterMethod(name,field.getDeclaringClass());
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// L.w("No "+prefix +" method found for "+field.getName());
//
// return null;
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/Entity.java
// public static <E extends Entity> E find(Class entityClass,long id){
// return (E) DBExecutor.getInstance().findById(entityClass,id);
//
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/EntityBuilder.java
import android.database.Cursor;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
import static com.basilgregory.onam.android.DbUtil.getMethod;
import static com.basilgregory.onam.android.Entity.find;
package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/30/17.
*/
class EntityBuilder {
static List<Entity> getEntityFromMappingTable(Cursor cursor, Class collectionType){
if (cursor == null || cursor.getCount() < 1) return null;
cursor.moveToFirst();
List<Entity> entities = new ArrayList<>();
do{
long foreignKey = cursor.getLong
(cursor.getColumnIndex(
getMappingForeignColumnNameClass(collectionType)));
Entity queriedEntity = find(collectionType,foreignKey);
if (queriedEntity == null) continue;
entities.add(queriedEntity);
}while (cursor.moveToNext());
return entities;
}
private static Entity convertToEntity(Class<Entity> cls,Cursor cursor,Field[] fields,Entity entity){
for (Field field: fields) {
try {
if (Modifier.isTransient(field.getModifiers())) continue; //Transient field are already omitted from database.
String columnName = getColumnName(field);
if (columnName == null) continue; //No getter functions found. Getter is mandatory
String firstParameterType = field.getType().getSimpleName().toUpperCase();
entity = entity == null ? cls.newInstance() : entity; | Method setter= getMethod("set", field); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/DDLBuilder.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getTableName(Entity entity){
// return getTableName((Class<Entity>)entity.getClass());
// }
| import com.basilgregory.onam.annotations.ManyToMany;
import com.basilgregory.onam.annotations.OneToMany;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getTableName; | package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/28/17.
*/
class DDLBuilder {
static String createMappingTables(String tableName,Class fromClass,Class targetClass){
StringBuffer ddlCreate = new StringBuffer();
//This pattern "table [] ( " is used in #{DbUtil.extractNameOfTableFromDdl} cross check when making a change.
ddlCreate.append("create table ").append(tableName).append(" ( ");
ddlCreate.append(DbUtil.getMappingForeignColumnNameClass(fromClass)).append(" integer,");
ddlCreate.append(DbUtil.getMappingForeignColumnNameClass(targetClass)).append(" integer");
ddlCreate.append(");");
return ddlCreate.toString();
}
static HashMap<String,String> createTables(List<Class> curatedClassList){
HashMap<String,String> ddls = new HashMap<String,String>(curatedClassList.size());
for(Class cls:curatedClassList) {
if (cls == null || cls.getAnnotation(Table.class) == null) continue; | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getTableName(Entity entity){
// return getTableName((Class<Entity>)entity.getClass());
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/DDLBuilder.java
import com.basilgregory.onam.annotations.ManyToMany;
import com.basilgregory.onam.annotations.OneToMany;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.List;
import static com.basilgregory.onam.android.DbUtil.getTableName;
package com.basilgregory.onam.android;
/**
* Created by donpeter on 8/28/17.
*/
class DDLBuilder {
static String createMappingTables(String tableName,Class fromClass,Class targetClass){
StringBuffer ddlCreate = new StringBuffer();
//This pattern "table [] ( " is used in #{DbUtil.extractNameOfTableFromDdl} cross check when making a change.
ddlCreate.append("create table ").append(tableName).append(" ( ");
ddlCreate.append(DbUtil.getMappingForeignColumnNameClass(fromClass)).append(" integer,");
ddlCreate.append(DbUtil.getMappingForeignColumnNameClass(targetClass)).append(" integer");
ddlCreate.append(");");
return ddlCreate.toString();
}
static HashMap<String,String> createTables(List<Class> curatedClassList){
HashMap<String,String> ddls = new HashMap<String,String>(curatedClassList.size());
for(Class cls:curatedClassList) {
if (cls == null || cls.getAnnotation(Table.class) == null) continue; | ddls.put(getTableName(cls),createTable(cls)); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/annotations/ManyToMany.java | // Path: onam/src/main/java/com/basilgregory/onam/android/FetchType.java
// public interface FetchType {
// public static final short LAZY = 0;
// public static final short EAGER = 1;
// }
| import com.basilgregory.onam.android.FetchType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; | package com.basilgregory.onam.annotations;
/**
* Created by donpeter on 9/1/17.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ManyToMany { | // Path: onam/src/main/java/com/basilgregory/onam/android/FetchType.java
// public interface FetchType {
// public static final short LAZY = 0;
// public static final short EAGER = 1;
// }
// Path: onam/src/main/java/com/basilgregory/onam/annotations/ManyToMany.java
import com.basilgregory.onam.android.FetchType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
package com.basilgregory.onam.annotations;
/**
* Created by donpeter on 9/1/17.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ManyToMany { | short fetchType() default FetchType.LAZY; |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/annotations/OneToMany.java | // Path: onam/src/main/java/com/basilgregory/onam/android/FetchType.java
// public interface FetchType {
// public static final short LAZY = 0;
// public static final short EAGER = 1;
// }
| import com.basilgregory.onam.android.FetchType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; | package com.basilgregory.onam.annotations;
/**
* Created by donpeter on 9/1/17.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface OneToMany{ | // Path: onam/src/main/java/com/basilgregory/onam/android/FetchType.java
// public interface FetchType {
// public static final short LAZY = 0;
// public static final short EAGER = 1;
// }
// Path: onam/src/main/java/com/basilgregory/onam/annotations/OneToMany.java
import com.basilgregory.onam.android.FetchType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
package com.basilgregory.onam.annotations;
/**
* Created by donpeter on 9/1/17.
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface OneToMany{ | short fetchType() default FetchType.LAZY; |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/QueryBuilder.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Object invokeGetter(Field field, Entity entity){
// try {
// Method method = getMethod("get",field);
// if (method == null) return null;
// return method.invoke(entity);
// } catch (Exception e) {
// L.w("invoking getter "+field.getName()+" failed in entity "+entity.getClass().getSimpleName());
// L.e("invoking getter failed "+e.getLocalizedMessage());
// }
// return null;
// }
| import android.content.ContentValues;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import static com.basilgregory.onam.android.DbUtil.invokeGetter; | String rawQuery = "SELECT :columnName FROM :table WHERE "+DB.PRIMARY_KEY_ID+" = :id Limit 1";
return rawQuery
.replace(":columnName",columnName)
.replaceFirst(":table",DbUtil.getTableName(cls))
.replaceFirst(":id",String.valueOf(id));
}
static String selectQuery(String tableName,String whereClause,String groupBy,String orderBy,Integer startIndex, Integer pageSize){
if (tableName == null) return null;
whereClause = whereClause == null? "" : " where "+ whereClause;
groupBy = groupBy == null? "" : " group by "+ groupBy;
orderBy = orderBy == null? "" : " order by "+orderBy;
StringBuffer selectQuery = new StringBuffer("select * from ").append(tableName)
.append(whereClause).append(groupBy).append(orderBy);
if (pageSize != null)
selectQuery.append(" LIMIT ").append(startIndex == null? 0 : startIndex).append(",").append(pageSize);
selectQuery.append(";");
return selectQuery.toString();
}
static ContentValues insertContentValues(Entity entity, Entity parentEntity){
ContentValues contentValues = new ContentValues();
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field: fields) {
try {
if (Modifier.isTransient(field.getModifiers())) continue; //Transient field are already omitted from database.
if (field.getType().getAnnotation(Table.class) != null) {
String columnName = DbUtil.getColumnName(field);
if (columnName == null) continue; | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static Object invokeGetter(Field field, Entity entity){
// try {
// Method method = getMethod("get",field);
// if (method == null) return null;
// return method.invoke(entity);
// } catch (Exception e) {
// L.w("invoking getter "+field.getName()+" failed in entity "+entity.getClass().getSimpleName());
// L.e("invoking getter failed "+e.getLocalizedMessage());
// }
// return null;
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/QueryBuilder.java
import android.content.ContentValues;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import static com.basilgregory.onam.android.DbUtil.invokeGetter;
String rawQuery = "SELECT :columnName FROM :table WHERE "+DB.PRIMARY_KEY_ID+" = :id Limit 1";
return rawQuery
.replace(":columnName",columnName)
.replaceFirst(":table",DbUtil.getTableName(cls))
.replaceFirst(":id",String.valueOf(id));
}
static String selectQuery(String tableName,String whereClause,String groupBy,String orderBy,Integer startIndex, Integer pageSize){
if (tableName == null) return null;
whereClause = whereClause == null? "" : " where "+ whereClause;
groupBy = groupBy == null? "" : " group by "+ groupBy;
orderBy = orderBy == null? "" : " order by "+orderBy;
StringBuffer selectQuery = new StringBuffer("select * from ").append(tableName)
.append(whereClause).append(groupBy).append(orderBy);
if (pageSize != null)
selectQuery.append(" LIMIT ").append(startIndex == null? 0 : startIndex).append(",").append(pageSize);
selectQuery.append(";");
return selectQuery.toString();
}
static ContentValues insertContentValues(Entity entity, Entity parentEntity){
ContentValues contentValues = new ContentValues();
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field: fields) {
try {
if (Modifier.isTransient(field.getModifiers())) continue; //Transient field are already omitted from database.
if (field.getType().getAnnotation(Table.class) != null) {
String columnName = DbUtil.getColumnName(field);
if (columnName == null) continue; | Object relatedEntity = DbUtil.invokeGetter(field,entity); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/DBExecutor.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.basilgregory.onam.annotations.AfterCreate;
import com.basilgregory.onam.annotations.AfterUpdate;
import com.basilgregory.onam.annotations.BeforeCreate;
import com.basilgregory.onam.annotations.BeforeUpdate;
import com.basilgregory.onam.annotations.ManyToMany;
import com.basilgregory.onam.annotations.OneToMany;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass; | public static DBExecutor getInstance() {
return instance;
}
public static void init(Context context, Object o) {
if (o.getClass().getAnnotation(com.basilgregory.onam.annotations.DB.class) == null) return;
getInstance(context, o.getClass().getAnnotation(com.basilgregory.onam.annotations.DB.class).name(),
o.getClass().getAnnotation(com.basilgregory.onam.annotations.DB.class).version())
.createTables(context, o);
}
private DBExecutor(Context context, String dbName, int version) {
super(context, dbName, null, version);
this.dbName = dbName;
}
@Override
public void onCreate(SQLiteDatabase database) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//endregion
//Interface methods used by Entity.java
Entity findRelatedEntityByMapping(Entity entity, Method method) {
L.v("executing method "+method.getName()+" in entity "+entity.getClass().getSimpleName()); | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/DBExecutor.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.basilgregory.onam.annotations.AfterCreate;
import com.basilgregory.onam.annotations.AfterUpdate;
import com.basilgregory.onam.annotations.BeforeCreate;
import com.basilgregory.onam.annotations.BeforeUpdate;
import com.basilgregory.onam.annotations.ManyToMany;
import com.basilgregory.onam.annotations.OneToMany;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
public static DBExecutor getInstance() {
return instance;
}
public static void init(Context context, Object o) {
if (o.getClass().getAnnotation(com.basilgregory.onam.annotations.DB.class) == null) return;
getInstance(context, o.getClass().getAnnotation(com.basilgregory.onam.annotations.DB.class).name(),
o.getClass().getAnnotation(com.basilgregory.onam.annotations.DB.class).version())
.createTables(context, o);
}
private DBExecutor(Context context, String dbName, int version) {
super(context, dbName, null, version);
this.dbName = dbName;
}
@Override
public void onCreate(SQLiteDatabase database) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//endregion
//Interface methods used by Entity.java
Entity findRelatedEntityByMapping(Entity entity, Method method) {
L.v("executing method "+method.getName()+" in entity "+entity.getClass().getSimpleName()); | String foreignKeyColumn = getColumnName(method); |
basilgregory/ONAM4Android | onam/src/main/java/com/basilgregory/onam/android/DBExecutor.java | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.basilgregory.onam.annotations.AfterCreate;
import com.basilgregory.onam.annotations.AfterUpdate;
import com.basilgregory.onam.annotations.BeforeCreate;
import com.basilgregory.onam.annotations.BeforeUpdate;
import com.basilgregory.onam.annotations.ManyToMany;
import com.basilgregory.onam.annotations.OneToMany;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass; |
List<Entity> findAllWithOrderBy(Class<Entity> cls, String whereClause, String orderByColumn,boolean descending, Integer startIndex, Integer pageSize) {
return convertToEntityAndFetchFirstDegreeRelatedEntity(getReadableDatabase().rawQuery
(QueryBuilder.findAll(cls, whereClause,orderByColumn,descending, startIndex, pageSize), null)
,cls);
}
// Private methods
private List<Entity> findOneToManyRelatedEntities(Entity entity, Object holderClass
,OneToMany oneToMany,Method method ) {
Class collectionType = holderClass.getClass().getSuperclass();
List<Entity> entities = findByProperty(collectionType,
DbUtil.getReferencedColumnName(oneToMany,entity.getClass()),entity.getId(),null,null);
DbUtil.invokeSetter(entity,DbUtil.getSetterMethod(method),entities);
return entities;
}
/**
* Mapping table name has to be provided by the user.
* Foreignkey column names will be auto generated using #{getMappingForeignColumnNameClass}.
* @param entity
* @param holderClass
* @param method
* @return
*/
private List<Entity> findManyToManyRelatedEntities(ManyToMany manyToMany,Entity entity, Object holderClass
, Method method ) {
Cursor cursor = findByProperty(manyToMany.tableName(), | // Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getColumnName(Field field){
// return getColumnName(getMethod("get", field));
// }
//
// Path: onam/src/main/java/com/basilgregory/onam/android/DbUtil.java
// static String getMappingForeignColumnNameClass(Class aClass){
// return aClass.getSimpleName().toLowerCase()+"_id";
// }
// Path: onam/src/main/java/com/basilgregory/onam/android/DBExecutor.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.basilgregory.onam.annotations.AfterCreate;
import com.basilgregory.onam.annotations.AfterUpdate;
import com.basilgregory.onam.annotations.BeforeCreate;
import com.basilgregory.onam.annotations.BeforeUpdate;
import com.basilgregory.onam.annotations.ManyToMany;
import com.basilgregory.onam.annotations.OneToMany;
import com.basilgregory.onam.annotations.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.basilgregory.onam.android.DbUtil.getColumnName;
import static com.basilgregory.onam.android.DbUtil.getMappingForeignColumnNameClass;
List<Entity> findAllWithOrderBy(Class<Entity> cls, String whereClause, String orderByColumn,boolean descending, Integer startIndex, Integer pageSize) {
return convertToEntityAndFetchFirstDegreeRelatedEntity(getReadableDatabase().rawQuery
(QueryBuilder.findAll(cls, whereClause,orderByColumn,descending, startIndex, pageSize), null)
,cls);
}
// Private methods
private List<Entity> findOneToManyRelatedEntities(Entity entity, Object holderClass
,OneToMany oneToMany,Method method ) {
Class collectionType = holderClass.getClass().getSuperclass();
List<Entity> entities = findByProperty(collectionType,
DbUtil.getReferencedColumnName(oneToMany,entity.getClass()),entity.getId(),null,null);
DbUtil.invokeSetter(entity,DbUtil.getSetterMethod(method),entities);
return entities;
}
/**
* Mapping table name has to be provided by the user.
* Foreignkey column names will be auto generated using #{getMappingForeignColumnNameClass}.
* @param entity
* @param holderClass
* @param method
* @return
*/
private List<Entity> findManyToManyRelatedEntities(ManyToMany manyToMany,Entity entity, Object holderClass
, Method method ) {
Cursor cursor = findByProperty(manyToMany.tableName(), | getMappingForeignColumnNameClass(entity.getClass()),entity.getId(),null,null); |
basilgregory/ONAM4Android | demo/src/main/java/com/basilgregory/onamsample/views/PostView.java | // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Comment.java
// @Table
// public class Comment extends Entity {
// private String comment;
// private long createdAt;
//
// private Post post;
// private User user;
//
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @ManyToOne
// @Column(name = "post_id")
// public Post getPost() {
// return fetch(this.post,new Post(){});
// }
//
// public void setPost(Post post) {
// this.post = post;
// }
//
// @ManyToOne
// @Column(name = "creator_id")
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// /**
// * You may create any number of @BeforeCreate functions and will be executed before actual insertion to the database
// * The order of execution of @BeforeCreate functions (incase of more than one) will be random.
// */
// @BeforeCreate
// public void settingTimeStamps(){
// createdAt = System.currentTimeMillis();
// }
//
// /**
// * You may create any number of #{{@link AfterCreate}} functions and will be executed before actual insertion to the
// * database
// * The order of execution of #{{@link AfterCreate}} functions (incase of more than one) will be random.
// */
// @AfterCreate
// public void afterCreate(){
// this.comment = "Comment: "+this.comment;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
| import com.basilgregory.onam.annotations.Json;
import com.basilgregory.onamsample.entities.Comment;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
import java.util.List; | package com.basilgregory.onamsample.views;
/**
* Created by donpeter on 10/5/17.
*/
public class PostView {
private Post post;
public PostView(Post post) {
this.post = post;
}
@Json(fieldName = "title")
public String getTitle() {
return post.getTitle();
}
@Json(fieldName = "created_at")
public long getCreatedAt() {
return post.getCreatedAt();
}
| // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Comment.java
// @Table
// public class Comment extends Entity {
// private String comment;
// private long createdAt;
//
// private Post post;
// private User user;
//
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @ManyToOne
// @Column(name = "post_id")
// public Post getPost() {
// return fetch(this.post,new Post(){});
// }
//
// public void setPost(Post post) {
// this.post = post;
// }
//
// @ManyToOne
// @Column(name = "creator_id")
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// /**
// * You may create any number of @BeforeCreate functions and will be executed before actual insertion to the database
// * The order of execution of @BeforeCreate functions (incase of more than one) will be random.
// */
// @BeforeCreate
// public void settingTimeStamps(){
// createdAt = System.currentTimeMillis();
// }
//
// /**
// * You may create any number of #{{@link AfterCreate}} functions and will be executed before actual insertion to the
// * database
// * The order of execution of #{{@link AfterCreate}} functions (incase of more than one) will be random.
// */
// @AfterCreate
// public void afterCreate(){
// this.comment = "Comment: "+this.comment;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
// Path: demo/src/main/java/com/basilgregory/onamsample/views/PostView.java
import com.basilgregory.onam.annotations.Json;
import com.basilgregory.onamsample.entities.Comment;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
import java.util.List;
package com.basilgregory.onamsample.views;
/**
* Created by donpeter on 10/5/17.
*/
public class PostView {
private Post post;
public PostView(Post post) {
this.post = post;
}
@Json(fieldName = "title")
public String getTitle() {
return post.getTitle();
}
@Json(fieldName = "created_at")
public long getCreatedAt() {
return post.getCreatedAt();
}
| public List<Comment> getComments() { |
basilgregory/ONAM4Android | demo/src/main/java/com/basilgregory/onamsample/views/PostView.java | // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Comment.java
// @Table
// public class Comment extends Entity {
// private String comment;
// private long createdAt;
//
// private Post post;
// private User user;
//
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @ManyToOne
// @Column(name = "post_id")
// public Post getPost() {
// return fetch(this.post,new Post(){});
// }
//
// public void setPost(Post post) {
// this.post = post;
// }
//
// @ManyToOne
// @Column(name = "creator_id")
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// /**
// * You may create any number of @BeforeCreate functions and will be executed before actual insertion to the database
// * The order of execution of @BeforeCreate functions (incase of more than one) will be random.
// */
// @BeforeCreate
// public void settingTimeStamps(){
// createdAt = System.currentTimeMillis();
// }
//
// /**
// * You may create any number of #{{@link AfterCreate}} functions and will be executed before actual insertion to the
// * database
// * The order of execution of #{{@link AfterCreate}} functions (incase of more than one) will be random.
// */
// @AfterCreate
// public void afterCreate(){
// this.comment = "Comment: "+this.comment;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
| import com.basilgregory.onam.annotations.Json;
import com.basilgregory.onamsample.entities.Comment;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
import java.util.List; | package com.basilgregory.onamsample.views;
/**
* Created by donpeter on 10/5/17.
*/
public class PostView {
private Post post;
public PostView(Post post) {
this.post = post;
}
@Json(fieldName = "title")
public String getTitle() {
return post.getTitle();
}
@Json(fieldName = "created_at")
public long getCreatedAt() {
return post.getCreatedAt();
}
public List<Comment> getComments() {
return post.getComments();
}
| // Path: demo/src/main/java/com/basilgregory/onamsample/entities/Comment.java
// @Table
// public class Comment extends Entity {
// private String comment;
// private long createdAt;
//
// private Post post;
// private User user;
//
//
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
//
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @ManyToOne
// @Column(name = "post_id")
// public Post getPost() {
// return fetch(this.post,new Post(){});
// }
//
// public void setPost(Post post) {
// this.post = post;
// }
//
// @ManyToOne
// @Column(name = "creator_id")
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// /**
// * You may create any number of @BeforeCreate functions and will be executed before actual insertion to the database
// * The order of execution of @BeforeCreate functions (incase of more than one) will be random.
// */
// @BeforeCreate
// public void settingTimeStamps(){
// createdAt = System.currentTimeMillis();
// }
//
// /**
// * You may create any number of #{{@link AfterCreate}} functions and will be executed before actual insertion to the
// * database
// * The order of execution of #{{@link AfterCreate}} functions (incase of more than one) will be random.
// */
// @AfterCreate
// public void afterCreate(){
// this.comment = "Comment: "+this.comment;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/Post.java
// @Table
// public class Post extends Entity {
// private String title;
// private Object post;
//
// //If you need to include a property that is not be inserted/updated to database then you have to specify the modifier transient
// private transient String transientPost;
//
//
// private long createdAt;
//
// private List<User> followers;
//
// private List<Comment> comments;
// private User user;
//
// @Column(unique = true)
// @Json(fieldName = "title")
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// @Json(fieldName = "post")
// public Object getPost() {
// return post;
// }
//
// public void setPost(Object post) {
// this.post = post;
// }
//
// @Json(fieldName = "created_at")
// public long getCreatedAt() {
// return createdAt;
// }
//
// public void setCreatedAt(long createdAt) {
// this.createdAt = createdAt;
// }
//
// @OneToMany(referencedColumnName = "post_id", targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToOne
// public User getUser() {
// return fetch(this.user,new User(){});
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = User.class)
// public List<User> getFollowers() {
// return fetch(this.followers,new User(){});
// }
//
// public void setFollowers(List<User> followers) {
// this.followers = followers;
// }
//
// public String getTransientPost() {
// return transientPost;
// }
//
// public void setTransientPost(String transientPost) {
// this.transientPost = transientPost;
// }
// }
//
// Path: demo/src/main/java/com/basilgregory/onamsample/entities/User.java
// @Table
// public class User extends Entity {
// private String name;
// private String bio;
//
//
// private List<Post> followedPosts;
// private List<Post> posts;
// private List<Comment> comments;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getBio() {
// return bio;
// }
//
// public void setBio(String bio) {
// this.bio = bio;
// }
//
// @OneToMany(targetEntity = Post.class)
// public List<Post> getPosts() {
// return fetch(this.posts,new Post(){});
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
//
// @OneToMany(targetEntity = Comment.class)
// public List<Comment> getComments() {
// return fetch(this.comments,new Comment(){});
// }
//
// public void setComments(List<Comment> comments) {
// this.comments = comments;
// }
//
// @ManyToMany(tableName = "post_followers", targetEntity = Post.class)
// public List<Post> getFollowedPosts() {
// return fetch(this.followedPosts,new Post(){});
// }
//
// public void setFollowedPosts(List<Post> followedPosts) {
// this.followedPosts = followedPosts;
// }
// }
// Path: demo/src/main/java/com/basilgregory/onamsample/views/PostView.java
import com.basilgregory.onam.annotations.Json;
import com.basilgregory.onamsample.entities.Comment;
import com.basilgregory.onamsample.entities.Post;
import com.basilgregory.onamsample.entities.User;
import java.util.List;
package com.basilgregory.onamsample.views;
/**
* Created by donpeter on 10/5/17.
*/
public class PostView {
private Post post;
public PostView(Post post) {
this.post = post;
}
@Json(fieldName = "title")
public String getTitle() {
return post.getTitle();
}
@Json(fieldName = "created_at")
public long getCreatedAt() {
return post.getCreatedAt();
}
public List<Comment> getComments() {
return post.getComments();
}
| public User getUser() { |
astrapi69/jgeohash | jgeohash-core/src/test/java/de/alpharogroup/jgeohash/distance/DistancePointTest.java | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/Point.java
// @EqualsAndHashCode
// @Builder(toBuilder = true)
// public class Point implements Comparable<Point>, Cloneable, Position
// {
//
// /**
// * The serialVersionUID.
// */
// private static final long serialVersionUID = -4799959551221362673L;
//
// /** The latitude. */
// private double latitude;
//
// /** The longitude. */
// private double longitude;
//
// /**
// * Instantiates a new {@link Point} object.
// *
// * @param latitude
// * the latitude
// * @param longitude
// * the longitude
// */
// public Point(final double latitude, final double longitude)
// {
// if (Math.abs(latitude) > 90 || Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates " + this.toString() + " are out of range.");
// }
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object clone()
// {
// final Position inst = new Point(this.latitude, this.longitude);
// return inst;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int compareTo(final Point other)
// {
// if (this == other)
// {
// return 0;
// }
// if (this.latitude < other.latitude)
// {
// return -1;
// }
// if (this.latitude > other.latitude)
// {
// return 1;
// }
// if (this.longitude < other.longitude)
// {
// return -1;
// }
// if (this.longitude > other.longitude)
// {
// return 1;
// }
// // all comparisons have yielded equality
// // verify that compareTo is consistent with equals (optional)
// assert this.equals(other) : "compareTo inconsistent with equals.";
// return 0;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLatitude()
// {
// return latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLongitude()
// {
// return longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLatitude(final double latitude)
// {
// if (Math.abs(latitude) > 90)
// {
// throw new IllegalArgumentException(
// "The given coordinates for latitude " + latitude + " are out of range.");
// }
// this.latitude = latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLongitude(final double longitude)
// {
// if (Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates for longitude " + longitude + " are out of range.");
// }
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString()
// {
// return "Latitude : " + latitude + " Longitude : " + longitude;
// }
//
// }
//
// Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
| import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNotSame;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.Test;
import de.alpharogroup.evaluate.object.evaluators.EqualsEvaluator;
import de.alpharogroup.evaluate.object.evaluators.HashcodeEvaluator;
import de.alpharogroup.evaluate.object.evaluators.ToStringEvaluator;
import de.alpharogroup.jgeohash.Point;
import de.alpharogroup.jgeohash.api.Position; | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash.distance;
/**
* The unit test class for the class {@link DistancePoint}.
*/
public class DistancePointTest
{
/**
* Test method for {@link DistancePoint#compareTo(DistancePoint)}
*/
@Test
public void testCompareTo()
{
boolean expected;
int actual; | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/Point.java
// @EqualsAndHashCode
// @Builder(toBuilder = true)
// public class Point implements Comparable<Point>, Cloneable, Position
// {
//
// /**
// * The serialVersionUID.
// */
// private static final long serialVersionUID = -4799959551221362673L;
//
// /** The latitude. */
// private double latitude;
//
// /** The longitude. */
// private double longitude;
//
// /**
// * Instantiates a new {@link Point} object.
// *
// * @param latitude
// * the latitude
// * @param longitude
// * the longitude
// */
// public Point(final double latitude, final double longitude)
// {
// if (Math.abs(latitude) > 90 || Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates " + this.toString() + " are out of range.");
// }
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object clone()
// {
// final Position inst = new Point(this.latitude, this.longitude);
// return inst;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int compareTo(final Point other)
// {
// if (this == other)
// {
// return 0;
// }
// if (this.latitude < other.latitude)
// {
// return -1;
// }
// if (this.latitude > other.latitude)
// {
// return 1;
// }
// if (this.longitude < other.longitude)
// {
// return -1;
// }
// if (this.longitude > other.longitude)
// {
// return 1;
// }
// // all comparisons have yielded equality
// // verify that compareTo is consistent with equals (optional)
// assert this.equals(other) : "compareTo inconsistent with equals.";
// return 0;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLatitude()
// {
// return latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLongitude()
// {
// return longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLatitude(final double latitude)
// {
// if (Math.abs(latitude) > 90)
// {
// throw new IllegalArgumentException(
// "The given coordinates for latitude " + latitude + " are out of range.");
// }
// this.latitude = latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLongitude(final double longitude)
// {
// if (Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates for longitude " + longitude + " are out of range.");
// }
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString()
// {
// return "Latitude : " + latitude + " Longitude : " + longitude;
// }
//
// }
//
// Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
// Path: jgeohash-core/src/test/java/de/alpharogroup/jgeohash/distance/DistancePointTest.java
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNotSame;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.Test;
import de.alpharogroup.evaluate.object.evaluators.EqualsEvaluator;
import de.alpharogroup.evaluate.object.evaluators.HashcodeEvaluator;
import de.alpharogroup.evaluate.object.evaluators.ToStringEvaluator;
import de.alpharogroup.jgeohash.Point;
import de.alpharogroup.jgeohash.api.Position;
/**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash.distance;
/**
* The unit test class for the class {@link DistancePoint}.
*/
public class DistancePointTest
{
/**
* Test method for {@link DistancePoint#compareTo(DistancePoint)}
*/
@Test
public void testCompareTo()
{
boolean expected;
int actual; | Position point; |
astrapi69/jgeohash | jgeohash-core/src/test/java/de/alpharogroup/jgeohash/distance/DistancePointTest.java | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/Point.java
// @EqualsAndHashCode
// @Builder(toBuilder = true)
// public class Point implements Comparable<Point>, Cloneable, Position
// {
//
// /**
// * The serialVersionUID.
// */
// private static final long serialVersionUID = -4799959551221362673L;
//
// /** The latitude. */
// private double latitude;
//
// /** The longitude. */
// private double longitude;
//
// /**
// * Instantiates a new {@link Point} object.
// *
// * @param latitude
// * the latitude
// * @param longitude
// * the longitude
// */
// public Point(final double latitude, final double longitude)
// {
// if (Math.abs(latitude) > 90 || Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates " + this.toString() + " are out of range.");
// }
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object clone()
// {
// final Position inst = new Point(this.latitude, this.longitude);
// return inst;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int compareTo(final Point other)
// {
// if (this == other)
// {
// return 0;
// }
// if (this.latitude < other.latitude)
// {
// return -1;
// }
// if (this.latitude > other.latitude)
// {
// return 1;
// }
// if (this.longitude < other.longitude)
// {
// return -1;
// }
// if (this.longitude > other.longitude)
// {
// return 1;
// }
// // all comparisons have yielded equality
// // verify that compareTo is consistent with equals (optional)
// assert this.equals(other) : "compareTo inconsistent with equals.";
// return 0;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLatitude()
// {
// return latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLongitude()
// {
// return longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLatitude(final double latitude)
// {
// if (Math.abs(latitude) > 90)
// {
// throw new IllegalArgumentException(
// "The given coordinates for latitude " + latitude + " are out of range.");
// }
// this.latitude = latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLongitude(final double longitude)
// {
// if (Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates for longitude " + longitude + " are out of range.");
// }
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString()
// {
// return "Latitude : " + latitude + " Longitude : " + longitude;
// }
//
// }
//
// Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
| import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNotSame;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.Test;
import de.alpharogroup.evaluate.object.evaluators.EqualsEvaluator;
import de.alpharogroup.evaluate.object.evaluators.HashcodeEvaluator;
import de.alpharogroup.evaluate.object.evaluators.ToStringEvaluator;
import de.alpharogroup.jgeohash.Point;
import de.alpharogroup.jgeohash.api.Position; | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash.distance;
/**
* The unit test class for the class {@link DistancePoint}.
*/
public class DistancePointTest
{
/**
* Test method for {@link DistancePoint#compareTo(DistancePoint)}
*/
@Test
public void testCompareTo()
{
boolean expected;
int actual;
Position point;
Double distance;
| // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/Point.java
// @EqualsAndHashCode
// @Builder(toBuilder = true)
// public class Point implements Comparable<Point>, Cloneable, Position
// {
//
// /**
// * The serialVersionUID.
// */
// private static final long serialVersionUID = -4799959551221362673L;
//
// /** The latitude. */
// private double latitude;
//
// /** The longitude. */
// private double longitude;
//
// /**
// * Instantiates a new {@link Point} object.
// *
// * @param latitude
// * the latitude
// * @param longitude
// * the longitude
// */
// public Point(final double latitude, final double longitude)
// {
// if (Math.abs(latitude) > 90 || Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates " + this.toString() + " are out of range.");
// }
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Object clone()
// {
// final Position inst = new Point(this.latitude, this.longitude);
// return inst;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public int compareTo(final Point other)
// {
// if (this == other)
// {
// return 0;
// }
// if (this.latitude < other.latitude)
// {
// return -1;
// }
// if (this.latitude > other.latitude)
// {
// return 1;
// }
// if (this.longitude < other.longitude)
// {
// return -1;
// }
// if (this.longitude > other.longitude)
// {
// return 1;
// }
// // all comparisons have yielded equality
// // verify that compareTo is consistent with equals (optional)
// assert this.equals(other) : "compareTo inconsistent with equals.";
// return 0;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLatitude()
// {
// return latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public double getLongitude()
// {
// return longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLatitude(final double latitude)
// {
// if (Math.abs(latitude) > 90)
// {
// throw new IllegalArgumentException(
// "The given coordinates for latitude " + latitude + " are out of range.");
// }
// this.latitude = latitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public void setLongitude(final double longitude)
// {
// if (Math.abs(longitude) > 180)
// {
// throw new IllegalArgumentException(
// "The given coordinates for longitude " + longitude + " are out of range.");
// }
// this.longitude = longitude;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString()
// {
// return "Latitude : " + latitude + " Longitude : " + longitude;
// }
//
// }
//
// Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
// Path: jgeohash-core/src/test/java/de/alpharogroup/jgeohash/distance/DistancePointTest.java
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNotSame;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.Test;
import de.alpharogroup.evaluate.object.evaluators.EqualsEvaluator;
import de.alpharogroup.evaluate.object.evaluators.HashcodeEvaluator;
import de.alpharogroup.evaluate.object.evaluators.ToStringEvaluator;
import de.alpharogroup.jgeohash.Point;
import de.alpharogroup.jgeohash.api.Position;
/**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash.distance;
/**
* The unit test class for the class {@link DistancePoint}.
*/
public class DistancePointTest
{
/**
* Test method for {@link DistancePoint#compareTo(DistancePoint)}
*/
@Test
public void testCompareTo()
{
boolean expected;
int actual;
Position point;
Double distance;
| point = Point.builder().longitude(0.1d).latitude(20.0d).build(); |
astrapi69/jgeohash | jgeohash-core/src/main/java/de/alpharogroup/jgeohash/GeoHashPoint.java | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
| import java.math.BigDecimal;
import de.alpharogroup.jgeohash.api.Position;
import lombok.EqualsAndHashCode; | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash;
/**
* The class {@link GeoHashPoint}.
*/
@EqualsAndHashCode(callSuper = true)
public class GeoHashPoint extends Point
{
/** The Constant GEOHASH_KEY. */
public static final String GEOHASH_KEY = "GEOHASH_KEY";
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = -3580536765079661097L;
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param latitude
* the latitude
* @param longitude
* the longitude
*/
public GeoHashPoint(final double latitude, final double longitude)
{
super(latitude, longitude);
}
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param latitude
* the latitude
* @param longitude
* the longitude
*/
public GeoHashPoint(final Double latitude, final Double longitude)
{
super(latitude, longitude);
}
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param latitude
* the latitude
* @param longitude
* the longitude
*/
public GeoHashPoint(final float latitude, final float longitude)
{
this(Float.toString(latitude), Float.toString(longitude));
}
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param position
* the position
*/ | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
// Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/GeoHashPoint.java
import java.math.BigDecimal;
import de.alpharogroup.jgeohash.api.Position;
import lombok.EqualsAndHashCode;
/**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash;
/**
* The class {@link GeoHashPoint}.
*/
@EqualsAndHashCode(callSuper = true)
public class GeoHashPoint extends Point
{
/** The Constant GEOHASH_KEY. */
public static final String GEOHASH_KEY = "GEOHASH_KEY";
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = -3580536765079661097L;
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param latitude
* the latitude
* @param longitude
* the longitude
*/
public GeoHashPoint(final double latitude, final double longitude)
{
super(latitude, longitude);
}
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param latitude
* the latitude
* @param longitude
* the longitude
*/
public GeoHashPoint(final Double latitude, final Double longitude)
{
super(latitude, longitude);
}
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param latitude
* the latitude
* @param longitude
* the longitude
*/
public GeoHashPoint(final float latitude, final float longitude)
{
this(Float.toString(latitude), Float.toString(longitude));
}
/**
* Instantiates a new {@link GeoHashPoint}.
*
* @param position
* the position
*/ | public GeoHashPoint(final Position position) |
astrapi69/jgeohash | jgeohash-core/src/main/java/de/alpharogroup/jgeohash/Point.java | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
| import de.alpharogroup.jgeohash.api.Position;
import lombok.Builder;
import lombok.EqualsAndHashCode; | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash;
/**
* The class {@link Point} represents a point on earth with the latitude and longitude.
*/
@EqualsAndHashCode
@Builder(toBuilder = true) | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
// Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/Point.java
import de.alpharogroup.jgeohash.api.Position;
import lombok.Builder;
import lombok.EqualsAndHashCode;
/**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash;
/**
* The class {@link Point} represents a point on earth with the latitude and longitude.
*/
@EqualsAndHashCode
@Builder(toBuilder = true) | public class Point implements Comparable<Point>, Cloneable, Position |
astrapi69/jgeohash | jgeohash-core/src/main/java/de/alpharogroup/jgeohash/distance/DistancePoint.java | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
| import de.alpharogroup.jgeohash.api.Position;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString; | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash.distance;
/**
* The class {@link DistancePoint} is a pojo for holding a distance from one point. you can sort
* than the objects from the distance.
*/
@Getter
@EqualsAndHashCode
@ToString
@Builder(toBuilder = true)
public class DistancePoint implements Comparable<DistancePoint>
{
/** The distance. */
private final Double distance;
/** The position point. */ | // Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/api/Position.java
// public interface Position extends Serializable
// {
//
// /**
// * Gets the latitude.
// *
// * @return the latitude
// */
// double getLatitude();
//
// /**
// * Gets the longitude.
// *
// * @return the longitude
// */
// double getLongitude();
//
// /**
// * Sets the latitude.
// *
// * @param latitude
// * the new latitude
// */
// void setLatitude(final double latitude);
//
// /**
// * Sets the longitude.
// *
// * @param longitude
// * the new longitude
// */
// void setLongitude(final double longitude);
//
// }
// Path: jgeohash-core/src/main/java/de/alpharogroup/jgeohash/distance/DistancePoint.java
import de.alpharogroup.jgeohash.api.Position;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
/**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.jgeohash.distance;
/**
* The class {@link DistancePoint} is a pojo for holding a distance from one point. you can sort
* than the objects from the distance.
*/
@Getter
@EqualsAndHashCode
@ToString
@Builder(toBuilder = true)
public class DistancePoint implements Comparable<DistancePoint>
{
/** The distance. */
private final Double distance;
/** The position point. */ | private final Position point; |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/Control.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/ControlException.java
// public class ControlException extends V4L4JException{
//
// private static final long serialVersionUID = -8310718978974706151L;
//
// public ControlException(String message) {
// super(message);
// }
//
// public ControlException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public ControlException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
| import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.ControlException; | for(String s: names)
this.names.add(s);
}
this.values = values;
if(min<=0 && 0<=max)
this.defaultValue = 0;
else
this.defaultValue = (int) Math.round((max - min) / 2.0) + min;
v4l4jObject = o;
state = new State();
}
/**
* This method retrieves the current value of this control. Some controls
* (for example relative values like pan or tilt) are write-only and getting
* their value does not make sense. Invoking this method on this kind of
* controls will trigger a ControlException.
* @return the current value of this control (0 if it is a button)
* @throws ControlException if the value cannot be retrieved
* @throws UnsupportedMethod if this control is of type {@link V4L4JConstants#CTRL_TYPE_STRING}
* (and you should be using {@link #getStringValue()} instead) or
* if this control is of type {@link V4L4JConstants#CTRL_TYPE_LONG}
* (and you should be using {@link #setLongValue(long)} instead).
* @throws StateException if this control has been released and must not be used anymore.
*/
public int getValue() throws ControlException{
int v = 0;
if(type==V4L4JConstants.CTRL_TYPE_STRING) | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/ControlException.java
// public class ControlException extends V4L4JException{
//
// private static final long serialVersionUID = -8310718978974706151L;
//
// public ControlException(String message) {
// super(message);
// }
//
// public ControlException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public ControlException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/Control.java
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.ControlException;
for(String s: names)
this.names.add(s);
}
this.values = values;
if(min<=0 && 0<=max)
this.defaultValue = 0;
else
this.defaultValue = (int) Math.round((max - min) / 2.0) + min;
v4l4jObject = o;
state = new State();
}
/**
* This method retrieves the current value of this control. Some controls
* (for example relative values like pan or tilt) are write-only and getting
* their value does not make sense. Invoking this method on this kind of
* controls will trigger a ControlException.
* @return the current value of this control (0 if it is a button)
* @throws ControlException if the value cannot be retrieved
* @throws UnsupportedMethod if this control is of type {@link V4L4JConstants#CTRL_TYPE_STRING}
* (and you should be using {@link #getStringValue()} instead) or
* if this control is of type {@link V4L4JConstants#CTRL_TYPE_LONG}
* (and you should be using {@link #setLongValue(long)} instead).
* @throws StateException if this control has been released and must not be used anymore.
*/
public int getValue() throws ControlException{
int v = 0;
if(type==V4L4JConstants.CTRL_TYPE_STRING) | throw new UnsupportedMethod("This control is a string control and does not accept calls to getValue()"); |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/Control.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/ControlException.java
// public class ControlException extends V4L4JException{
//
// private static final long serialVersionUID = -8310718978974706151L;
//
// public ControlException(String message) {
// super(message);
// }
//
// public ControlException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public ControlException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
| import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.ControlException; | * when read can still have their value decrease()d
*/
state.get();
try { old = doGetValue(v4l4jObject,id);} catch (ControlException e) {}
try {old = doSetValue(v4l4jObject,id, validateValue(old-step));}
catch (ControlException ce){
state.put();
throw ce;
}
state.put();
return old;
}
/**
* This method retrieves the maximum value this control will accept.
* If this control is a string control, this method returns the maximum string
* size that can be set on this control.
*
* @return the maximum value, or the largest string size
* @throws StateException if this control has been released and must not be used anymore.
* @throws UnsupportedMethod if this control is of type {@link V4L4JConstants#CTRL_TYPE_LONG}
*/
public int getMaxValue() {
if(type==V4L4JConstants.CTRL_TYPE_LONG)
throw new UnsupportedMethod("This control is a long control and does not support calls to getMaxValue()");
synchronized(state){
if(state.isNotReleased())
return max;
else | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/ControlException.java
// public class ControlException extends V4L4JException{
//
// private static final long serialVersionUID = -8310718978974706151L;
//
// public ControlException(String message) {
// super(message);
// }
//
// public ControlException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public ControlException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/Control.java
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.ControlException;
* when read can still have their value decrease()d
*/
state.get();
try { old = doGetValue(v4l4jObject,id);} catch (ControlException e) {}
try {old = doSetValue(v4l4jObject,id, validateValue(old-step));}
catch (ControlException ce){
state.put();
throw ce;
}
state.put();
return old;
}
/**
* This method retrieves the maximum value this control will accept.
* If this control is a string control, this method returns the maximum string
* size that can be set on this control.
*
* @return the maximum value, or the largest string size
* @throws StateException if this control has been released and must not be used anymore.
* @throws UnsupportedMethod if this control is of type {@link V4L4JConstants#CTRL_TYPE_LONG}
*/
public int getMaxValue() {
if(type==V4L4JConstants.CTRL_TYPE_LONG)
throw new UnsupportedMethod("This control is a long control and does not support calls to getMaxValue()");
synchronized(state){
if(state.isNotReleased())
return max;
else | throw new StateException("This control has been released and must not be used"); |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/PushSource.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.concurrent.ThreadFactory;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException; | /*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* PushSource instances create their own thread which polls
* a frame grabber and notify the
* {@link CaptureCallback} object given in the constructor
* each time a new frame is available.
* @author gilles
*
*/
class PushSource implements Runnable {
private CaptureCallback callback;
private AbstractGrabber frameGrabber;
private Thread thread;
private ThreadFactory threadFactory;
private int state;
private static final int STATE_STOPPED = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_ABOUT_TO_STOP = 2;
/**
* This method builds a new <code>PushSource</code> instance
* which will obtain frames from the given frame grabber and
* pass them to the given callback object.
* @param grabber the {@link FrameGrabber} instance on which
* this push source will repeatedly call {@link FrameGrabber#getVideoFrame()}.
* @param callback an object implementing the {@link CaptureCallback}
* interface to which the frames will be delivered through the
* {@link CaptureCallback#nextFrame(VideoFrame)}.
*/
public PushSource(AbstractGrabber grabber, CaptureCallback callback, ThreadFactory factory) {
if ((grabber == null) || (callback == null))
throw new NullPointerException("the frame grabber and callback cannot be null");
this.callback = callback;
frameGrabber = grabber;
threadFactory = factory;
state = STATE_STOPPED;
}
/**
* This method instructs this source to start the capture and to push
* to the captured frame to the
* {@link CaptureCallback}.
* @throws StateException if the capture has already been started
*/ | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/PushSource.java
import java.util.concurrent.ThreadFactory;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException;
/*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* PushSource instances create their own thread which polls
* a frame grabber and notify the
* {@link CaptureCallback} object given in the constructor
* each time a new frame is available.
* @author gilles
*
*/
class PushSource implements Runnable {
private CaptureCallback callback;
private AbstractGrabber frameGrabber;
private Thread thread;
private ThreadFactory threadFactory;
private int state;
private static final int STATE_STOPPED = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_ABOUT_TO_STOP = 2;
/**
* This method builds a new <code>PushSource</code> instance
* which will obtain frames from the given frame grabber and
* pass them to the given callback object.
* @param grabber the {@link FrameGrabber} instance on which
* this push source will repeatedly call {@link FrameGrabber#getVideoFrame()}.
* @param callback an object implementing the {@link CaptureCallback}
* interface to which the frames will be delivered through the
* {@link CaptureCallback#nextFrame(VideoFrame)}.
*/
public PushSource(AbstractGrabber grabber, CaptureCallback callback, ThreadFactory factory) {
if ((grabber == null) || (callback == null))
throw new NullPointerException("the frame grabber and callback cannot be null");
this.callback = callback;
frameGrabber = grabber;
threadFactory = factory;
state = STATE_STOPPED;
}
/**
* This method instructs this source to start the capture and to push
* to the captured frame to the
* {@link CaptureCallback}.
* @throws StateException if the capture has already been started
*/ | public synchronized final long startCapture() throws V4L4JException{ |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/PushSource.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.concurrent.ThreadFactory;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException; | /*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* PushSource instances create their own thread which polls
* a frame grabber and notify the
* {@link CaptureCallback} object given in the constructor
* each time a new frame is available.
* @author gilles
*
*/
class PushSource implements Runnable {
private CaptureCallback callback;
private AbstractGrabber frameGrabber;
private Thread thread;
private ThreadFactory threadFactory;
private int state;
private static final int STATE_STOPPED = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_ABOUT_TO_STOP = 2;
/**
* This method builds a new <code>PushSource</code> instance
* which will obtain frames from the given frame grabber and
* pass them to the given callback object.
* @param grabber the {@link FrameGrabber} instance on which
* this push source will repeatedly call {@link FrameGrabber#getVideoFrame()}.
* @param callback an object implementing the {@link CaptureCallback}
* interface to which the frames will be delivered through the
* {@link CaptureCallback#nextFrame(VideoFrame)}.
*/
public PushSource(AbstractGrabber grabber, CaptureCallback callback, ThreadFactory factory) {
if ((grabber == null) || (callback == null))
throw new NullPointerException("the frame grabber and callback cannot be null");
this.callback = callback;
frameGrabber = grabber;
threadFactory = factory;
state = STATE_STOPPED;
}
/**
* This method instructs this source to start the capture and to push
* to the captured frame to the
* {@link CaptureCallback}.
* @throws StateException if the capture has already been started
*/
public synchronized final long startCapture() throws V4L4JException{
if (state != STATE_STOPPED) | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/PushSource.java
import java.util.concurrent.ThreadFactory;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException;
/*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* PushSource instances create their own thread which polls
* a frame grabber and notify the
* {@link CaptureCallback} object given in the constructor
* each time a new frame is available.
* @author gilles
*
*/
class PushSource implements Runnable {
private CaptureCallback callback;
private AbstractGrabber frameGrabber;
private Thread thread;
private ThreadFactory threadFactory;
private int state;
private static final int STATE_STOPPED = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_ABOUT_TO_STOP = 2;
/**
* This method builds a new <code>PushSource</code> instance
* which will obtain frames from the given frame grabber and
* pass them to the given callback object.
* @param grabber the {@link FrameGrabber} instance on which
* this push source will repeatedly call {@link FrameGrabber#getVideoFrame()}.
* @param callback an object implementing the {@link CaptureCallback}
* interface to which the frames will be delivered through the
* {@link CaptureCallback#nextFrame(VideoFrame)}.
*/
public PushSource(AbstractGrabber grabber, CaptureCallback callback, ThreadFactory factory) {
if ((grabber == null) || (callback == null))
throw new NullPointerException("the frame grabber and callback cannot be null");
this.callback = callback;
frameGrabber = grabber;
threadFactory = factory;
state = STATE_STOPPED;
}
/**
* This method instructs this source to start the capture and to push
* to the captured frame to the
* {@link CaptureCallback}.
* @throws StateException if the capture has already been started
*/
public synchronized final long startCapture() throws V4L4JException{
if (state != STATE_STOPPED) | throw new StateException("The capture has already been started"); |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/DeviceInfo.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException; | * could have its type set to {@link FrameInterval.Type#UNSUPPORTED} if the
* driver does not support frame interval enumeration OR if the device is
* currently being used by another application and frame intervals cannot
* be enumerated at this time.</b><br>Frame interval information can also
* be obtained through {@link ResolutionInfo} objects, attached to each
* {@link ImageFormat}. See {@link #getFormatList()}.
* @return a {@link FrameInterval} object containing information about
* the supported frame intervals
* @param imf the capture image format for which the frame intervals should
* be enumerated
* @param width the capture width for which the frame intervals should be
* enumerated
* @param height the capture height for which the frame intervals should be
* enumerated
* @throws StateException if the associated VideoDevice has been released
*/
public synchronized FrameInterval listIntervals(ImageFormat imf,
int width, int height){
checkRelease();
return doListIntervals(object, imf.getIndex(), width, height);
}
/**
* This constructor build a DeviceInfo object containing information about
* the given V4L device.
* @param object the JNI C pointer to struct v4l4j_device
* @throws V4L4JException if there is an error retrieving information from
* the video device.
*/ | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/DeviceInfo.java
import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException;
* could have its type set to {@link FrameInterval.Type#UNSUPPORTED} if the
* driver does not support frame interval enumeration OR if the device is
* currently being used by another application and frame intervals cannot
* be enumerated at this time.</b><br>Frame interval information can also
* be obtained through {@link ResolutionInfo} objects, attached to each
* {@link ImageFormat}. See {@link #getFormatList()}.
* @return a {@link FrameInterval} object containing information about
* the supported frame intervals
* @param imf the capture image format for which the frame intervals should
* be enumerated
* @param width the capture width for which the frame intervals should be
* enumerated
* @param height the capture height for which the frame intervals should be
* enumerated
* @throws StateException if the associated VideoDevice has been released
*/
public synchronized FrameInterval listIntervals(ImageFormat imf,
int width, int height){
checkRelease();
return doListIntervals(object, imf.getIndex(), width, height);
}
/**
* This constructor build a DeviceInfo object containing information about
* the given V4L device.
* @param object the JNI C pointer to struct v4l4j_device
* @throws V4L4JException if there is an error retrieving information from
* the video device.
*/ | DeviceInfo(long object, String dev) throws V4L4JException{ |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/DeviceInfo.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException; | return doListIntervals(object, imf.getIndex(), width, height);
}
/**
* This constructor build a DeviceInfo object containing information about
* the given V4L device.
* @param object the JNI C pointer to struct v4l4j_device
* @throws V4L4JException if there is an error retrieving information from
* the video device.
*/
DeviceInfo(long object, String dev) throws V4L4JException{
inputs = new Vector<InputInfo>();
deviceFile = dev;
getInfo(object);
this.object = object;
}
/**
* This method releases the libvideo query interface
*/
synchronized void release() {
doRelease(object);
}
/**
* checks if this object has been released (by the owning video device
* object). If yes, throws a {@link StateException}
* @throws StateException if this object has been released
*/ | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/DeviceInfo.java
import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.V4L4JException;
return doListIntervals(object, imf.getIndex(), width, height);
}
/**
* This constructor build a DeviceInfo object containing information about
* the given V4L device.
* @param object the JNI C pointer to struct v4l4j_device
* @throws V4L4JException if there is an error retrieving information from
* the video device.
*/
DeviceInfo(long object, String dev) throws V4L4JException{
inputs = new Vector<InputInfo>();
deviceFile = dev;
getInfo(object);
this.object = object;
}
/**
* This method releases the libvideo query interface
*/
synchronized void release() {
doRelease(object);
}
/**
* checks if this object has been released (by the owning video device
* object). If yes, throws a {@link StateException}
* @throws StateException if this object has been released
*/ | private void checkRelease() throws StateException{ |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/InputInfo.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/NoTunerException.java
// public class NoTunerException extends V4L4JException {
//
// private static final long serialVersionUID = -4596596557974047977L;
//
// public NoTunerException(String message) {
// super(message);
// }
//
// public NoTunerException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public NoTunerException(Throwable throwable) {
// super(throwable);
// }
//
// }
| import java.util.HashSet;
import java.util.Set;
import au.edu.jcu.v4l4j.exceptions.NoTunerException; | */
public String getName() {
return name;
}
/**
* This method returns the type of this input
* ({@link V4L4JConstants#INPUT_TYPE_TUNER} or {@link V4L4JConstants#INPUT_TYPE_CAMERA})
* @return the type of this input
*/
public short getType() {
return type;
}
/**
* This method returns the standards supported by this input
* ({@link V4L4JConstants#STANDARD_PAL}, {@link V4L4JConstants#STANDARD_SECAM},
* {@link V4L4JConstants#STANDARD_NTSC} or {@link V4L4JConstants#STANDARD_WEBCAM})
* @return the supportedStandards
*/
public Set<Integer> getSupportedStandards() {
return supportedStandards;
}
/**
* This method returns the {@link TunerInfo} associated with this input, if any.
* @return the tuner
* @throws NoTunerException if this input is of type
* {@link V4L4JConstants#INPUT_TYPE_CAMERA}, and is not a tuner.
*/ | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/NoTunerException.java
// public class NoTunerException extends V4L4JException {
//
// private static final long serialVersionUID = -4596596557974047977L;
//
// public NoTunerException(String message) {
// super(message);
// }
//
// public NoTunerException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public NoTunerException(Throwable throwable) {
// super(throwable);
// }
//
// }
// Path: src/main/java/au/edu/jcu/v4l4j/InputInfo.java
import java.util.HashSet;
import java.util.Set;
import au.edu.jcu.v4l4j.exceptions.NoTunerException;
*/
public String getName() {
return name;
}
/**
* This method returns the type of this input
* ({@link V4L4JConstants#INPUT_TYPE_TUNER} or {@link V4L4JConstants#INPUT_TYPE_CAMERA})
* @return the type of this input
*/
public short getType() {
return type;
}
/**
* This method returns the standards supported by this input
* ({@link V4L4JConstants#STANDARD_PAL}, {@link V4L4JConstants#STANDARD_SECAM},
* {@link V4L4JConstants#STANDARD_NTSC} or {@link V4L4JConstants#STANDARD_WEBCAM})
* @return the supportedStandards
*/
public Set<Integer> getSupportedStandards() {
return supportedStandards;
}
/**
* This method returns the {@link TunerInfo} associated with this input, if any.
* @return the tuner
* @throws NoTunerException if this input is of type
* {@link V4L4JConstants#INPUT_TYPE_CAMERA}, and is not a tuner.
*/ | public TunerInfo getTunerInfo() throws NoTunerException{ |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/TunerList.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException; | /*
* Copyright (C) 2007-2008 Gilles Gigan (gilles.gigan@gmail.com)
* eResearch Centre, James Cook University (eresearch.jcu.edu.au)
*
* This program was developed as part of the ARCHER project
* (Australian Research Enabling Environment) funded by a
* Systemic Infrastructure Initiative (SII) grant and supported by the Australian
* Department of Innovation, Industry, Science and Research
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* Objects of this class encapsulate a list of available {@link Tuner}s.
* This class can not be directly instantiated. Instead, to retrieve a list of
* tuners from a {@link VideoDevice}, use its
* {@link VideoDevice#getTunerList() getTunerList()} method.
* @author gilles
*
*/
public class TunerList {
private Vector<Tuner> tuners;
private boolean released;
/**
* This constructor builds a control list from the given list. (a copy of
* the list object is made).
* @param c the tuner list used to initialise this object.
*/
TunerList(List<Tuner> t){
tuners= new Vector<Tuner>(t);
released = false;
}
/**
* This method returns a copy of the tuner list.
* @return a copy of the tuner list.
* @throws StateException if this tuner list has been released and must
* not be used anymore
*/
public synchronized List<Tuner> getList(){
checkReleased();
return new Vector<Tuner>(tuners);
}
/**
* This method returns a tuner given its index.
* @return the tuner matching the given index, null otherwise
* @throws StateException if this tuner list has been released and must not
* be used anymore
* @throws ArrayIndexOutOfBoundsException if the given index is out of bounds
*/
public synchronized Tuner getTuner(int i){
checkReleased();
for(Tuner t: tuners)
if(t.getIndex()==i)
return t;
throw new ArrayIndexOutOfBoundsException("No tuner with such index");
}
/**
* This method released the tuner list, and all tuners in it.
*/
synchronized void release(){
released = true;
for(Tuner t: tuners)
t.release();
}
private void checkReleased(){
if(released) | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/TunerList.java
import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException;
/*
* Copyright (C) 2007-2008 Gilles Gigan (gilles.gigan@gmail.com)
* eResearch Centre, James Cook University (eresearch.jcu.edu.au)
*
* This program was developed as part of the ARCHER project
* (Australian Research Enabling Environment) funded by a
* Systemic Infrastructure Initiative (SII) grant and supported by the Australian
* Department of Innovation, Industry, Science and Research
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* Objects of this class encapsulate a list of available {@link Tuner}s.
* This class can not be directly instantiated. Instead, to retrieve a list of
* tuners from a {@link VideoDevice}, use its
* {@link VideoDevice#getTunerList() getTunerList()} method.
* @author gilles
*
*/
public class TunerList {
private Vector<Tuner> tuners;
private boolean released;
/**
* This constructor builds a control list from the given list. (a copy of
* the list object is made).
* @param c the tuner list used to initialise this object.
*/
TunerList(List<Tuner> t){
tuners= new Vector<Tuner>(t);
released = false;
}
/**
* This method returns a copy of the tuner list.
* @return a copy of the tuner list.
* @throws StateException if this tuner list has been released and must
* not be used anymore
*/
public synchronized List<Tuner> getList(){
checkReleased();
return new Vector<Tuner>(tuners);
}
/**
* This method returns a tuner given its index.
* @return the tuner matching the given index, null otherwise
* @throws StateException if this tuner list has been released and must not
* be used anymore
* @throws ArrayIndexOutOfBoundsException if the given index is out of bounds
*/
public synchronized Tuner getTuner(int i){
checkReleased();
for(Tuner t: tuners)
if(t.getIndex()==i)
return t;
throw new ArrayIndexOutOfBoundsException("No tuner with such index");
}
/**
* This method released the tuner list, and all tuners in it.
*/
synchronized void release(){
released = true;
for(Tuner t: tuners)
t.release();
}
private void checkReleased(){
if(released) | throw new StateException("The tuner list has been released and " + |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/JPEGVideoFrame.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
| import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod; | /*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* Instances of this class encapsulate image data for a JPEG compressed
* image. They will not generate a {@link Raster} as rasters only support
* uncompressed format. They do support however creation of {@link BufferedImage}s.
* @author gilles
*
*/
class JPEGVideoFrame extends BaseVideoFrame {
JPEGVideoFrame(AbstractGrabber grabber, int bufferSize) {
super(grabber, bufferSize);
}
@Override
protected WritableRaster refreshRaster() { | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/JPEGVideoFrame.java
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
/*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* Instances of this class encapsulate image data for a JPEG compressed
* image. They will not generate a {@link Raster} as rasters only support
* uncompressed format. They do support however creation of {@link BufferedImage}s.
* @author gilles
*
*/
class JPEGVideoFrame extends BaseVideoFrame {
JPEGVideoFrame(AbstractGrabber grabber, int bufferSize) {
super(grabber, bufferSize);
}
@Override
protected WritableRaster refreshRaster() { | throw new UnsupportedMethod("A raster cannot be generated for a JPEG frame"); |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/ResolutionInfo.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod; | return;
}
if(t==0)
type = Type.UNSUPPORTED;
else if(t==1){
type = Type.DISCRETE;
} else {
type = Type.STEPWISE;
}
}
/**
* This method returns the resolution information type. See {@link Type}
* enumeration.
* @return the resolution information type. See {@link Type}.
*/
public Type getType(){
return type;
}
/**
* This method returns a list of {@link DiscreteResolution}s, or throws a
* {@link UnsupportedMethod} exception if this resolution info object
* is not of type {@link Type#DISCRETE}.
* @return a list of {@link DiscreteResolution}s
* @throws UnsupportedMethod if this resolution info object
* is not of type {@link Type#DISCRETE}.
*/
public List<DiscreteResolution> getDiscreteResolutions() | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/ResolutionInfo.java
import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
return;
}
if(t==0)
type = Type.UNSUPPORTED;
else if(t==1){
type = Type.DISCRETE;
} else {
type = Type.STEPWISE;
}
}
/**
* This method returns the resolution information type. See {@link Type}
* enumeration.
* @return the resolution information type. See {@link Type}.
*/
public Type getType(){
return type;
}
/**
* This method returns a list of {@link DiscreteResolution}s, or throws a
* {@link UnsupportedMethod} exception if this resolution info object
* is not of type {@link Type#DISCRETE}.
* @return a list of {@link DiscreteResolution}s
* @throws UnsupportedMethod if this resolution info object
* is not of type {@link Type#DISCRETE}.
*/
public List<DiscreteResolution> getDiscreteResolutions() | throws UnsupportedMethod{ |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/ControlList.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException; | * This method returns a list of {@link Control}s
* @return a list of {@link Control}s
* @throws StateException if this control list has been released and must not be used anymore
*/
public synchronized List<Control> getList(){
checkReleased();
return new Vector<Control>(controls.values());
}
/**
* This method returns a control given its name.
* @return the control matching the given name, null otherwise
* @throws StateException if this control list has been released and must not be used anymore
*/
public synchronized Control getControl(String n){
checkReleased();
return controls.get(n);
}
/**
* This method released the control list, and all controls in it.
*/
synchronized void release(){
released = true;
for(Control c: controls.values())
c.release();
}
private void checkReleased(){
if(released) | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/ControlList.java
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import au.edu.jcu.v4l4j.exceptions.StateException;
* This method returns a list of {@link Control}s
* @return a list of {@link Control}s
* @throws StateException if this control list has been released and must not be used anymore
*/
public synchronized List<Control> getList(){
checkReleased();
return new Vector<Control>(controls.values());
}
/**
* This method returns a control given its name.
* @return the control matching the given name, null otherwise
* @throws StateException if this control list has been released and must not be used anymore
*/
public synchronized Control getControl(String n){
checkReleased();
return controls.get(n);
}
/**
* This method released the control list, and all controls in it.
*/
synchronized void release(){
released = true;
for(Control c: controls.values())
c.release();
}
private void checkReleased(){
if(released) | throw new StateException("The control list has been released and must not be used"); |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/Tuner.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
| import au.edu.jcu.v4l4j.exceptions.StateException; | * @return the index of this tuner
* @throws StateException if the associated frame grabber has been released
* and this tuner must not be used anymore.
*/
public synchronized int getIndex(){
checkRelease();
return index;
}
/**
* This method returns the {@link TunerInfo} object associated with this
* tuner.
* @return the {@link TunerInfo} object associated with this tuner.
* @throws StateException if the associated frame grabber has been released
* and this tuner must not be used anymore.
*/
public synchronized TunerInfo getInfo(){
checkRelease();
return info;
}
/**
* This method releases this tuner.
*/
synchronized void release(){
released = true;
}
private void checkRelease(){
if(released) | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/Tuner.java
import au.edu.jcu.v4l4j.exceptions.StateException;
* @return the index of this tuner
* @throws StateException if the associated frame grabber has been released
* and this tuner must not be used anymore.
*/
public synchronized int getIndex(){
checkRelease();
return index;
}
/**
* This method returns the {@link TunerInfo} object associated with this
* tuner.
* @return the {@link TunerInfo} object associated with this tuner.
* @throws StateException if the associated frame grabber has been released
* and this tuner must not be used anymore.
*/
public synchronized TunerInfo getInfo(){
checkRelease();
return info;
}
/**
* This method releases this tuner.
*/
synchronized void release(){
released = true;
}
private void checkRelease(){
if(released) | throw new StateException("The frame grabber associated with this " + |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/CaptureCallback.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
| import au.edu.jcu.v4l4j.exceptions.V4L4JException; | /*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* Objects implementing this interface receive notifications from frame grabbers
* when new captured frames become available, or an exception
* occurs during a capture. In order to capture from a video device,
* you must instantiate an object which implements this interface
* and pass it to a frame grabber
* (via @link {@link FrameGrabber#setCaptureCallback(CaptureCallback)}).
* When you start the capture, v4l4j will call {@link #nextFrame(VideoFrame)}
* to deliver new frames to your application as soon as they arrive.
* Check the {@link FrameGrabber} page for more information.
* @author gilles
*
*/
public interface CaptureCallback {
/**
* During a capture, this method is called by v4l4j to provide
* the latest video frame. It is important that you minimise
* the amount of code and processing done in this method in
* order to maintain the appropriate frame rate.
* <br>Make sure the frame is recycled when no longer used. It does not
* have to be done in this method, but it must be done at some point in
* the near future.
* @param frame the latest captured frame
*/
public void nextFrame(VideoFrame frame);
/**
* This method is called if an error occurs during capture.
* It is safe to assume that if this method is called,
* no more calls to {@link #nextFrame(VideoFrame)} will follow.
* @param e the exception that was raised during the capture.
*/ | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/V4L4JException.java
// public class V4L4JException extends Exception {
//
// private static final long serialVersionUID = -8247407640809375121L;
// public V4L4JException(String message) {
// super(message);
// }
// public V4L4JException(String message, Throwable throwable) {
// super(message, throwable);
// }
// public V4L4JException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/CaptureCallback.java
import au.edu.jcu.v4l4j.exceptions.V4L4JException;
/*
* Copyright (C) 2011 Gilles Gigan (gilles.gigan@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* Objects implementing this interface receive notifications from frame grabbers
* when new captured frames become available, or an exception
* occurs during a capture. In order to capture from a video device,
* you must instantiate an object which implements this interface
* and pass it to a frame grabber
* (via @link {@link FrameGrabber#setCaptureCallback(CaptureCallback)}).
* When you start the capture, v4l4j will call {@link #nextFrame(VideoFrame)}
* to deliver new frames to your application as soon as they arrive.
* Check the {@link FrameGrabber} page for more information.
* @author gilles
*
*/
public interface CaptureCallback {
/**
* During a capture, this method is called by v4l4j to provide
* the latest video frame. It is important that you minimise
* the amount of code and processing done in this method in
* order to maintain the appropriate frame rate.
* <br>Make sure the frame is recycled when no longer used. It does not
* have to be done in this method, but it must be done at some point in
* the near future.
* @param frame the latest captured frame
*/
public void nextFrame(VideoFrame frame);
/**
* This method is called if an error occurs during capture.
* It is safe to assume that if this method is called,
* no more calls to {@link #nextFrame(VideoFrame)} will follow.
* @param e the exception that was raised during the capture.
*/ | public void exceptionReceived(V4L4JException e); |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/BaseVideoFrame.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
| import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.WritableRaster;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod; |
/**
* This method is used by the owning frame grabber to get a reference
* to the byte array used to hold the frame data.
* @return the byte array used to hold the frame data
*/
final byte[] getByteArray() {
return frameBuffer;
}
/**
* This method is used by the owning frame grabber to get the V4L2 buffer
* index
* @return the V4L2 buffer index
*/
final int getBufferInex() {
return bufferIndex;
}
/**
* Subclasses can override this method to either
* return a {@link WritableRaster} for this video frame, or throw
* a {@link UnsupportedMethod} exception if this video frame cannot
* generate a {@link WritableRaster}.
* @return a {@link WritableRaster}.
* @throws UnsupportedMethod exception if a raster cannot be generated
* for this video frame (because of its image format for instance)
*/
protected WritableRaster refreshRaster() {
if (raster == null) | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/BaseVideoFrame.java
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.WritableRaster;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
/**
* This method is used by the owning frame grabber to get a reference
* to the byte array used to hold the frame data.
* @return the byte array used to hold the frame data
*/
final byte[] getByteArray() {
return frameBuffer;
}
/**
* This method is used by the owning frame grabber to get the V4L2 buffer
* index
* @return the V4L2 buffer index
*/
final int getBufferInex() {
return bufferIndex;
}
/**
* Subclasses can override this method to either
* return a {@link WritableRaster} for this video frame, or throw
* a {@link UnsupportedMethod} exception if this video frame cannot
* generate a {@link WritableRaster}.
* @return a {@link WritableRaster}.
* @throws UnsupportedMethod exception if a raster cannot be generated
* for this video frame (because of its image format for instance)
*/
protected WritableRaster refreshRaster() {
if (raster == null) | throw new UnsupportedMethod("A raster can not be generated for this " |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/BaseVideoFrame.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
| import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.WritableRaster;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod; | protected WritableRaster refreshRaster() {
if (raster == null)
throw new UnsupportedMethod("A raster can not be generated for this "
+ "image format ("+frameGrabber.getImageFormat().toString()+")");
return raster;
}
/**
* Subclasses can override this method to either
* return a {@link BufferedImage} for this video frame, or throw
* a {@link UnsupportedMethod} exception if this video frame cannot
* generate a {@link BufferedImage}.
* @return a {@link BufferedImage}.
* @throws UnsupportedMethod exception if a buffered image cannot be generated
* for this video frame (because of its image format for instance)
*/
protected BufferedImage refreshBufferedImage() {
if (bufferedImage == null)
throw new UnsupportedMethod("A Bufferedimage can not be generated for this "
+ "image format ("+frameGrabber.getImageFormat().toString()+")");
return bufferedImage;
}
/**
* This method must be called with this video frame lock held, and
* throws a {@link StateException} if it is recycled.
* @throws StateException if this video frame is recycled.
*/ | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/UnsupportedMethod.java
// public class UnsupportedMethod extends RuntimeException {
// private static final long serialVersionUID = -8801339441741012577L;
//
// public UnsupportedMethod(String message) {
// super(message);
// }
//
// public UnsupportedMethod(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public UnsupportedMethod(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/BaseVideoFrame.java
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.WritableRaster;
import au.edu.jcu.v4l4j.exceptions.StateException;
import au.edu.jcu.v4l4j.exceptions.UnsupportedMethod;
protected WritableRaster refreshRaster() {
if (raster == null)
throw new UnsupportedMethod("A raster can not be generated for this "
+ "image format ("+frameGrabber.getImageFormat().toString()+")");
return raster;
}
/**
* Subclasses can override this method to either
* return a {@link BufferedImage} for this video frame, or throw
* a {@link UnsupportedMethod} exception if this video frame cannot
* generate a {@link BufferedImage}.
* @return a {@link BufferedImage}.
* @throws UnsupportedMethod exception if a buffered image cannot be generated
* for this video frame (because of its image format for instance)
*/
protected BufferedImage refreshBufferedImage() {
if (bufferedImage == null)
throw new UnsupportedMethod("A Bufferedimage can not be generated for this "
+ "image format ("+frameGrabber.getImageFormat().toString()+")");
return bufferedImage;
}
/**
* This method must be called with this video frame lock held, and
* throws a {@link StateException} if it is recycled.
* @throws StateException if this video frame is recycled.
*/ | private final void checkIfRecycled() throws StateException { |
sarxos/v4l4j | src/main/java/au/edu/jcu/v4l4j/RawFrameGrabber.java | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/ImageFormatException.java
// public class ImageFormatException extends V4L4JException {
//
// private static final long serialVersionUID = -3338859321078232443L;
//
// public ImageFormatException(String message) {
// super(message);
// }
//
// public ImageFormatException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public ImageFormatException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.concurrent.ThreadFactory;
import au.edu.jcu.v4l4j.exceptions.ImageFormatException;
import au.edu.jcu.v4l4j.exceptions.StateException; | /*
* Copyright (C) 2007-2008 Gilles Gigan (gilles.gigan@gmail.com)
* eResearch Centre, James Cook University (eresearch.jcu.edu.au)
*
* This program was developed as part of the ARCHER project
* (Australian Research Enabling Environment) funded by a
* Systemic Infrastructure Initiative (SII) grant and supported by the Australian
* Department of Innovation, Industry, Science and Research
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* This class provides methods to capture raw frames from a {@link VideoDevice}.
* Raw means that the image format will be left untouched and passed on straight
* away to the caller. v4l4j also provides additional frame grabber classes
* which encodes frames in a specific format before handing them out.
* <code>FrameGrabber</code> objects are not instantiated directly. Instead, the
* {@link VideoDevice#getRawFrameGrabber(int, int, int, int) getRawFrameGrabber()}
* method must be called on the associated {@link VideoDevice}. Raw frame grabbers
* implement the {@link FrameGrabber} interface which provides methods to handle
* video capture. See {@link FrameGrabber its documentation} for more information.
*
* @see FrameGrabber {@link FrameGrabber}
* @see JPEGFrameGrabber {@link RGBFrameGrabber}
* @author gilles
*
*/
public class RawFrameGrabber extends AbstractGrabber {
/**
* This constructor builds a raw FrameGrabber object used to raw frames
* from a video source.
* @param di the DeviceInfo of the VideoDevice who created this frame grabber
* @param o a JNI pointer to the v4l4j_device structure
* @param w the requested frame width
* @param h the requested frame height
* @param ch the input index, as returned by
* <code>InputInfo.getIndex()</code>
* @param std the video standard, as returned by
* <code>InputInfo.getSupportedStandards()</code> (see V4L4JConstants)
* @param t the {@link Tuner} associated with this frame grabber or
* <code>null</code>.
* @param imf the image format frames should be captured in
* @param factory the thread factory to sue when creating the push source
* @throws ImageFormatException if the image format is null and a RAW frame
* grabber is to be created
*/
RawFrameGrabber(DeviceInfo di, long o, int w, int h, int ch, | // Path: src/main/java/au/edu/jcu/v4l4j/exceptions/ImageFormatException.java
// public class ImageFormatException extends V4L4JException {
//
// private static final long serialVersionUID = -3338859321078232443L;
//
// public ImageFormatException(String message) {
// super(message);
// }
//
// public ImageFormatException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public ImageFormatException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: src/main/java/au/edu/jcu/v4l4j/exceptions/StateException.java
// public class StateException extends RuntimeException {
//
// private static final long serialVersionUID = 1351714754008657462L;
//
// public StateException(String message) {
// super(message);
// }
//
// public StateException(String message, Throwable throwable) {
// super(message, throwable);
// }
//
// public StateException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/au/edu/jcu/v4l4j/RawFrameGrabber.java
import java.util.concurrent.ThreadFactory;
import au.edu.jcu.v4l4j.exceptions.ImageFormatException;
import au.edu.jcu.v4l4j.exceptions.StateException;
/*
* Copyright (C) 2007-2008 Gilles Gigan (gilles.gigan@gmail.com)
* eResearch Centre, James Cook University (eresearch.jcu.edu.au)
*
* This program was developed as part of the ARCHER project
* (Australian Research Enabling Environment) funded by a
* Systemic Infrastructure Initiative (SII) grant and supported by the Australian
* Department of Innovation, Industry, Science and Research
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package au.edu.jcu.v4l4j;
/**
* This class provides methods to capture raw frames from a {@link VideoDevice}.
* Raw means that the image format will be left untouched and passed on straight
* away to the caller. v4l4j also provides additional frame grabber classes
* which encodes frames in a specific format before handing them out.
* <code>FrameGrabber</code> objects are not instantiated directly. Instead, the
* {@link VideoDevice#getRawFrameGrabber(int, int, int, int) getRawFrameGrabber()}
* method must be called on the associated {@link VideoDevice}. Raw frame grabbers
* implement the {@link FrameGrabber} interface which provides methods to handle
* video capture. See {@link FrameGrabber its documentation} for more information.
*
* @see FrameGrabber {@link FrameGrabber}
* @see JPEGFrameGrabber {@link RGBFrameGrabber}
* @author gilles
*
*/
public class RawFrameGrabber extends AbstractGrabber {
/**
* This constructor builds a raw FrameGrabber object used to raw frames
* from a video source.
* @param di the DeviceInfo of the VideoDevice who created this frame grabber
* @param o a JNI pointer to the v4l4j_device structure
* @param w the requested frame width
* @param h the requested frame height
* @param ch the input index, as returned by
* <code>InputInfo.getIndex()</code>
* @param std the video standard, as returned by
* <code>InputInfo.getSupportedStandards()</code> (see V4L4JConstants)
* @param t the {@link Tuner} associated with this frame grabber or
* <code>null</code>.
* @param imf the image format frames should be captured in
* @param factory the thread factory to sue when creating the push source
* @throws ImageFormatException if the image format is null and a RAW frame
* grabber is to be created
*/
RawFrameGrabber(DeviceInfo di, long o, int w, int h, int ch, | int std, Tuner t, ImageFormat imf, ThreadFactory factory) throws ImageFormatException{ |
kimxogus/react-native-version-check | examples/reactnative/android/app/src/main/java/com/reactnative/MainApplication.java | // Path: packages/react-native-version-check/android/src/main/java/io/xogus/reactnative/versioncheck/RNVersionCheckPackage.java
// public class RNVersionCheckPackage implements ReactPackage {
// @Override
// public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
// return Arrays.<NativeModule>asList(new RNVersionCheckModule(reactContext));
// }
//
// public List<Class<? extends JavaScriptModule>> createJSModules() {
// return Collections.emptyList();
// }
//
// @Override
// public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
// return Collections.emptyList();
// }
// }
| import android.app.Application;
import com.facebook.react.ReactApplication;
import io.xogus.reactnative.versioncheck.RNVersionCheckPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List; | package com.reactnative;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(), | // Path: packages/react-native-version-check/android/src/main/java/io/xogus/reactnative/versioncheck/RNVersionCheckPackage.java
// public class RNVersionCheckPackage implements ReactPackage {
// @Override
// public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
// return Arrays.<NativeModule>asList(new RNVersionCheckModule(reactContext));
// }
//
// public List<Class<? extends JavaScriptModule>> createJSModules() {
// return Collections.emptyList();
// }
//
// @Override
// public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
// return Collections.emptyList();
// }
// }
// Path: examples/reactnative/android/app/src/main/java/com/reactnative/MainApplication.java
import android.app.Application;
import com.facebook.react.ReactApplication;
import io.xogus.reactnative.versioncheck.RNVersionCheckPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
package com.reactnative;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(), | new RNVersionCheckPackage() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.