blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 131 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 32 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 313 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6c41bb660f144f2c8aeafcc7c3c4cc6289d9191b | 875ed8f558fbe0f425e793fceeae18c20b2a48ac | /Coding/src/swordForOffer/FindGreatestSumOfSubArray.java | b3e6855f776e78e7d26e115b40cd323eb0e08325 | [] | no_license | yajiefu/Coding | 2f63911bba7bf8ca3c9d1ac2ecd30b1376a5c0a0 | b012acc7a34550f5dc7eb4ee5993d5c8ba46f6c5 | refs/heads/master | 2020-05-27T20:44:48.637173 | 2019-12-09T13:01:43 | 2019-12-09T13:01:43 | 188,784,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,012 | java | package swordForOffer;
/**
* 题目:连续子数组的最大和
* 描述:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。
* 但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?
* 例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。 给一个数组,返回它的最大连续子序列的和
*
*
*
* @author yajie
*
*/
public class FindGreatestSumOfSubArray {
//
public static int findGreatestSumOfSubArray(int[] array) {
if (array == null || array.length <= 0) {
return 0;
}
int max = array[0];//用于保存最大和的值
int sum = 0;
for(int i = 0; i < array.length; i++) {
if (sum <= 0) {//如果之前的sum为负数的话,则从现在这个点开始
sum = array[i];
}else {
sum += array[i];
}
if (sum > max) {
max = sum;
}
}
return max;
}
//动态规划:用f(i)来表示以第i个数字结尾的子数组的最大和。
// f(i) = arr[i] 当i=0或f(i-1)<=0
// f(i-1)+arr[i] 当i不为0或f(i-1)>0
//通常用递归方式做,但最终都会基于循环去编码
//其实f[i]对应的上一种方法的sum。可见两种方法的思路异曲同工。
public static int findGreatestSumOfSubArray1(int[] array) {
if (array == null || array.length <= 0) {
return 0;
}
int[] f = new int[array.length];
f[0] = array[0];
int max = array[0];
for(int i = 1; i < array.length; i++) {
if (f[i-1] <= 0) {
f[i] = array[i];
}else {
f[i] = f[i-1] + array[i];
}
if (f[i] > max) {
max = f[i];
}
}
return max;
}
public static void main(String[] args) {
int[] arr = {6,-3,-2,7,-15,1,2,2};
System.out.println(findGreatestSumOfSubArray(arr));
System.out.println(findGreatestSumOfSubArray1(arr));
}
}
| [
"yajiefu@outlook.com"
] | yajiefu@outlook.com |
e6a677bf6b5a7dcac2b2c003b0d24db8fc4e9758 | 598df3e6948ab5d106b714637c951d2d2dfb44d6 | /Monitor-framework/src/main/java/com/monitor/framework/query/entity/QueryContext.java | 208cc560c9ae62ff314016b17769a86a6f085ca6 | [
"MIT"
] | permissive | aitp2/a2web | ce18b8fcfcddac9167e4f198c86d2ae9750f8ce0 | e5332e52b5e7a1c515c27ae213aee6ca6b7b95cd | refs/heads/master | 2021-04-03T06:00:55.312087 | 2018-08-22T06:29:39 | 2018-08-22T06:29:39 | 124,824,438 | 0 | 3 | MIT | 2018-03-26T01:47:51 | 2018-03-12T02:44:51 | Java | UTF-8 | Java | false | false | 701 | java | package com.monitor.framework.query.entity;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.digester3.annotations.rules.ObjectCreate;
import org.apache.commons.digester3.annotations.rules.SetNext;
@ObjectCreate(pattern="queryContext")
public class QueryContext {
private int cacheSize;
private List<Query> queries;
public QueryContext() {
cacheSize = 20;
queries = new ArrayList();
}
public int getCacheSize() {
return cacheSize;
}
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
@SetNext
public void addQuery(Query query) {
this.queries.add(query);
}
public List getQueries() {
return this.queries;
}
} | [
"kairong.su@accenture.com"
] | kairong.su@accenture.com |
dcb9d1c4ea9d972576bc881dab133bdc6eb72f19 | 8ce57f3d8730091c3703ad95f030841a275d8c65 | /test/testsuite/ouroboros/thread_test/RT0042-rt-thread-ThreadisDaemon2/ThreadIsDaemon2.java | 5b98b7d3e4e65120e96d8b40ae15f24f1776a8eb | [] | no_license | TanveerTanjeem/OpenArkCompiler | 6c913ebba33eb0509f91a8f884a87ef8431395f6 | 6acb8e0bac4ed3c7c24f5cb0196af81b9bedf205 | refs/heads/master | 2022-11-17T21:08:25.789107 | 2020-07-15T09:00:48 | 2020-07-15T09:00:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,777 | java | /*
* Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
* -@TestCaseID: ThreadIsDaemon2
*- @TestCaseName: Thread_ThreadIsDaemon2.java
*- @RequirementName: Java Thread
*- @Title/Destination: Setting child threads to daemon threads has no effect on the main thread.
*- @Brief: see below
* -#step1: 创建ThreadIsDaemon2类的实例对象threadIsDaemon2,并且ThreadIsDaemon2类继承自Thread类;
* -#step2: 通过threadIsDaemon2的setDaemon()方法设置其属性为true;
* -#step3: 调用threadIsDaemon2的start()方法启动该线程;
* -#step4: 经判断得知调用currentThread()的isDaemon()方法其返回值为false;
*- @Expect: expected.txt
*- @Priority: High
*- @Source: ThreadIsDaemon2.java
*- @ExecuteClass: ThreadIsDaemon2
*- @ExecuteArgs:
*/
public class ThreadIsDaemon2 extends Thread {
public static void main(String[] args) {
ThreadIsDaemon2 threadIsDaemon2 = new ThreadIsDaemon2();
threadIsDaemon2.setDaemon(true);
threadIsDaemon2.start();
if (currentThread().isDaemon()) {
System.out.println(2);
return;
}
System.out.println(0);
}
}
// EXEC:%maple %f %build_option -o %n.so
// EXEC:%run %n.so %n %run_option | compare %f
// ASSERT: scan 0 | [
"fuzhou@huawei.com"
] | fuzhou@huawei.com |
4f6687e8fdbd7c0bc8be43e1e759a43f3cc05667 | 129f58086770fc74c171e9c1edfd63b4257210f3 | /src/testcases/CWE83_XSS_Attribute/CWE83_XSS_Attribute__Servlet_PropertiesFile_21.java | 6306e6b794395ebb60bbc593a12271a0dbd580ef | [] | no_license | glopezGitHub/Android23 | 1bd0b6a6c7ce3c7439a74f1e4dcef2c4c0fac4ba | 6215d0684c4fbdc7217ccfbedfccfca69824cc5e | refs/heads/master | 2023-03-07T15:14:59.447795 | 2023-02-06T13:59:49 | 2023-02-06T13:59:49 | 6,856,387 | 0 | 3 | null | 2023-02-06T18:38:17 | 2012-11-25T22:04:23 | Java | UTF-8 | Java | false | false | 7,904 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE83_XSS_Attribute__Servlet_PropertiesFile_21.java
Label Definition File: CWE83_XSS_Attribute__Servlet.label.xml
Template File: sources-sink-21.tmpl.java
*/
/*
* @description
* CWE: 83 Cross Site Scripting (XSS) in attributes; Examples(replace QUOTE with an actual double quote): ?img_loc=http://www.google.comQUOTE%20onerror=QUOTEalert(1) and ?img_loc=http://www.google.comQUOTE%20onerror=QUOTEjavascript:alert(1)
* BadSource: PropertiesFile Read data from a .properties file (in property named data)
* GoodSource: A hardcoded string
* Sinks: printlnServlet
* GoodSink: $Sink.GoodSinkBody.description$
* BadSink : XSS in img src attribute
* Flow Variant: 21 Control flow: Flow controlled by value of a private variable. All functions contained in one file.
*
* */
package testcases.CWE83_XSS_Attribute;
import testcasesupport.*;
import javax.servlet.http.*;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CWE83_XSS_Attribute__Servlet_PropertiesFile_21 extends AbstractTestCaseServlet
{
/* The variable below is used to drive control flow in the source function */
private boolean bad_private = false;
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
bad_private = true;
data = bad_source(request, response);
if (data != null)
{
/* POTENTIAL FLAW: Input is not verified/sanitized before use in an image tag */
response.getWriter().println("<br>bad() - <img src=\"" + data + "\">");
}
}
private String bad_source(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
if(bad_private)
{
data = ""; /* Initialize data */
/* retrieve the property */
Properties props = new Properties();
FileInputStream finstr = null;
try
{
finstr = new FileInputStream("../common/config.properties");
props.load(finstr);
/* POTENTIAL FLAW: Read data from a .properties file */
data = props.getProperty("data");
}
catch( IOException ioe )
{
IO.logger.log(Level.WARNING, "Error with stream reading", ioe);
}
finally
{
/* Close stream reading object */
try {
if( finstr != null )
{
finstr.close();
}
}
catch( IOException ioe )
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe);
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Use a hardcoded string */
data = "foo";
}
return data;
}
/* The variables below are used to drive control flow in the source functions. */
private boolean goodG2B1_private = false;
private boolean goodG2B2_private = false;
public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
goodG2B1(request, response);
goodG2B2(request, response);
}
/* goodG2B1() - use goodsource and badsink by setting the variable to false instead of true */
private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
goodG2B1_private = false;
data = goodG2B1_source(request, response);
if (data != null)
{
/* POTENTIAL FLAW: Input is not verified/sanitized before use in an image tag */
response.getWriter().println("<br>bad() - <img src=\"" + data + "\">");
}
}
private String goodG2B1_source(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
if(goodG2B1_private)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
data = ""; /* Initialize data */
/* retrieve the property */
Properties props = new Properties();
FileInputStream finstr = null;
try
{
finstr = new FileInputStream("../common/config.properties");
props.load(finstr);
/* POTENTIAL FLAW: Read data from a .properties file */
data = props.getProperty("data");
}
catch( IOException ioe )
{
IO.logger.log(Level.WARNING, "Error with stream reading", ioe);
}
finally
{
/* Close stream reading object */
try {
if( finstr != null )
{
finstr.close();
}
}
catch( IOException ioe )
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe);
}
}
}
else {
/* FIX: Use a hardcoded string */
data = "foo";
}
return data;
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the sink function */
private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
goodG2B2_private = true;
data = goodG2B2_source(request, response);
if (data != null)
{
/* POTENTIAL FLAW: Input is not verified/sanitized before use in an image tag */
response.getWriter().println("<br>bad() - <img src=\"" + data + "\">");
}
}
private String goodG2B2_source(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
if(goodG2B2_private)
{
/* FIX: Use a hardcoded string */
data = "foo";
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
data = ""; /* Initialize data */
/* retrieve the property */
Properties props = new Properties();
FileInputStream finstr = null;
try {
finstr = new FileInputStream("../common/config.properties");
props.load(finstr);
/* POTENTIAL FLAW: Read data from a .properties file */
data = props.getProperty("data");
}
catch( IOException ioe )
{
IO.logger.log(Level.WARNING, "Error with stream reading", ioe);
}
finally {
/* Close stream reading object */
try {
if( finstr != null )
{
finstr.close();
}
}
catch( IOException ioe )
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", ioe);
}
}
}
return data;
}
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
| [
"guillermo.pando@gmail.com"
] | guillermo.pando@gmail.com |
26c281438e3da54fa8c5a7299652b70e7647f09a | 412073592eadc1a8835dbc4b47fd5dcbd810c070 | /storage-aws/src/main/java/net/kemitix/thorp/storage/aws/AmazonS3Client.java | add9937749bdd29e70888cca129b3f37645d9129 | [
"MIT"
] | permissive | kemitix/thorp | be1d70677909fe2eeb328128fb28ee6b2499bf2a | 8c5c84c1d8fede9e092b28de65bea45840f943d0 | refs/heads/master | 2022-12-11T22:10:47.251527 | 2022-12-03T11:49:19 | 2022-12-03T12:08:17 | 185,944,622 | 2 | 1 | MIT | 2022-12-03T12:08:59 | 2019-05-10T07:55:16 | Java | UTF-8 | Java | false | false | 1,359 | java | package net.kemitix.thorp.storage.aws;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import java.util.Optional;
public interface AmazonS3Client {
void shutdown();
void deleteObject(DeleteObjectRequest request);
Optional<CopyObjectResult> copyObject(CopyObjectRequest request);
ListObjectsV2Result listObjects(ListObjectsV2Request request);
PutObjectResult uploadObject(PutObjectRequest request);
static AmazonS3Client create(AmazonS3 amazonS3) {
return new AmazonS3Client() {
@Override
public void shutdown() {
amazonS3.shutdown();
}
@Override
public void deleteObject(DeleteObjectRequest request) {
amazonS3.deleteObject(request);
}
@Override
public Optional<CopyObjectResult> copyObject(CopyObjectRequest request) {
return Optional.of(amazonS3.copyObject(request));
}
@Override
public ListObjectsV2Result listObjects(ListObjectsV2Request request) {
return amazonS3.listObjectsV2(request);
}
@Override
public PutObjectResult uploadObject(PutObjectRequest request) {
return amazonS3.putObject(request);
}
};
}
}
| [
"noreply@github.com"
] | kemitix.noreply@github.com |
7e65f73f53ae18fb7ea1fb3fad6b8cda012aae3b | df8e54ff5fbd5942280e3230123494a401c57730 | /code/on-the-way/pre-way/src/main/java/com/vika/way/pre/algorithm/leetcode/midium/S501_600/S593ValidSquare.java | 162780204bb7f6a00c9d0e271e115a5d64a62043 | [] | no_license | kabitonn/cs-note | 255297a0a0634335eefba79882f7314f7b97308f | 1235bb56a40bce7e2056f083ba8cda0cd08e39b4 | refs/heads/master | 2022-06-09T23:46:02.145680 | 2022-05-13T10:44:53 | 2022-05-13T10:44:53 | 224,864,415 | 0 | 1 | null | 2022-05-13T07:25:09 | 2019-11-29T13:58:19 | Java | UTF-8 | Java | false | false | 2,907 | java | package com.vika.way.pre.algorithm.leetcode.midium.S501_600;
import java.util.Arrays;
public class S593ValidSquare {
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
int[] edge = new int[6];
int count = 0;
edge[count++] = getDistance(p1, p2);
edge[count++] = getDistance(p1, p3);
edge[count++] = getDistance(p1, p4);
edge[count++] = getDistance(p2, p3);
edge[count++] = getDistance(p2, p4);
edge[count++] = getDistance(p3, p4);
Arrays.sort(edge);
if (edge[0] != 0 && edge[0] == edge[1] && edge[0] == edge[2] && edge[0] == edge[3]) {
if (edge[4] == edge[5]) {
return true;
}
}
return false;
}
public int getDistance(int[] p1, int[] p2) {
int dx = p2[0] - p1[0];
int dy = p2[1] - p1[1];
return dx * dx + dy * dy;
}
public boolean validSquare1(int[] p1, int[] p2, int[] p3, int[] p4) {
int p12 = getDistance(p1, p2);
int p13 = getDistance(p1, p3);
int p14 = getDistance(p1, p4);
int p23 = getDistance(p2, p3);
int p24 = getDistance(p2, p4);
int p34 = getDistance(p3, p4);
if (p12 == 0 || p13 == 0 || p14 == 0 || p23 == 0 || p24 == 0 || p34 == 0) {
return false;
}
if ((p12 == p34 && p13 == p14 && p13 == p23 && p13 == p24) ||
(p13 == p24 && p12 == p14 && p12 == p23 && p12 == p34) ||
(p14 == p23 && p12 == p13 && p12 == p24 && p12 == p34)) {
return true;
}
return false;
}
// 待完善,检验对角线,仍需判断对角线相交
public boolean validSquare2(int[] p1, int[] p2, int[] p3, int[] p4) {
int[] p12 = getDiff(p1, p2);
int[] p13 = getDiff(p1, p3);
int[] p14 = getDiff(p1, p4);
int[] p23 = getDiff(p2, p3);
int[] p24 = getDiff(p2, p4);
int[] p34 = getDiff(p3, p4);
if (valid(p12, p34) || valid(p13, p24) || valid(p14, p23)) {
return true;
}
return false;
}
public boolean valid(int[] d1, int[] d2) {
boolean edge = d1[2] > 0 && d1[2] == d2[2];
boolean vertical = (d1[0] * d2[0] + d1[1] * d2[1]) == 0;
return edge && vertical;
}
public int[] getDiff(int[] p1, int[] p2) {
int dx = p2[0] - p1[0];
int dy = p2[1] - p1[1];
return new int[]{dx, dy, dx * dx + dy * dy};
}
public static void main(String[] args) {
S593ValidSquare solution = new S593ValidSquare();
/*
int[] p1 = {1, 0};
int[] p2 = {-1, 0};
int[] p3 = {0, 1};
int[] p4 = {0, -1};
*/
int[] p1 = {0, 1};
int[] p2 = {1, 2};
int[] p3 = {0, 2};
int[] p4 = {0, 0};
System.out.println(solution.validSquare1(p1, p2, p3, p4));
}
}
| [
"chenwei.tjw@alibaba-inc.com"
] | chenwei.tjw@alibaba-inc.com |
9b6c220237090d9f924888dffe043d09771df596 | aa5fa2f249e90038b9d7688e19287173712055ac | /Resilience5/src/main/java/com/example/Resilience5/CircuitBreaker5.java | d5f2e9643ef38d8b2dc68cd80d87f9b513c56c7a | [] | no_license | SiddharthSingh10671395/Resilience4J | c3e31c283b9371e265c446e313aec2f6776095ed | 07b9946eda1b8a5c4ed01abf3765bddffbfa32f6 | refs/heads/main | 2023-02-09T08:56:14.753704 | 2020-12-21T12:08:02 | 2020-12-21T12:08:02 | 323,297,947 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,055 | java | package com.example.Resilience5;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.core.SupplierUtils;
import io.vavr.CheckedFunction0;
import io.vavr.control.Try;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
//working code
public class CircuitBreaker5 {
public static String print(){
RestTemplate restTemplate=new RestTemplate();
// try {
// Thread.sleep(4000);
// throw new Exception();
// } catch (Exception e) {
// e.printStackTrace();
// }
return restTemplate.getForObject("http://localhost:8081/test/greet", String.class);
}
public static String printNew(int times){
RestTemplate restTemplate=new RestTemplate();
// try {
// Thread.sleep(4000);
// throw new Exception();
// } catch (Exception e) {
// e.printStackTrace();
// }
return restTemplate.getForObject("http://localhost:8081/test/greet", String.class);
}
public static String print2(){
RestTemplate restTemplate=new RestTemplate();
// try {
// Thread.sleep(4000);
// throw new Exception();
// } catch (Exception e) {
// e.printStackTrace();
// }
return restTemplate.getForObject("http://localhost:8082/movies/hello", String.class);
}
public static CircuitBreaker lend(){
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(1000))
.permittedNumberOfCallsInHalfOpenState(2)
.slidingWindowSize(2)
.recordExceptions(IOException.class, TimeoutException.class)
.build();
CircuitBreakerRegistry circuitBreakerRegistry =
CircuitBreakerRegistry.of(circuitBreakerConfig);
CircuitBreaker circuitBreaker = circuitBreakerRegistry
.circuitBreaker("name");
return circuitBreaker;
}
//this function return "hello " from recovery when our link stops working
public static void test(){
Supplier<String> decoratedSupplier = CircuitBreaker
.decorateSupplier(CircuitBreaker5.lend(), CircuitBreaker5::print);
String result = Try.ofSupplier(decoratedSupplier)
.recover(throwable -> "Hello from Recovery").get();
// String result = circuitBreaker
// .executeSupplier(CircuitBreaker5::print);
System.out.println(result);
}
public static void test2(){
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(1000))
.permittedNumberOfCallsInHalfOpenState(2)
.slidingWindowSize(2)
.recordExceptions(IOException.class, TimeoutException.class)
.build();
CircuitBreakerRegistry circuitBreakerRegistry =
CircuitBreakerRegistry.of(circuitBreakerConfig);
// CircuitBreaker circuitBreaker = circuitBreakerRegistry
// .circuitBreaker("name");
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
CheckedFunction0<String> checkedSupplier =
CircuitBreaker.decorateCheckedSupplier(circuitBreaker, () -> {
throw new RuntimeException("BAM!");
});
Try<String> result = Try.of(checkedSupplier)
.recover(throwable -> "Hello Recovery");
System.out.println(result);
}
//If you want to recover from an exception before the CircuitBreaker records it as a failure, you can do the following:
public static void test3(){
Supplier<String> supplier = () -> {
throw new RuntimeException("BAM!");
};
Supplier<String> supplier2 = CircuitBreaker5::print;
Supplier<String> supplierWithRecovery = SupplierUtils
//test it with supplier also
.recover(supplier2, (exception) -> "Hello Recovery");
String result = CircuitBreaker5.lend().executeSupplier(supplierWithRecovery);
System.out.println(result);
}
public static void main(String[] args) {
//CircuitBreaker5.test();
//CircuitBreaker5.test2();
CircuitBreaker5.test3();
}
}
| [
"noreply@github.com"
] | SiddharthSingh10671395.noreply@github.com |
5b7678cd3f6b6275f2b003da3aef401871f6d2a3 | af819199ddf71ed89937434f71f3d478fd9336d5 | /Source/Parsing/src/ca/uqac/lif/util/MutableString.java | 61d4cf9f1e46ce13ff05c52c030cf32ed1768287 | [
"Apache-2.0"
] | permissive | sylvainhalle/Bullwinkle | 6d1be01a20cc89fe51e8ca75dea7a23fda5d5150 | 6b04727d3c18d283371c63e7480550d33738e224 | refs/heads/master | 2023-08-18T11:00:14.981785 | 2021-11-08T12:09:00 | 2021-11-08T12:09:00 | 18,143,415 | 51 | 23 | null | 2017-05-15T18:56:26 | 2014-03-26T15:37:51 | Java | UTF-8 | Java | false | false | 8,786 | java | /* MIT License
*
* Copyright 2014-2021 Sylvain Hallé
*
* Laboratoire d'informatique formelle
* Université du Québec à Chicoutimi, Canada
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package ca.uqac.lif.util;
/**
* A mutable String object. This object behaves in almost the same way as
* a regular <tt>String</tt>, except that its contents can be changed.
* For example, while method {@link String#replaceAll(String, String)} in
* the class <tt>String</tt> creates a <em>new</em> string where the
* replacements are made, method {@link #replaceAll(String, String)} in
* <tt>MutableString</tt> modifies the current object.
*
* @author Sylvain Hallé
*/
public class MutableString
{
/**
* The underlying string
*/
protected String m_string;
/**
* Creates a new empty mutable string
*/
public MutableString()
{
this("");
}
/**
* Creates a new mutable string from an existing string object
* @param s The string
*/
public MutableString(String s)
{
super();
m_string = s;
}
/**
* Creates a new mutable string from another mutable string
* @param s The mutable string
*/
public MutableString(MutableString s)
{
this(s.toString());
}
/**
* Clears the contents of this mutable string
*/
public void clear()
{
m_string = "";
}
/**
* Returns the position of the first occurrence of a substring within
* the current string
* @see String#indexOf(String)
* @param s The string to look for
* @return The position
*/
public int indexOf(String s)
{
return m_string.indexOf(s);
}
/**
* Returns the position of the first occurrence of a substring within
* the current string, starting at some index
* @see String#indexOf(String, int)
* @param s The string to look for
* @param fromIndex The starting position
* @return The position
*/
public int indexOf(String s, int fromIndex)
{
return m_string.indexOf(s, fromIndex);
}
/**
* Trims a string of its leading and trailing whitespace characters
* @see String#trim()
*/
public void trim()
{
m_string = m_string.trim();
}
/**
* Gets the length of the string
* @see String#length()
* @return The length
*/
public int length()
{
return m_string.length();
}
/**
* Splits a mutable string into parts according to a separator expression
* @see String#split(String)
* @param regex The regex used to separate the string
* @return An array of mutable strings, one for each part
*/
public MutableString[] split(String regex)
{
String[] splitted = m_string.split(regex);
MutableString[] out = new MutableString[splitted.length];
for (int i = 0; i < splitted.length; i++)
{
out[i] = new MutableString(splitted[i]);
}
return out;
}
/**
* Truncates the current string. This effectively takes out a part of
* the current substring.
* @param begin The start position
* @param end The end position
* @return A new instance of the mutable string, keeping only the
* characters between <tt>begin</tt> and <tt>end</tt>. Note that this
* also <em>removes</em> this substring from the current object.
*/
public MutableString truncateSubstring(int begin, int end)
{
String out = m_string.substring(begin, end);
m_string = m_string.substring(0, begin) + m_string.substring(end);
return new MutableString(out);
}
/**
* Truncates the current substring
* @param begin The start position
* @return A new instance of the mutable string, keeping only the
* characters between <tt>begin</tt> and the end of the string.
* Note that this
* also <em>removes</em> this substring from the current object.
*/
public MutableString truncateSubstring(int begin)
{
String out = m_string.substring(0, begin);
m_string = m_string.substring(begin);
return new MutableString(out);
}
/**
* Gets a substring of the current string. Contrary to
* {@link #truncateSubstring(int, int)}, this does not modify the current
* object.
* @see String#substring(int, int)
* @param start The start position
* @param end The end position
* @return A new instance of the mutable string, keeping only the
* characters between <tt>begin</tt> and <tt>end</tt>.
*/
public MutableString substring(int start, int end)
{
return new MutableString(m_string.substring(start, end));
}
/**
* Gets a substring of the current string. Contrary to
* {@link #truncateSubstring(int)}, this does not modify the current
* object.
* @see String#substring(int, int)
* @param start The start position
* @return A new instance of the mutable string, keeping only the
* characters between <tt>begin</tt> and the end of the string.
*/
public MutableString substring(int start)
{
return new MutableString(m_string.substring(start));
}
/**
* Checks if a string starts with another string
* @see String#startsWith(String)
* @param s The string to look for
* @return {@code true} if the current object starts with <tt>s</tt>,
* {@code false} otherwise
*/
public boolean startsWith(String s)
{
return m_string.startsWith(s);
}
/**
* Checks if a string starts with another string, ignoring upper/lowercase
* @param s The string to look for
* @return {@code true} if the current object starts with <tt>s</tt>,
* {@code false} otherwise
*/
public boolean startsWithIgnoreCase(String s)
{
return m_string.toLowerCase().startsWith(s.toLowerCase());
}
/**
* Checks if a string ends with another string
* @see String#endsWith(String)
* @param s The string to look for
* @return {@code true} if the current object ends with <tt>s</tt>,
* {@code false} otherwise
*/
public boolean endsWith(String s)
{
return m_string.endsWith(s);
}
/**
* Checks if a string ends with another string, ignoring upper/lowercase
* @param s The string to look for
* @return {@code true} if the current object ends with <tt>s</tt>,
* {@code false} otherwise
*/
public boolean endsWithIgnoreCase(String s)
{
return m_string.toLowerCase().endsWith(s.toLowerCase());
}
/**
* Checks if a string contains the same character sequence as this
* mutable string object
* @see String#compareTo(String)
* @param s The string to compare to
* @return {@code true} if <tt>s</tt> and the current object contain the
* same character sequence, {@code false} otherwise
*/
public boolean is(String s)
{
return m_string.compareTo(s) == 0;
}
@Override
public boolean equals(Object o)
{
if (o == null || !(o instanceof MutableString))
{
return false;
}
return is(((MutableString) o).toString());
}
@Override
public int hashCode()
{
return m_string.hashCode();
}
/**
* Checks if the current mutable string is empty
* @see String#isEmpty()
* @return {@code true} if the string is empty, {@code false} otherwise
*/
public boolean isEmpty()
{
return m_string.isEmpty();
}
/**
* Replaces all occurrences of a pattern by another string in the current
* mutable string object
* @see String#replaceAll(String, String)
* @param regex The pattern to look for
* @param replacement The replacement string
*/
public void replaceAll(String regex, String replacement)
{
m_string = m_string.replaceAll(regex, replacement);
}
@Override
public String toString()
{
return m_string;
}
} | [
"shalle@acm.org"
] | shalle@acm.org |
4ab042ba128c05b325fb532d68c3598eaa2332b8 | 95f4863759fb2c96109ef753e5077d1904a42516 | /app/src/main/java/com/example/hiotmvp/utils/ImageUtils.java | b4432b4aeabff1eece94ddf5c42f654f75d5a3da | [] | no_license | hehefengye/android | 76e7d33ee89299ad8e6ce03e00d0d20da4ad967d | a52c6d1ee66ebc44218d1e7ed138198340fe82f3 | refs/heads/master | 2023-08-22T16:57:16.436005 | 2021-10-17T07:22:54 | 2021-10-17T07:22:54 | 412,960,542 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,180 | java | package com.example.hiotmvp.utils;
import android.content.Context;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.hiotmvp.R;
import com.example.hiotmvp.data.MyService;
/**
* 图片工具类
*/
public class ImageUtils {
/**
* 返回图片全路径url
*
* @param url
* @return
*/
public static String getFullUrl(String url) {
return MyService.BASE_URL + url;
}
public static void show(Context context, ImageView imageView, String url) {
Glide.with(context).load(url).apply(getCommonOptions()).into(imageView);
}
public static void showCircle(Context context, ImageView imageView, String url) {
Glide.with(context).load(url).apply(getCommonOptions().circleCrop()).into(imageView);
}
/**
* 获取默认配置
*
* @return
*/
private static RequestOptions getCommonOptions() {
RequestOptions options = new RequestOptions();
options.placeholder(R.drawable.loading)
.error(R.drawable.error)
.centerCrop();
return options;
}
}
| [
"1729086309@qq.com"
] | 1729086309@qq.com |
ed82c223542046f4ceae43e52ae8e394b2190385 | 21b6fdceb3f3d11004781950f5745cbec761fab1 | /tspoon/src/main/java/it/polimi/affetti/tspoon/tgraph/query/QueryTuple.java | af459a3102d8fd600373d8f6fd85d8050d78c99a | [] | no_license | affo/t-spoon | 8cfbe90e9ce50cd03f2459295a5df502010d77f0 | 737d84936758fb8226cd3a7fa8c09554b529383f | refs/heads/master | 2022-05-25T08:47:14.644309 | 2019-09-11T14:05:51 | 2019-09-11T14:05:51 | 97,845,157 | 2 | 1 | null | 2022-05-20T20:48:38 | 2017-07-20T14:29:24 | Java | UTF-8 | Java | false | false | 191 | java | package it.polimi.affetti.tspoon.tgraph.query;
/**
* Created by affo on 20/03/17.
*/
// TODO implement
public class QueryTuple {
public String getKey() {
return "foo";
}
}
| [
"lorenzo.affetti@gmail.com"
] | lorenzo.affetti@gmail.com |
3f58280879c63016c0691cec94bf468e5f35904f | 1a1ee82aee594f412015ef737af87594405098eb | /fypProjectfinal/app/src/main/java/com/practice/e_centrar/DatabaseHelper.java | 88bbc46c000c540dc4fac874c4cc4b2500f37b9a | [] | no_license | uroojkhan01/E-Centrar | 1aee3959e2d78e485e31169959cf81061f307a1f | ead92f6b112df652150587768fa11fc6d7a8659f | refs/heads/master | 2020-05-21T21:26:34.684306 | 2019-05-11T19:38:17 | 2019-05-11T19:38:17 | 186,154,099 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,085 | java | package com.practice.e_centrar;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.practice.e_centrar.DataContract.Customer_Entry;
import com.practice.e_centrar.DataContract.Product_Entry;
import com.practice.e_centrar.DataContract.GoodNotes_Entry;
import com.practice.e_centrar.DataContract.PurchaseInvoice_Entry;
import com.practice.e_centrar.DataContract.Locations_entry;
import java.lang.ref.PhantomReference;
public class DatabaseHelper extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "hello.db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CUSTOMER_TABLE = "CREATE TABLE " + DataContract.Customer_Entry.TABLE_NAME + " ( "+
DataContract.Customer_Entry.COLUMN_Customer_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + DataContract.Customer_Entry.COLUMN_FirstName+" TEXT, " + DataContract.Customer_Entry.COLUMN_LastName+" TEXT, "+
DataContract.Customer_Entry.COLUMN_Adress +" TEXT, "+ DataContract.Customer_Entry.COLUMN_EnterpriseName +" TEXT, "+ DataContract.Customer_Entry.COLUMN_JobPosition + " TEXT, " +
DataContract.Customer_Entry.COLUMN_Email +" TEXT, "+ DataContract.Customer_Entry.COLUMN_MobileNo +" TEXT, " + DataContract.Customer_Entry.COLUMN_PhoneNo + " TEXT, "+
DataContract.Customer_Entry.COLUMN_DateCreated +" TEXT, "+ DataContract.Customer_Entry.COLUMN_PaymentMethod +" TEXT, " + DataContract.Customer_Entry.COLUMN_IsActive + " TEXT, " +
DataContract.Customer_Entry.COLUMN_CreatedBy +" TEXT, "+ DataContract.Customer_Entry.COLUMN_UpdatedBy +" TEXT, " + DataContract.Customer_Entry.COLUMN_UpdatedDate + " TEXT );";
String PRODUCT_TABLE= "CREATE TABLE " + Product_Entry.PRODUCT_TABLE_NAME + " ( " + Product_Entry.COLUMN_PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + Product_Entry.COLUMN_PRODUCT_NAME + " TEXT, " +
Product_Entry.COLUMN_PRODUCT_CATEGORYID_FK_+ " INTEGER, " + Product_Entry.COLUMN_PRODUCT_PRODUCTTYPEID_FK + " INTEGER, " + Product_Entry.COLUMN_PRODUCT_ONHAND + " TEXT, " +
Product_Entry.COLUMN_PRODUCT_INSTOCK + " TEXT, " + Product_Entry.COLUMN_PRODUCT_FULFILLED + " TEXT, " + Product_Entry.COLUMN_PRODUCT_SKU + " TEXT, " +
Product_Entry.COLUMN_PRODUCT_IMAGE + " TEXT, " + Product_Entry.COLUMN_PRODUCT_CREATEDBY + " TEXT, " + Product_Entry.COLUMN_PRODUCT_CREATEDDATE + " TEXT, " +
Product_Entry.COLUMN_PRODUCT_UPDATEDBY + " TEXT, " + Product_Entry.COLUMN_PRODUCT_UPDATEDDATE + " TEXT, " + Product_Entry.COLUMN_PRODUCT_ISACTIVE + " TEXT, " +
Product_Entry.COLUMN_PRODUCT_VARIANTS + " TEXT ); ";
String GOODNOTE_TABLE = " CREATE TABLE " + GoodNotes_Entry.GOODNOTES_TABLE_NAME + "( " + GoodNotes_Entry.GOODNOTES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
GoodNotes_Entry.GOODNOTES_ORDERID_FK + " INTEGER, " + GoodNotes_Entry.GOODNOTES_DELIVERTO + " TEXT, " + GoodNotes_Entry.GOODNOTES_ORDERSTATUS + " TEXT, " +
GoodNotes_Entry.GOODNOTES_PACKED + " TEXT, " + GoodNotes_Entry.GOODNOTES_PICKED + " TEXT, " + GoodNotes_Entry.GOODNOTES_PRINTED + " TEXT, " +
GoodNotes_Entry.GOODNOTES_SHIPPED + " TEXT, " + GoodNotes_Entry.GOODNOTES_WAREHOUSE + " TEXT, " + GoodNotes_Entry.GOODNOTES_CREATEDBY + " TEXT, " +
GoodNotes_Entry.GOODNOTES_CREATEDDATE + " TEXT, " + GoodNotes_Entry.GOODNOTES_UPDATEDBY + " TEXT, " + GoodNotes_Entry.GOODNOTES_UPDATEDDATE + " TEXT, " +
GoodNotes_Entry.GOODNOTES_ISACTIVE + " TEXT ); " ;
String PURCHASE_INVOICE = "CREATE TABLE " + PurchaseInvoice_Entry.PURCHASE_ORDER_TABLE_NAME + " ( " + PurchaseInvoice_Entry.PURCHASE_INVOICE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
PurchaseInvoice_Entry.PURCHASE_SUPPLIER + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_BALANCE + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_DUEDATE + " TEXT, " +
PurchaseInvoice_Entry.PURCHASE_INVOICEDATE + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_PAIDAMOUNT + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE + " TEXT, " +
PurchaseInvoice_Entry.PURCHASE_STATUS + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_REVENUE + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_TOTAL + " TEXT, " +
PurchaseInvoice_Entry.PURCHASE_CREATEDBY + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_CREATEDDATE + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_UPDATEDBY + " TEXT, " +
PurchaseInvoice_Entry.PURCHASE_UPDATEDDATE + " TEXT, " + PurchaseInvoice_Entry.PURCHASE_ISACTIVE + " TEXT );";
Log.v("DatabaseHelper",PURCHASE_INVOICE);
String LOCATION_TRACKER = "create table " + Locations_entry.LOCATION_TABLE_NAME + " ( " +
Locations_entry.LOCATION_ID + " integer primary key autoincrement , " +
Locations_entry.LOCATION_LATITUDE + " REAL , " +
Locations_entry.LOCATION_LONGITUDE + " REAL , " +
Locations_entry.LOCATION_ZOOM + " TEXT , " +
Locations_entry.CURRENT_DATE + " TEXT " +
" ); ";
Log.v("DatabaseHelper",LOCATION_TRACKER);
db.execSQL(CUSTOMER_TABLE);
db.execSQL(PRODUCT_TABLE);
db.execSQL(GOODNOTE_TABLE);
db.execSQL(PURCHASE_INVOICE);
db.execSQL(LOCATION_TRACKER);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DataContract.Customer_Entry.TABLE_NAME );
db.execSQL("DROP TABLE IF EXISTS " + PurchaseInvoice_Entry.PURCHASE_ORDER_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + Product_Entry.PRODUCT_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + GoodNotes_Entry.GOODNOTES_TABLE_NAME);
onCreate(db);
}
public String loadHandler() {
String result = "";
String query = "Select * FROM " + DataContract.Customer_Entry.TABLE_NAME ;
String query1 = "Select * FROM " + PurchaseInvoice_Entry.PURCHASE_ORDER_TABLE_NAME;
String query2 = "Select * FROM " + Product_Entry.PRODUCT_TABLE_NAME;
String query3 = "Select * FROM " + GoodNotes_Entry.GOODNOTES_TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
Cursor cursor1 = db.rawQuery(query1,null);
Cursor cursor2 = db.rawQuery(query2,null);
Cursor cursor3 = db.rawQuery(query3,null);
// Column Indices of Customer table
int firstNameColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_FirstName);
int lastNameColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_LastName);
int addressColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_Adress);
int enterpriseColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_EnterpriseName);
int emailColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_Email);
int Mob_NoColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_MobileNo);
int Phone_noColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_PhoneNo);
int Job_positionColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_JobPosition);
int Updated_byColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_UpdatedBy);
int Updated_dateColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_UpdatedDate);
int Date_CreatedColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_DateCreated);
int IsActiveColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_IsActive);
int PaymentMethodColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_PaymentMethod);
int Created_ByColumnIndex = cursor.getColumnIndex(Customer_Entry.COLUMN_CreatedBy);
//Column indices of Purchase invoice table
int supplierColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_SUPPLIER);
int PaymentDateColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int DueDateColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_DUEDATE);
int BalanceeColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int PaidAmountDateColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int TotaleColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int StatusColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int InvoiceDateColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int RevenueColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int CreatedByColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int CreatedtDateColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int UpdatedByColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int UpdatedDateColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
int Is_ACtiveDateColumnIndex = cursor1.getColumnIndex(PurchaseInvoice_Entry.PURCHASE_PAYMENT_DATE);
//Column indices of Prodect table
int productnameColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_NAME);
int productSKUColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_SKU);
int productvariantColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_VARIANTS);
int producttype_IDColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_PRODUCTTYPEID_FK);
int productCategory_IDColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_CATEGORYID_FK_);
int productOnhandColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_ONHAND);
int productfulfilledColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_FULFILLED);
int productInstockColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_INSTOCK);
int productCreatedByColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_CREATEDBY);
int productCreatedDateColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_CREATEDDATE);
int productUpdatedByColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_UPDATEDBY);
int productUpdatedDateColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_UPDATEDDATE);
int productisactiveColumnIndex = cursor2.getColumnIndex(Product_Entry.COLUMN_PRODUCT_ISACTIVE);
//Column indices of goodnotes table
int good_orderID_FKColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_ORDERID_FK);
int good_orderstatusColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_ORDERSTATUS);
int good_delivertoColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_DELIVERTO);
int good_warehouseColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_WAREHOUSE);
int good_printedColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_PRINTED);
int good_pickedColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_PICKED);
int good_packedColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_PACKED);
int good_shippedColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_SHIPPED);
int good_createdbyColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_CREATEDBY);
int good_createddatedrderIDColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_CREATEDDATE);
int good_updatedbyColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_UPDATEDBY);
int good_updateddateColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_UPDATEDDATE);
int good_isactiveColumnIndex = cursor3.getColumnIndex(GoodNotes_Entry.GOODNOTES_ISACTIVE);
//To retireve the customer table
while (cursor.moveToNext()) {
String firstname = cursor.getString(firstNameColumnIndex);
String lastname = cursor.getString(lastNameColumnIndex);
String email = cursor.getString(emailColumnIndex);
String address = cursor.getString(addressColumnIndex);
String enterprise = cursor.getString(enterpriseColumnIndex);
String mobile = cursor.getString(Mob_NoColumnIndex);
String phone = cursor.getString(Phone_noColumnIndex);
String jobpos = cursor.getString(Job_positionColumnIndex);
String update_by = cursor.getString(Updated_byColumnIndex);
String updated_date = cursor.getString(Updated_dateColumnIndex);
String date_created = cursor.getString(Date_CreatedColumnIndex);
String is_active = cursor.getString(IsActiveColumnIndex);
String payment_method = cursor.getString(PaymentMethodColumnIndex);
String created_by = cursor.getString(Created_ByColumnIndex);
result += firstname + " " + lastname + " " + email + " " + address + " " + enterprise + " " + mobile + " " + phone +
" " + jobpos + " " + update_by + " " + updated_date + " " + date_created + " " + is_active + " " + payment_method + " " + created_by + "\n\n";
System.getProperty("line.separator");
}
//To retrieve the purchase invoice table
while(cursor1.moveToNext()){
String supplier = cursor1.getString(supplierColumnIndex);
String paymentdate = cursor1.getString(PaymentDateColumnIndex);
String duedate = cursor1.getString(DueDateColumnIndex);
String balance = cursor1.getString(BalanceeColumnIndex);
String paidamount = cursor1.getString(PaidAmountDateColumnIndex);
String total = cursor1.getString(TotaleColumnIndex);
String status = cursor1.getString(StatusColumnIndex);
String invoice = cursor1.getString(InvoiceDateColumnIndex);
String revenue = cursor1.getString(RevenueColumnIndex);
String createdby = cursor1.getString(CreatedByColumnIndex);
String createddate = cursor1.getString(CreatedtDateColumnIndex);
String updatedby = cursor1.getString(UpdatedByColumnIndex);
String updateddate = cursor1.getString(UpdatedDateColumnIndex);
String isactive = cursor1.getString(Is_ACtiveDateColumnIndex);
result += supplier + " " + paymentdate + " " + duedate + " " + balance + " " + paidamount + " " + total + " " +
status + " " + invoice + " " + revenue + " " + createdby + " " + createddate + " " + updatedby + " " + updateddate + " " + isactive +" \n\n" ;
System.getProperty("line.seperator");
}
//To retrieve the product table data
while(cursor2.moveToNext()){
String productname = cursor2.getString(productnameColumnIndex);
String productsku = cursor2.getString(productSKUColumnIndex);
String productvariant = cursor2.getString(productvariantColumnIndex);
String producttype = cursor2.getString(producttype_IDColumnIndex);
String productcategory = cursor2.getString(productCategory_IDColumnIndex);
String productonhand = cursor2.getString(productOnhandColumnIndex);
String productfulfilled = cursor2.getString(productfulfilledColumnIndex);
String productinstock = cursor2.getString(productInstockColumnIndex);
String productcreatedby = cursor2.getString(productCreatedByColumnIndex);
String productcreateddate = cursor2.getString(productCreatedDateColumnIndex);
String productupdatedby = cursor2.getString(productUpdatedByColumnIndex);
String productupdateddate = cursor2.getString(productUpdatedDateColumnIndex);
String productisactive = cursor2.getString(productisactiveColumnIndex);
result += productname + " " + productsku + " " + productvariant + " " + producttype + " " + productcategory + " " +
productonhand + " " + productfulfilled + " " + productinstock + " " + productcreatedby + " " + productcreateddate +
" " + productupdatedby + " " + productupdateddate + " " + productisactive + "\n\n ";
System.getProperty("line.seperator");
}
while(cursor3.moveToNext()){
String goodorderidfk = cursor3.getString(good_orderID_FKColumnIndex);
String goodstatus = cursor3.getString(good_orderstatusColumnIndex);
String gooddeliverto = cursor3.getString(good_delivertoColumnIndex);
String goodwarehouse = cursor3.getString(good_warehouseColumnIndex);
String goodprinted = cursor3.getString(good_printedColumnIndex);
String goodpacked = cursor3.getString(good_packedColumnIndex);
String goodpicked = cursor3.getString(good_pickedColumnIndex);
String goodshipped = cursor3.getString(good_shippedColumnIndex);
String goodcreatedby = cursor3.getString(good_createdbyColumnIndex);
String goodcreateddate = cursor3.getString(good_createddatedrderIDColumnIndex);
String goodupdatedby = cursor3.getString(good_updatedbyColumnIndex);
String goodupdateddate = cursor3.getString(good_updateddateColumnIndex);
String goodisactive = cursor3.getString(good_isactiveColumnIndex);
result += goodorderidfk + " " + goodstatus + " " + gooddeliverto + " " + goodwarehouse + " " + goodprinted + " " +
goodpacked + " " + goodpicked + " " + goodshipped + " " + goodcreatedby + " " + goodcreateddate + " " +
goodupdatedby + " " + goodupdateddate + " " + goodisactive + " ";
System.getProperty("line.seperator");
}
cursor.close();
cursor1.close();
cursor2.close();
cursor3.close();
db.close();
return result;
}
public Location getLocation(String date) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + Locations_entry.LOCATION_TABLE_NAME + " WHERE "
+ Locations_entry.CURRENT_DATE + " = '" + date + "'";
Log.e("DatabaseHelper", selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
Log.v("tempMethod","No of rows: "+c.getCount());
int locationdate=c.getColumnIndex(Locations_entry.CURRENT_DATE);
if (c != null)
c.moveToFirst();
Location td = null;
while(c.moveToNext())
{
td = new Location();
td.setId((c.getInt(c.getColumnIndex(Locations_entry.LOCATION_ID))));
td.setLatitude((c.getString(c.getColumnIndex(Locations_entry.LOCATION_LATITUDE))));
td.setLongitude(c.getString(c.getColumnIndex(Locations_entry.LOCATION_LONGITUDE)));
//String x= td.getLatitude();
//String y=td.getLongitude();
Log.v("DatabaseHelper",td.getId()+"-"+td.getLatitude()+"-"+td.getLongitude()+"-"+c.getString(locationdate));
//LatLng latLng= new LatLng(x,y);
//maps.addMarker( new MarkerOptions().position(x,y).title("Hello world"));
}
return td;
}
public void showmap( String x, String y ){
}
} | [
"urjkhan01@gmail.com"
] | urjkhan01@gmail.com |
f16e17221f96750c4dff05095654dd7a79767324 | fff4ff44c3883684603dd32c456421ba252f12b1 | /app/src/main/java/soexample/umeng/com/gouwuche/utils/HttpUtils.java | beabfca2e9badd22f710ccda0860d7be8162ae21 | [] | no_license | baijingping/gouwuche03 | 21409966a191c7338f9a1385e0f3b44a17881cb1 | 8be48ac2d8b9cb33210d4e82d499146b2bd004e0 | refs/heads/master | 2020-04-02T17:46:29.700204 | 2018-10-24T07:49:15 | 2018-10-24T07:49:15 | 154,671,484 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,372 | java | package soexample.umeng.com.gouwuche.utils;
import android.os.Handler;
import android.os.Looper;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import soexample.umeng.com.gouwuche.inat.INatCallBack;
/**
* Created by Shinelon on 2018/10/23.
*/
public class HttpUtils {
private static volatile HttpUtils insenter;
private OkHttpClient client;
private Handler handler=new Handler(Looper.getMainLooper());
private HttpUtils(){
HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client=new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
}
public static HttpUtils getInsenter(){
if (insenter==null){
synchronized (HttpUtils.class){
if (null==insenter){
insenter=new HttpUtils();
}
}
}
return insenter;
}
public void get(String url, final INatCallBack callBack, final Type type){
Request request=new Request.Builder()
.get()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.failer(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Gson gson=new Gson();
final Object o = gson.fromJson(result, type);
handler.post(new Runnable() {
@Override
public void run() {
callBack.success(o);
}
});
}
});
}
}
| [
"1435590723@qq.com"
] | 1435590723@qq.com |
4c28d7e65ceb6367739eab7058c7c57f9e79e401 | 441d55b88a5c12d1fdffb49679347a668a57aa9a | /User_Notes_Application/src/main/java/com/notes/entity/NoteTo.java | 2ed4caae452c680b1d141548d344fe197140a300 | [] | no_license | JagmohanRawat/GotPrint | bafdbca9647986c5b0a42ccfb817ca6149bcb1c4 | 56d5717419c9124e917f872909d7aca8d85e39cc | refs/heads/master | 2021-01-18T15:22:56.578543 | 2017-08-15T15:39:11 | 2017-08-15T15:39:11 | 100,378,450 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 681 | java | package com.notes.entity;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NoteTo {
public NoteTo() {
}
public NoteTo(String title, String note) {
this.title = title;
this.note = note;
}
@NotEmpty
@Size(max = 50)
private String title;
@Size(max = 1000)
private String note;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
| [
"30972096+JagmohanRawat@users.noreply.github.com"
] | 30972096+JagmohanRawat@users.noreply.github.com |
1d8cb43479ac9f8bebc9e79b45da48617e940cfe | cb6266a854c101ef27abf753e599351f43e79185 | /flutterViewDemo/app/src/main/java/com/trinasolar/flutterviewdemo/MainActivity.java | 26c552613234f17bfd303db86aa406e2a1d85b75 | [] | no_license | luyifei666/AndroidEmbedFlutter | c31de3d82453be47f3b07e906f6c00b6ab4f1968 | a8b2146a9c526c5d9bda470e57f2c1382528c253 | refs/heads/master | 2020-04-13T10:18:29.758031 | 2018-12-26T03:35:05 | 2018-12-26T03:35:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 798 | java | package com.trinasolar.flutterviewdemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button switchBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchBtn = (Button) findViewById(R.id.switch_btn);
switchBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, FlutterActivity.class);
startActivity(intent);
}
});
}
}
| [
"hongfei.wang@trinasolar.com"
] | hongfei.wang@trinasolar.com |
935ea88fa8fb3b9daf53324683bf3f8699221226 | 8c10c89dee9c47de572ecd9288c88581b960cba9 | /CBS-Backend-rev00-master/src/main/java/com/dfq/coeffi/cbs/member/entity/ShareMaster.java | 108c58ae73a2f791e329d45b520554e8156a306e | [] | no_license | shreedharkv/cbsproject | c5d3016eab58aff0ad77605e876a6a98d46e4fa9 | df2ea1233728f6daaf1a190da9697f8a0c56acc1 | refs/heads/master | 2023-02-12T20:04:29.364324 | 2021-01-18T16:21:07 | 2021-01-18T16:21:07 | 330,709,378 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 838 | java | package com.dfq.coeffi.cbs.member.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
@Setter
@Getter
@Entity
public class ShareMaster {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private BigDecimal shareValue;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public BigDecimal getShareValue() {
return shareValue;
}
public void setShareValue(BigDecimal shareValue) {
this.shareValue = shareValue;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | [
"Administrator@DESKTOP-6HJTM75"
] | Administrator@DESKTOP-6HJTM75 |
9153583dc5938155e0dfea2ed8584180299c8e55 | 4a9f8925c21621d006a2ecbb12fc1ea5f0a966f6 | /common-parent/tea-service/src/main/java/me/zhangyu/service/impl/ExamServiceImpl.java | 6767bfee6967b4e2c4fad3c92a0ec4bd3ba212f1 | [] | no_license | yuyuqiang/TeaProject | 07732f07f6e57e367c7cd3dbd1d868fe77ef352f | c7d5773a762f7358d45f42aa120a6f30f83b2054 | refs/heads/master | 2022-11-27T18:26:25.905463 | 2020-05-17T02:59:11 | 2020-05-17T02:59:11 | 248,242,658 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,136 | java | package me.zhangyu.service.impl;
import me.zhangyu.model.Exam;
import me.zhangyu.service.ExamService;
import me.zhangyu.service.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
@Service
@Transactional
public class ExamServiceImpl extends BaseServiceImpl<Exam> implements ExamService {
@Override
public int add(Exam exam) {
return examMapper.add(exam); }
@Override
public int edit(Exam exam) {
return examMapper.edit(exam);
}
@Override
public List<Exam> findList(Map<String, Object> queryMap) {
return examMapper.findList(queryMap); }
@Override
public int delete(Long id) {
return examMapper.delete(id); }
@Override
public Integer getTotal(Map<String, Object> queryMap) {
return examMapper.getTotal(queryMap);
}
@Override
public List<Exam> findListByUser(Map<String, Object> queryMap) {
return examMapper.findListByUser(queryMap);
}
@Override
public Integer getTotalByUser(Map<String, Object> queryMap) {
return examMapper.getTotalByUser(queryMap);
}
@Override
public Exam findById(Long id) {
return examMapper.findById(id);
}
@Override
public int updateExam(Exam exam) {
return examMapper.updateExam(exam);
}
@Override
public Exam findById(int id) {
return null;
}
@Override
public Exam findByUsername(String username) {
return null;
}
@Override
public Exam findByUUId(String uuid) {
return null;
}
@Override
public void deleteById(Integer id) {
}
@Override
public void deleteByUUId(String uuid) {
}
@Override
public void update(Exam exam) {
}
@Override
public void insert(Exam exam) {
}
@Override
public Exam validateUserExist(String username) {
return null;
}
}
| [
"1145192105@qq.com"
] | 1145192105@qq.com |
dd3206625094be00892fa4263d6d58d08dc82b96 | dd8dd5cab1d4a678c412c64f30ef10f9c5d210f1 | /java/0050. Pow(x, n)/code_readable.java | 2ad5e9b2dc39ce332be0b10f2e29965b7fb0c493 | [] | no_license | blacksea3/leetcode | e48a35ad7a1a1bb8dd9a98ffc1af6694c09061ee | 18f87742b64253861ca37a2fb197bb8cb656bcf2 | refs/heads/master | 2021-07-12T04:45:59.428804 | 2020-07-19T02:01:29 | 2020-07-19T02:01:29 | 184,689,901 | 6 | 2 | null | null | null | null | UTF-8 | Java | false | false | 331 | java | class Solution {
public double myPow(double x, int n) {
if(n == 0) return 1;
if(n == Integer.MIN_VALUE){
x = x * x;
n = n/2;
}
if(n < 0) {
n = -n;
x = 1/x;
}
return (n%2 == 0) ? myPow(x * x, n/2) : x * myPow(x * x, n/2);
}
}
| [
"kevinliminhao@gmail.com"
] | kevinliminhao@gmail.com |
398edd1b3edf4e04c1b829b58b562534f56ff6d4 | 471a1d9598d792c18392ca1485bbb3b29d1165c5 | /jadx-MFP/src/main/java/com/google/ads/interactivemedia/v3/internal/xe.java | 522aa0cedc2ffe71df7712f30c2ce1582ca5f351 | [] | no_license | reed07/MyPreferencePal | 84db3a93c114868dd3691217cc175a8675e5544f | 365b42fcc5670844187ae61b8cbc02c542aa348e | refs/heads/master | 2020-03-10T23:10:43.112303 | 2019-07-08T00:39:32 | 2019-07-08T00:39:32 | 129,635,379 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,244 | java | package com.google.ads.interactivemedia.v3.internal;
import java.math.BigInteger;
/* compiled from: IMASDK */
public final class xe extends wz {
private static final Class<?>[] a = {Integer.TYPE, Long.TYPE, Short.TYPE, Float.TYPE, Double.TYPE, Byte.TYPE, Boolean.TYPE, Character.TYPE, Integer.class, Long.class, Short.class, Float.class, Double.class, Byte.class, Boolean.class, Character.class};
private Object b;
public xe(Boolean bool) {
a((Object) bool);
}
public xe(Number number) {
a((Object) number);
}
public xe(String str) {
a((Object) str);
}
/* JADX WARNING: Code restructure failed: missing block: B:16:0x0035, code lost:
if (r0 != false) goto L_0x0037;
*/
/* Code decompiled incorrectly, please refer to instructions dump. */
private final void a(java.lang.Object r8) {
/*
r7 = this;
boolean r0 = r8 instanceof java.lang.Character
if (r0 == 0) goto L_0x0011
java.lang.Character r8 = (java.lang.Character) r8
char r8 = r8.charValue()
java.lang.String r8 = java.lang.String.valueOf(r8)
r7.b = r8
return
L_0x0011:
boolean r0 = r8 instanceof java.lang.Number
r1 = 0
r2 = 1
if (r0 != 0) goto L_0x0037
boolean r0 = r8 instanceof java.lang.String
if (r0 == 0) goto L_0x001d
r0 = 1
goto L_0x0035
L_0x001d:
java.lang.Class r0 = r8.getClass()
java.lang.Class<?>[] r3 = a
int r4 = r3.length
r5 = 0
L_0x0025:
if (r5 >= r4) goto L_0x0034
r6 = r3[r5]
boolean r6 = r6.isAssignableFrom(r0)
if (r6 == 0) goto L_0x0031
r0 = 1
goto L_0x0035
L_0x0031:
int r5 = r5 + 1
goto L_0x0025
L_0x0034:
r0 = 0
L_0x0035:
if (r0 == 0) goto L_0x0038
L_0x0037:
r1 = 1
L_0x0038:
com.google.ads.interactivemedia.v3.internal.tt.a(r1)
r7.b = r8
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.ads.interactivemedia.v3.internal.xe.a(java.lang.Object):void");
}
public final boolean h() {
return this.b instanceof Boolean;
}
public final boolean f() {
Object obj = this.b;
if (obj instanceof Boolean) {
return ((Boolean) obj).booleanValue();
}
return Boolean.parseBoolean(b());
}
public final boolean i() {
return this.b instanceof Number;
}
public final Number a() {
Object obj = this.b;
return obj instanceof String ? new yn((String) obj) : (Number) obj;
}
public final boolean j() {
return this.b instanceof String;
}
public final String b() {
Object obj = this.b;
if (obj instanceof Number) {
return a().toString();
}
if (obj instanceof Boolean) {
return ((Boolean) obj).toString();
}
return (String) obj;
}
public final double c() {
return this.b instanceof Number ? a().doubleValue() : Double.parseDouble(b());
}
public final long d() {
return this.b instanceof Number ? a().longValue() : Long.parseLong(b());
}
public final int e() {
return this.b instanceof Number ? a().intValue() : Integer.parseInt(b());
}
public final int hashCode() {
if (this.b == null) {
return 31;
}
if (a(this)) {
long longValue = a().longValue();
return (int) ((longValue >>> 32) ^ longValue);
}
Object obj = this.b;
if (!(obj instanceof Number)) {
return obj.hashCode();
}
long doubleToLongBits = Double.doubleToLongBits(a().doubleValue());
return (int) ((doubleToLongBits >>> 32) ^ doubleToLongBits);
}
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
xe xeVar = (xe) obj;
if (this.b == null) {
return xeVar.b == null;
}
if (a(this) && a(xeVar)) {
return a().longValue() == xeVar.a().longValue();
}
if (!(this.b instanceof Number) || !(xeVar.b instanceof Number)) {
return this.b.equals(xeVar.b);
}
double doubleValue = a().doubleValue();
double doubleValue2 = xeVar.a().doubleValue();
return doubleValue == doubleValue2 || (Double.isNaN(doubleValue) && Double.isNaN(doubleValue2));
}
private static boolean a(xe xeVar) {
Object obj = xeVar.b;
if (!(obj instanceof Number)) {
return false;
}
Number number = (Number) obj;
if ((number instanceof BigInteger) || (number instanceof Long) || (number instanceof Integer) || (number instanceof Short) || (number instanceof Byte)) {
return true;
}
return false;
}
}
| [
"anon@ymous.email"
] | anon@ymous.email |
19372efa704b5ce6e293ed5a5a58bee51cbcdd94 | 4672ce38c73a15b2f57377ceea13f5f90b252d32 | /gmall-admin/src/main/java/com/atguigu/modules/oss/cloud/CloudStorageConfig.java | 8a8a5b4268dc2060f0f5aee35e6ccf4b8404729f | [
"Apache-2.0"
] | permissive | LRCgtp/shop-plateform | 420863b1d4593349bea91b0e738ce4833ead2add | 59e2df3a555e9c278dac97d87d8ab2a2921d15f1 | refs/heads/master | 2022-07-25T22:41:43.543678 | 2020-04-12T11:12:05 | 2020-04-12T11:12:05 | 254,298,060 | 0 | 0 | null | 2022-07-06T20:49:10 | 2020-04-09T07:11:25 | JavaScript | UTF-8 | Java | false | false | 3,604 | java | /**
* Copyright (c) 2016-2019 谷粒开源 All rights reserved.
* <p>
* https://www.guli.cloud
* <p>
* 版权所有,侵权必究!
*/
package com.atguigu.modules.oss.cloud;
import com.atguigu.common.validator.group.AliyunGroup;
import com.atguigu.common.validator.group.QcloudGroup;
import com.atguigu.common.validator.group.QiniuGroup;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import org.hibernate.validator.constraints.URL;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* 云存储配置信息
*
* @author Mark sunlightcs@gmail.com
*/
@Data
public class CloudStorageConfig implements Serializable {
private static final long serialVersionUID = 1L;
//类型 1:七牛 2:阿里云 3:腾讯云
@Range(min = 1, max = 3, message = "类型错误")
private Integer type;
//七牛绑定的域名
@NotBlank(message = "七牛绑定的域名不能为空" , groups = QiniuGroup.class)
@URL(message = "七牛绑定的域名格式不正确" , groups = QiniuGroup.class)
private String qiniuDomain;
//七牛路径前缀
private String qiniuPrefix;
//七牛ACCESS_KEY
@NotBlank(message = "七牛AccessKey不能为空" , groups = QiniuGroup.class)
private String qiniuAccessKey;
//七牛SECRET_KEY
@NotBlank(message = "七牛SecretKey不能为空" , groups = QiniuGroup.class)
private String qiniuSecretKey;
//七牛存储空间名
@NotBlank(message = "七牛空间名不能为空" , groups = QiniuGroup.class)
private String qiniuBucketName;
//阿里云绑定的域名
@NotBlank(message = "阿里云绑定的域名不能为空" , groups = AliyunGroup.class)
@URL(message = "阿里云绑定的域名格式不正确" , groups = AliyunGroup.class)
private String aliyunDomain;
//阿里云路径前缀
private String aliyunPrefix;
//阿里云EndPoint
@NotBlank(message = "阿里云EndPoint不能为空" , groups = AliyunGroup.class)
private String aliyunEndPoint;
//阿里云AccessKeyId
@NotBlank(message = "阿里云AccessKeyId不能为空" , groups = AliyunGroup.class)
private String aliyunAccessKeyId;
//阿里云AccessKeySecret
@NotBlank(message = "阿里云AccessKeySecret不能为空" , groups = AliyunGroup.class)
private String aliyunAccessKeySecret;
//阿里云BucketName
@NotBlank(message = "阿里云BucketName不能为空" , groups = AliyunGroup.class)
private String aliyunBucketName;
//腾讯云绑定的域名
@NotBlank(message = "腾讯云绑定的域名不能为空" , groups = QcloudGroup.class)
@URL(message = "腾讯云绑定的域名格式不正确" , groups = QcloudGroup.class)
private String qcloudDomain;
//腾讯云路径前缀
private String qcloudPrefix;
//腾讯云AppId
@NotNull(message = "腾讯云AppId不能为空" , groups = QcloudGroup.class)
private Integer qcloudAppId;
//腾讯云SecretId
@NotBlank(message = "腾讯云SecretId不能为空" , groups = QcloudGroup.class)
private String qcloudSecretId;
//腾讯云SecretKey
@NotBlank(message = "腾讯云SecretKey不能为空" , groups = QcloudGroup.class)
private String qcloudSecretKey;
//腾讯云BucketName
@NotBlank(message = "腾讯云BucketName不能为空" , groups = QcloudGroup.class)
private String qcloudBucketName;
//腾讯云COS所属地区
@NotBlank(message = "所属地区不能为空" , groups = QcloudGroup.class)
private String qcloudRegion;
}
| [
"3115679714@qq.com"
] | 3115679714@qq.com |
6176a74056021fdb3eb84092351c4c39e8b03e1a | 8e2e8cdffcf208a9738096b4a23568a60a547ddc | /app/src/main/java/com/example/user/myapp2/login/Login2Activity.java | 40246fff52ed984cb1f7286f085bc0aabd158c0d | [] | no_license | andylee3d/MyApp2 | a51d41d48affdbbdfdbe2d07fe51d6d04a79e658 | e1f608227912e171f165cd97bc91148cdc36b82c | refs/heads/master | 2021-01-21T01:50:50.642941 | 2016-06-11T09:01:36 | 2016-06-11T09:01:36 | 60,386,214 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,569 | java | package com.example.user.myapp2.login;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import com.example.user.myapp2.R;
import com.example.user.myapp2.member.MemberBean;
import com.example.user.myapp2.member.MemberDAO;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via email/password.
*/
public class Login2Activity extends Activity implements View.OnClickListener{
EditText etID,etPW;
TextView textResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etID = (EditText) findViewById(R.id.etID);
etPW = (EditText) findViewById(R.id.etPW);
textResult = (TextView) findViewById(R.id.textResult);
((Button)findViewById(R.id.btSignup)).setOnClickListener(this);
}
@Override
public void onClick(View v) {
String id = etID.getText().toString();
String pw = etPW.getText().toString();
MemberBean member = new MemberBean();
// MemberServiceImpl service = new MemberServiceImpl();
MemberDAO dao = new MemberDAO(this.getApplicationContext());
member.setId(id);
member.setPw(pw);
member = dao.login(member);
Log.i("DB 다녀온 결과 ID", member.getId());
if(member==null){
textResult.setText("로그인 결과 : 실패");
}else {
textResult.setText("로그인 결과 : "+member.getName()+" 환영합니다");
}
}
}
| [
"andylee3d@gmail.com"
] | andylee3d@gmail.com |
dcfda14fe7e235719ad9bc7bff3e88921aca76fd | b74bc2324c6b6917d24e1389f1cf95936731643f | /basedata/src/main/java/com/wuyizhiye/basedata/basic/model/BaseConfigConstants.java | b7b7d83eab52114a071f99315235fda34241483e | [] | no_license | 919126624/Feiying- | ebeb8fcfbded932058347856e2a3f38731821e5e | d3b14ff819cc894dcbe80e980792c08c0eb7167b | refs/heads/master | 2021-01-13T00:40:59.447803 | 2016-03-24T03:41:30 | 2016-03-24T03:41:30 | 54,537,727 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,832 | java | package com.wuyizhiye.basedata.basic.model;
/**
* @ClassName BaseConfigConstants
* @Description TODO
* @author li.biao
* @date 2015-4-2
*/
public class BaseConfigConstants {
public static final String HOUSEPOWERINDEX_KEY = "housepowerindex";//权限索引库
public static final String HOUSEINDEX_KEY = "houseindex";//无权限索引库
public static final String HOMEPAGE_KEY = "homeurl"; //登录页面
public static final String LICENSE_KEY = "licensepath"; //license
public static final String INDEXSERVER_KEY = "indexurl"; //索引服务器地址
public static final String RESOURCEINDEX_KEY = "resourceindex"; //资源客索引
public static final String CONTROLMODE_KEY = "controlmode"; //控制模式
public static final String MAIL_CLIENT_ID = "mailclientid"; //邮件client_id
public static final String MAIL_CLIENT_SECRET = "mailclientsecret"; //邮件client_secret
public static final String OS_NAME = "osname"; //操作系统
public static final String CUSTOMER_NO = "customerno"; //操作系统
public static final String SYNCBASEDATAURL = "syncbasedataurl"; //同步基础数据url
public static final String SYNCSQLURL = "syncsqlurl"; //同步脚本url
public static final String OS_NETWORK_CARD = "osnetworkcard"; //网卡名
public static final String QYWECHAT_CROPID = "qywechatcropid"; //公司ID
public static final String QYWECHAT_SECRET = "qywechatsecret"; //开发者密钥
public static final String LOCAL_LICENSE = "locallicense"; //是否启用本地license
public static final String REMOTE_LICENSE = "remotelicense"; //是否启用本地license
public static final String BROWER_RESTRICT = "browerrestrict"; //浏览器限制
public static final String REMOTE_SERVERURL = "remoteserverurl"; //同步基础数据url
}
| [
"919126624@qq.com"
] | 919126624@qq.com |
c0eaf32ffe2fd662e3f2c0c8d06e641486b6fb50 | 63b0d30b49825165ac620f9b5c5a68c6af686804 | /src/main/java/me/egaetan/slay/MainTmp.java | 42d7b472c9cde4d383983330c42de4bc8e9dc7d7 | [] | no_license | geleouet/summer-slay | 74cda7ab398fbefec008a9e8d6bc083ac3ebe236 | b4488360bea1d13abfd908194232b9a64701c22b | refs/heads/main | 2023-05-11T19:37:37.290782 | 2021-06-03T07:46:20 | 2021-06-03T07:46:20 | 362,357,575 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 179 | java | package me.egaetan.slay;
public class MainTmp {
public static void main(String[] args) {
System.out.println(String.format(new Main.Description().permArmure(), ""+2));
}
}
| [
"gaetan.eleouet@gmail.com"
] | gaetan.eleouet@gmail.com |
0e98d967a4cc0da93281f1a1293bb5eb5f61b794 | 09c0498d9ab6534c705e23a3876cd9dc7f4bf291 | /src/day18/WebtableDynamic.java | 77e1d071dc3f699ddc7f2fb476d5cdb9f09f6801 | [] | no_license | SaiKrishna12/May25Batch | 3d8b5c1d3eb9bb4b7e35c5ed330452f94edb354c | 0dac1f36ae8bf0446375e02616383ff5e9fb577f | refs/heads/master | 2020-06-06T14:27:20.340585 | 2015-07-10T14:37:19 | 2015-07-10T14:37:19 | 39,013,168 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,056 | java | package day18;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class WebtableDynamic {
FirefoxDriver driver;
@BeforeMethod
public void setUp()
{
ProfilesIni pr=new ProfilesIni();
FirefoxProfile fp=pr.getProfile("SeleniumUser");
driver=new FirefoxDriver(fp);
driver.get("http://www.timeanddate.com/worldclock/");
}
@Test
public void webtableTest()
{
WebElement table=driver.findElement(By.xpath("html/body/div[1]/div[7]/section[2]/div[1]/table"));
List<WebElement> rows=table.findElements(By.tagName("tr"));
for(int i=0;i<rows.size();i++)
{
List<WebElement> cols=rows.get(i).findElements(By.tagName("td"));
for(int j=0;j<cols.size();j++)
{
System.out.print(cols.get(j).getText()+" ");
}
System.out.println();
}
}
}
| [
"saikrishna_gandham@yahoo.co.in"
] | saikrishna_gandham@yahoo.co.in |
ad0495459b495dd013391b735908157ec3b7a38a | 583fb54eb8476efa079c917f21c858123a16fcf2 | /main/java/Day13Problems/Library.java | bb4a959631168d8c5e05414b310814b4f2f4bdae | [] | no_license | AmitSisodiya275/Day13Problems | ca6064f82933d26d68a0ed8df170503c53475e37 | 46c9c45272e739e259260f22ba4486b05f598b51 | refs/heads/master | 2023-08-21T04:56:59.975469 | 2021-10-06T08:59:02 | 2021-10-06T08:59:02 | 413,448,286 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package Day13Problems;
public class Library {
public boolean someLibraryMethod() {
return true;
}
}
| [
"amitsisodiya275@gmail.com"
] | amitsisodiya275@gmail.com |
1eec2e53f17e492a2ddb3e788e23029d38af3c0e | a9aa928ef12b55a4452450c488516564a3570d82 | /src/test/java/com/w2a/rough/TestTimeStamp.java | c4b7c69651f7af9ff14bf7fd1181ac0bdba2355b | [] | no_license | Tony-Lu/DataDriven | 7e09f3808aaf8b65a27db2ca4655eb2d9499d32c | fa9fa19624c2ca1f02247b3eaa68e89713d247e8 | refs/heads/master | 2020-05-05T13:16:49.615110 | 2019-04-16T19:45:06 | 2019-04-16T19:45:06 | 180,070,236 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 415 | java | package com.w2a.rough;
import java.util.Date;
public class TestTimeStamp {
public static void main(String[] args) {
//this is for test jenkins trigger new build once git checked in
//using Eclipse plugin commit to git
Date d = new Date();
String screenShotName = d.toString().replace(":", "_").replace(" ", "_")+".jpg";
System.out.println(screenShotName);
}
}
| [
"xudong.lu@yahoo.com"
] | xudong.lu@yahoo.com |
634799bf545d629f9b46b936c609930c7369a7f9 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/29/29_1eb8d23f4ede75c6c55381ee5d5a92f5f32d38d5/Bashoid/29_1eb8d23f4ede75c6c55381ee5d5a92f5f32d38d5_Bashoid_s.java | dac511579ba403c5f3c24cdf9b9924562ef41795 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 1,016 | java | package bashoid;
import bash.Bash;
import java.util.ArrayList;
import org.jibble.pircbot.*;
public class Bashoid extends PircBot {
public Bashoid() {
setName("bashoid");
setAutoNickChange(true);
setMessageDelay(0);
}
@Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
if ( Bash.isBashMessage(message) )
sendListOfMessages(channel, new Bash().getOutput() );
}
@Override
protected void onKick(String channel, String kickerNick, String kickerLogin, String kickerHostname, String recipientNick, String reason) {
if ( recipientNick.equals( getNick() ) ) {
joinChannel(channel);
sendMessage(channel, Colors.BOLD + "sorry...");
}
}
protected void sendListOfMessages(String target, ArrayList<String> output) {
for ( String line : output )
sendMessage(target, line);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
2d1e6b509bd0dc09ddaecfb79a1f11acae502c54 | a434eacb645dfc1f1fcfb88dd59cbfd1a936fab2 | /src/reinfo.java | b925da86a44e2b4a07eea2d4abe5bc773019c894 | [] | no_license | breyolinfebi/Clinical-Database-Management-System | d9312b7758ed0ec3f1fc04e2ee3c4dc080a08cc7 | 6222a0a6c4634344de74c639981c75a08ee290bf | refs/heads/master | 2023-06-11T05:28:04.037480 | 2021-06-19T16:56:07 | 2021-06-19T16:56:07 | 378,462,010 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,644 | java |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author breyo
*/
public class reinfo extends javax.swing.JFrame {
/**
* Creates new form reinfo
*/
public reinfo() {
initComponents();
setSize(560,400);
listfill();
}
private void listfill(){
DefaultListModel m = new DefaultListModel();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
//step3 create the statement object
//step2 create the connection object
Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:breyo","system","hackpassword123");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from RECEP");
while(rs.next()){
String id = rs.getString("id");
m.addElement(id);
}
jList1.setModel(m);
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(F1.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
name = new javax.swing.JTextField();
gen = new javax.swing.JTextField();
ag = new javax.swing.JTextField();
num = new javax.swing.JTextField();
user = new javax.swing.JTextField();
pass = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel9 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel1.setText("Receptionist Information");
getContentPane().add(jLabel1);
jLabel1.setBounds(240, 30, 196, 34);
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(10, 90, 58, 130);
jLabel2.setText("Receptionist Id");
getContentPane().add(jLabel2);
jLabel2.setBounds(10, 65, 72, 14);
jLabel3.setText("Name");
getContentPane().add(jLabel3);
jLabel3.setBounds(190, 80, 60, 14);
jLabel4.setText("Gender");
getContentPane().add(jLabel4);
jLabel4.setBounds(190, 120, 60, 14);
jLabel5.setText("Age");
getContentPane().add(jLabel5);
jLabel5.setBounds(210, 160, 30, 14);
jLabel6.setText("Contact Number");
getContentPane().add(jLabel6);
jLabel6.setBounds(148, 190, 90, 14);
jLabel7.setText("username");
getContentPane().add(jLabel7);
jLabel7.setBounds(167, 240, 70, 14);
jLabel8.setText("Password");
getContentPane().add(jLabel8);
jLabel8.setBounds(166, 280, 70, 14);
getContentPane().add(name);
name.setBounds(250, 70, 120, 30);
getContentPane().add(gen);
gen.setBounds(250, 110, 120, 30);
getContentPane().add(ag);
ag.setBounds(250, 150, 120, 30);
getContentPane().add(num);
num.setBounds(250, 190, 120, 30);
getContentPane().add(user);
user.setBounds(250, 232, 120, 30);
getContentPane().add(pass);
pass.setBounds(250, 270, 120, 30);
jButton1.setText("Update");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(142, 330, 90, 23);
jButton2.setText("Delete");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2);
jButton2.setBounds(273, 330, 80, 23);
jButton3.setText("Back");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
getContentPane().add(jButton3);
jButton3.setBounds(395, 330, 55, 23);
jLabel9.setIcon(new javax.swing.ImageIcon("C:\\Users\\breyo\\Pictures\\Saved Pictures\\istockphoto-1003420604-1024x1024.jpg")); // NOI18N
jLabel9.setText("jLabel9");
getContentPane().add(jLabel9);
jLabel9.setBounds(-6, -6, 560, 370);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_jButton3ActionPerformed
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
// TODO add your handling code here:
String tmp=(String)jList1.getSelectedValue();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
//step3 create the statement object
//step2 create the connection object
Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:breyo","system","hackpassword123");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs= null;
PreparedStatement pst = null;
// String r = pid.getText();
String sql = "SELECT * FROM RECEP WHERE ID=?";
pst = con.prepareStatement(sql);
pst.setString(1, tmp);
rs=pst.executeQuery();
if(rs.next()){
//String ad0 = rs.getString("reg");
//rid.setText(ad0);
String ad1 = rs.getString("name");
name.setText(ad1);
String ad2 = rs.getString("gender");
gen.setText(ad2);
int ad3 = rs.getInt("age");
String st1 = Integer.toString(ad3);
ag.setText(st1);
int ad4 = rs.getInt("num");
String st2 = Integer.toString(ad4);
num.setText(st2);
String ad5 = rs.getString("username");
user.setText(ad5);
String ad6 = rs.getString("password");
pass.setText(ad6);
}
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(F1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}//GEN-LAST:event_jList1MouseClicked
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:breyo", "system", "hackpassword123");
if (con != null) {
System.out.println("Connected to the database!");
} else
{
System.out.println("Failed to make connection!");
}
String tmp=(String)jList1.getSelectedValue();
//String tmp = pid.getText();
java.sql.Statement st = null;
Statement stmt = con.createStatement();
String n = name.getText();
String g = gen.getText();
int a = Integer.parseInt(ag.getText());
int nm = Integer.parseInt(num.getText());
String ar = user.getText();
String d = pass.getText();
String q1 = "UPDATE RECEP SET NAME='"+n+"',GENDER='"+g+"',AGE='"+a+"',NUM = '"+nm+"',USERNAME='"+ar+"',PASSWORD='"+d+"'";
int x = stmt.executeUpdate(q1);
if(x>0){
JOptionPane.showMessageDialog(null,"DETAILS UPDATED!");
}
else
{
JOptionPane.showMessageDialog(null,"INVALID!");
}
}
catch (SQLException e)
{
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
System.out.println(e);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR", "WARNING", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
System.out.println(e);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:breyo", "system", "hackpassword123");
if (con != null) {
System.out.println("Connected to the database!");
} else
{
System.out.println("Failed to make connection!");
}
String tmp=(String)jList1.getSelectedValue();
String r = "receptionist";
java.sql.Statement st = null;
Statement stmt = con.createStatement();
String q1 = "DELETE FROM RECEP WHERE ID='"+ tmp +"'";
String q2 ="DELETE FROM LOGIN WHERE USERTYPE='"+ r +"'";
int y = stmt.executeUpdate(q2);
int x = stmt.executeUpdate(q1);
if(x>0){
JOptionPane.showMessageDialog(null,"DETAILS DELETED!");
}
else
{ try{
JOptionPane.showMessageDialog(null,"INVALID!");
}catch(Exception e){System.out.println(e);}
}
}
catch (SQLException e)
{
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR", "WARNING", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();}
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(reinfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(reinfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(reinfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(reinfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new reinfo().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField ag;
private javax.swing.JTextField gen;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JList<String> jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField name;
private javax.swing.JTextField num;
private javax.swing.JTextField pass;
private javax.swing.JTextField user;
// End of variables declaration//GEN-END:variables
}
| [
"breyo@DESKTOP-TN3DR0Q"
] | breyo@DESKTOP-TN3DR0Q |
8d6931db5acc2c4321fac12253e621daa26e30e6 | 2d978951f0aeadf15a1d0b1473b586f017e65e44 | /FWC/kingkong/src/androidTest/java/com/mageeyang/kingkong/ApplicationTest.java | 50899b7b03a0436757591f4f9f46b3eb48cc00f6 | [
"Apache-2.0"
] | permissive | mageeYang/FWC | faee50618dc61be8a14189a73699b1556fb5d2f5 | b5a21f78393516a782f5870b129e85e82445c021 | refs/heads/master | 2020-04-13T09:38:16.679087 | 2016-09-19T08:18:02 | 2016-09-19T08:18:02 | 68,091,868 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 353 | java | package com.mageeyang.kingkong;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"ym31316120@gmail.com"
] | ym31316120@gmail.com |
0c4c8adc44ae682630aabb28d3bb3c6bb33a89a4 | 733aa85ae1e404281aff414a487789463474fe95 | /build/javasqlc/srcAD/org/openbravo/erpWindows/FinancialAccount/ImportedBankStatementsData.java | 0f89361667d29b030de5187b650ee1ab4b634720 | [] | no_license | khayalalwataniya/OpenbravoSyariah | 6f5d8e157f23f73df612fbb07410d72e64baefc3 | aeed1b8c09ea81c45b3a6c179a8f37db28b7b45e | refs/heads/master | 2020-05-29T08:46:17.790189 | 2016-02-15T03:58:39 | 2016-02-15T03:58:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 39,861 | java | //Sqlc generated V1.O00-1
package org.openbravo.erpWindows.FinancialAccount;
import java.sql.*;
import org.apache.log4j.Logger;
import javax.servlet.ServletException;
import org.openbravo.data.FieldProvider;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.data.UtilSql;
import org.openbravo.service.db.QueryTimeOutUtil;
import org.openbravo.database.SessionInfo;
import java.util.*;
/**
WAD Generated class
*/
class ImportedBankStatementsData implements FieldProvider {
static Logger log4j = Logger.getLogger(ImportedBankStatementsData.class);
private String InitRecordNumber="0";
public String created;
public String createdbyr;
public String updated;
public String updatedTimeStamp;
public String updatedby;
public String updatedbyr;
public String documentno;
public String cDoctypeId;
public String cDoctypeIdr;
public String name;
public String isactive;
public String importdate;
public String statementdate;
public String filename;
public String finReconciliationId;
public String notes;
public String posted;
public String postedBtn;
public String emAprmProcessBsForce;
public String emAprmProcessBsForceBtn;
public String emAprmProcessBs;
public String emAprmProcessBsBtn;
public String adOrgId;
public String processing;
public String processed;
public String finBankstatementId;
public String adClientId;
public String finFinancialAccountId;
public String language;
public String adUserClient;
public String adOrgClient;
public String createdby;
public String trBgcolor;
public String totalCount;
public String dateTimeFormat;
public String getInitRecordNumber() {
return InitRecordNumber;
}
public String getField(String fieldName) {
if (fieldName.equalsIgnoreCase("CREATED"))
return created;
else if (fieldName.equalsIgnoreCase("CREATEDBYR"))
return createdbyr;
else if (fieldName.equalsIgnoreCase("UPDATED"))
return updated;
else if (fieldName.equalsIgnoreCase("UPDATED_TIME_STAMP") || fieldName.equals("updatedTimeStamp"))
return updatedTimeStamp;
else if (fieldName.equalsIgnoreCase("UPDATEDBY"))
return updatedby;
else if (fieldName.equalsIgnoreCase("UPDATEDBYR"))
return updatedbyr;
else if (fieldName.equalsIgnoreCase("DOCUMENTNO"))
return documentno;
else if (fieldName.equalsIgnoreCase("C_DOCTYPE_ID") || fieldName.equals("cDoctypeId"))
return cDoctypeId;
else if (fieldName.equalsIgnoreCase("C_DOCTYPE_IDR") || fieldName.equals("cDoctypeIdr"))
return cDoctypeIdr;
else if (fieldName.equalsIgnoreCase("NAME"))
return name;
else if (fieldName.equalsIgnoreCase("ISACTIVE"))
return isactive;
else if (fieldName.equalsIgnoreCase("IMPORTDATE"))
return importdate;
else if (fieldName.equalsIgnoreCase("STATEMENTDATE"))
return statementdate;
else if (fieldName.equalsIgnoreCase("FILENAME"))
return filename;
else if (fieldName.equalsIgnoreCase("FIN_RECONCILIATION_ID") || fieldName.equals("finReconciliationId"))
return finReconciliationId;
else if (fieldName.equalsIgnoreCase("NOTES"))
return notes;
else if (fieldName.equalsIgnoreCase("POSTED"))
return posted;
else if (fieldName.equalsIgnoreCase("POSTED_BTN") || fieldName.equals("postedBtn"))
return postedBtn;
else if (fieldName.equalsIgnoreCase("EM_APRM_PROCESS_BS_FORCE") || fieldName.equals("emAprmProcessBsForce"))
return emAprmProcessBsForce;
else if (fieldName.equalsIgnoreCase("EM_APRM_PROCESS_BS_FORCE_BTN") || fieldName.equals("emAprmProcessBsForceBtn"))
return emAprmProcessBsForceBtn;
else if (fieldName.equalsIgnoreCase("EM_APRM_PROCESS_BS") || fieldName.equals("emAprmProcessBs"))
return emAprmProcessBs;
else if (fieldName.equalsIgnoreCase("EM_APRM_PROCESS_BS_BTN") || fieldName.equals("emAprmProcessBsBtn"))
return emAprmProcessBsBtn;
else if (fieldName.equalsIgnoreCase("AD_ORG_ID") || fieldName.equals("adOrgId"))
return adOrgId;
else if (fieldName.equalsIgnoreCase("PROCESSING"))
return processing;
else if (fieldName.equalsIgnoreCase("PROCESSED"))
return processed;
else if (fieldName.equalsIgnoreCase("FIN_BANKSTATEMENT_ID") || fieldName.equals("finBankstatementId"))
return finBankstatementId;
else if (fieldName.equalsIgnoreCase("AD_CLIENT_ID") || fieldName.equals("adClientId"))
return adClientId;
else if (fieldName.equalsIgnoreCase("FIN_FINANCIAL_ACCOUNT_ID") || fieldName.equals("finFinancialAccountId"))
return finFinancialAccountId;
else if (fieldName.equalsIgnoreCase("LANGUAGE"))
return language;
else if (fieldName.equals("adUserClient"))
return adUserClient;
else if (fieldName.equals("adOrgClient"))
return adOrgClient;
else if (fieldName.equals("createdby"))
return createdby;
else if (fieldName.equals("trBgcolor"))
return trBgcolor;
else if (fieldName.equals("totalCount"))
return totalCount;
else if (fieldName.equals("dateTimeFormat"))
return dateTimeFormat;
else {
log4j.debug("Field does not exist: " + fieldName);
return null;
}
}
/**
Select for edit
*/
public static ImportedBankStatementsData[] selectEdit(ConnectionProvider connectionProvider, String dateTimeFormat, String paramLanguage, String finFinancialAccountId, String key, String adUserClient, String adOrgClient) throws ServletException {
return selectEdit(connectionProvider, dateTimeFormat, paramLanguage, finFinancialAccountId, key, adUserClient, adOrgClient, 0, 0);
}
/**
Select for edit
*/
public static ImportedBankStatementsData[] selectEdit(ConnectionProvider connectionProvider, String dateTimeFormat, String paramLanguage, String finFinancialAccountId, String key, String adUserClient, String adOrgClient, int firstRegister, int numberRegisters) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT to_char(FIN_BankStatement.Created, ?) as created, " +
" (SELECT NAME FROM AD_USER u WHERE AD_USER_ID = FIN_BankStatement.CreatedBy) as CreatedByR, " +
" to_char(FIN_BankStatement.Updated, ?) as updated, " +
" to_char(FIN_BankStatement.Updated, 'YYYYMMDDHH24MISS') as Updated_Time_Stamp, " +
" FIN_BankStatement.UpdatedBy, " +
" (SELECT NAME FROM AD_USER u WHERE AD_USER_ID = FIN_BankStatement.UpdatedBy) as UpdatedByR," +
" FIN_BankStatement.DocumentNo, " +
"FIN_BankStatement.C_Doctype_ID, " +
"(CASE WHEN FIN_BankStatement.C_Doctype_ID IS NULL THEN '' ELSE (COALESCE(TO_CHAR(TO_CHAR(COALESCE(TO_CHAR((CASE WHEN tableTRL1.Name IS NULL THEN TO_CHAR(table1.Name) ELSE TO_CHAR(tableTRL1.Name) END)), ''))),'') ) END) AS C_Doctype_IDR, " +
"FIN_BankStatement.Name, " +
"COALESCE(FIN_BankStatement.Isactive, 'N') AS Isactive, " +
"FIN_BankStatement.Importdate, " +
"FIN_BankStatement.Statementdate, " +
"FIN_BankStatement.Filename, " +
"FIN_BankStatement.FIN_Reconciliation_ID, " +
"FIN_BankStatement.Notes, " +
"FIN_BankStatement.Posted, " +
"list1.name as Posted_BTN, " +
"FIN_BankStatement.EM_APRM_Process_BS_Force, " +
"list2.name as EM_APRM_Process_BS_Force_BTN, " +
"FIN_BankStatement.EM_APRM_Process_BS, " +
"list3.name as EM_APRM_Process_BS_BTN, " +
"FIN_BankStatement.AD_Org_ID, " +
"COALESCE(FIN_BankStatement.Processing, 'N') AS Processing, " +
"COALESCE(FIN_BankStatement.Processed, 'N') AS Processed, " +
"FIN_BankStatement.FIN_Bankstatement_ID, " +
"FIN_BankStatement.AD_Client_ID, " +
"FIN_BankStatement.FIN_Financial_Account_ID, " +
" ? AS LANGUAGE " +
" FROM FIN_BankStatement left join (select C_Doctype_ID, Name from C_Doctype) table1 on (FIN_BankStatement.C_Doctype_ID = table1.C_Doctype_ID) left join (select C_DocType_ID,AD_Language, Name from C_DocType_TRL) tableTRL1 on (table1.C_DocType_ID = tableTRL1.C_DocType_ID and tableTRL1.AD_Language = ?) left join ad_ref_list_v list1 on (list1.ad_reference_id = '234' and list1.ad_language = ? AND FIN_BankStatement.Posted = TO_CHAR(list1.value)) left join ad_ref_list_v list2 on (list2.ad_reference_id = 'EC75B6F5A9504DB6B3F3356EA85F15EE' and list2.ad_language = ? AND FIN_BankStatement.EM_APRM_Process_BS_Force = TO_CHAR(list2.value)) left join ad_ref_list_v list3 on (list3.ad_reference_id = 'EC75B6F5A9504DB6B3F3356EA85F15EE' and list3.ad_language = ? AND FIN_BankStatement.EM_APRM_Process_BS = TO_CHAR(list3.value))" +
" WHERE 2=2 " +
" AND 1=1 ";
strSql = strSql + ((finFinancialAccountId==null || finFinancialAccountId.equals(""))?"":" AND FIN_BankStatement.FIN_Financial_Account_ID = ? ");
strSql = strSql +
" AND FIN_BankStatement.FIN_Bankstatement_ID = ? " +
" AND FIN_BankStatement.AD_Client_ID IN (";
strSql = strSql + ((adUserClient==null || adUserClient.equals(""))?"":adUserClient);
strSql = strSql +
") " +
" AND FIN_BankStatement.AD_Org_ID IN (";
strSql = strSql + ((adOrgClient==null || adOrgClient.equals(""))?"":adOrgClient);
strSql = strSql +
") ";
ResultSet result;
Vector<java.lang.Object> vector = new Vector<java.lang.Object>(0);
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, dateTimeFormat);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, dateTimeFormat);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, paramLanguage);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, paramLanguage);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, paramLanguage);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, paramLanguage);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, paramLanguage);
if (finFinancialAccountId != null && !(finFinancialAccountId.equals(""))) {
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finFinancialAccountId);
}
iParameter++; UtilSql.setValue(st, iParameter, 12, null, key);
if (adUserClient != null && !(adUserClient.equals(""))) {
}
if (adOrgClient != null && !(adOrgClient.equals(""))) {
}
result = st.executeQuery();
long countRecord = 0;
long countRecordSkip = 1;
boolean continueResult = true;
while(countRecordSkip < firstRegister && continueResult) {
continueResult = result.next();
countRecordSkip++;
}
while(continueResult && result.next()) {
countRecord++;
ImportedBankStatementsData objectImportedBankStatementsData = new ImportedBankStatementsData();
objectImportedBankStatementsData.created = UtilSql.getValue(result, "CREATED");
objectImportedBankStatementsData.createdbyr = UtilSql.getValue(result, "CREATEDBYR");
objectImportedBankStatementsData.updated = UtilSql.getValue(result, "UPDATED");
objectImportedBankStatementsData.updatedTimeStamp = UtilSql.getValue(result, "UPDATED_TIME_STAMP");
objectImportedBankStatementsData.updatedby = UtilSql.getValue(result, "UPDATEDBY");
objectImportedBankStatementsData.updatedbyr = UtilSql.getValue(result, "UPDATEDBYR");
objectImportedBankStatementsData.documentno = UtilSql.getValue(result, "DOCUMENTNO");
objectImportedBankStatementsData.cDoctypeId = UtilSql.getValue(result, "C_DOCTYPE_ID");
objectImportedBankStatementsData.cDoctypeIdr = UtilSql.getValue(result, "C_DOCTYPE_IDR");
objectImportedBankStatementsData.name = UtilSql.getValue(result, "NAME");
objectImportedBankStatementsData.isactive = UtilSql.getValue(result, "ISACTIVE");
objectImportedBankStatementsData.importdate = UtilSql.getDateValue(result, "IMPORTDATE", "dd-MM-yyyy");
objectImportedBankStatementsData.statementdate = UtilSql.getDateValue(result, "STATEMENTDATE", "dd-MM-yyyy");
objectImportedBankStatementsData.filename = UtilSql.getValue(result, "FILENAME");
objectImportedBankStatementsData.finReconciliationId = UtilSql.getValue(result, "FIN_RECONCILIATION_ID");
objectImportedBankStatementsData.notes = UtilSql.getValue(result, "NOTES");
objectImportedBankStatementsData.posted = UtilSql.getValue(result, "POSTED");
objectImportedBankStatementsData.postedBtn = UtilSql.getValue(result, "POSTED_BTN");
objectImportedBankStatementsData.emAprmProcessBsForce = UtilSql.getValue(result, "EM_APRM_PROCESS_BS_FORCE");
objectImportedBankStatementsData.emAprmProcessBsForceBtn = UtilSql.getValue(result, "EM_APRM_PROCESS_BS_FORCE_BTN");
objectImportedBankStatementsData.emAprmProcessBs = UtilSql.getValue(result, "EM_APRM_PROCESS_BS");
objectImportedBankStatementsData.emAprmProcessBsBtn = UtilSql.getValue(result, "EM_APRM_PROCESS_BS_BTN");
objectImportedBankStatementsData.adOrgId = UtilSql.getValue(result, "AD_ORG_ID");
objectImportedBankStatementsData.processing = UtilSql.getValue(result, "PROCESSING");
objectImportedBankStatementsData.processed = UtilSql.getValue(result, "PROCESSED");
objectImportedBankStatementsData.finBankstatementId = UtilSql.getValue(result, "FIN_BANKSTATEMENT_ID");
objectImportedBankStatementsData.adClientId = UtilSql.getValue(result, "AD_CLIENT_ID");
objectImportedBankStatementsData.finFinancialAccountId = UtilSql.getValue(result, "FIN_FINANCIAL_ACCOUNT_ID");
objectImportedBankStatementsData.language = UtilSql.getValue(result, "LANGUAGE");
objectImportedBankStatementsData.adUserClient = "";
objectImportedBankStatementsData.adOrgClient = "";
objectImportedBankStatementsData.createdby = "";
objectImportedBankStatementsData.trBgcolor = "";
objectImportedBankStatementsData.totalCount = "";
objectImportedBankStatementsData.InitRecordNumber = Integer.toString(firstRegister);
vector.addElement(objectImportedBankStatementsData);
if (countRecord >= numberRegisters && numberRegisters != 0) {
continueResult = false;
}
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
ImportedBankStatementsData objectImportedBankStatementsData[] = new ImportedBankStatementsData[vector.size()];
vector.copyInto(objectImportedBankStatementsData);
return(objectImportedBankStatementsData);
}
/**
Create a registry
*/
public static ImportedBankStatementsData[] set(String finFinancialAccountId, String posted, String postedBtn, String emAprmProcessBsForce, String emAprmProcessBsForceBtn, String finBankstatementId, String adClientId, String adOrgId, String createdby, String createdbyr, String updatedby, String updatedbyr, String isactive, String documentno, String name, String notes, String cDoctypeId, String filename, String importdate, String statementdate, String finReconciliationId, String processing, String processed, String emAprmProcessBs, String emAprmProcessBsBtn) throws ServletException {
ImportedBankStatementsData objectImportedBankStatementsData[] = new ImportedBankStatementsData[1];
objectImportedBankStatementsData[0] = new ImportedBankStatementsData();
objectImportedBankStatementsData[0].created = "";
objectImportedBankStatementsData[0].createdbyr = createdbyr;
objectImportedBankStatementsData[0].updated = "";
objectImportedBankStatementsData[0].updatedTimeStamp = "";
objectImportedBankStatementsData[0].updatedby = updatedby;
objectImportedBankStatementsData[0].updatedbyr = updatedbyr;
objectImportedBankStatementsData[0].documentno = documentno;
objectImportedBankStatementsData[0].cDoctypeId = cDoctypeId;
objectImportedBankStatementsData[0].cDoctypeIdr = "";
objectImportedBankStatementsData[0].name = name;
objectImportedBankStatementsData[0].isactive = isactive;
objectImportedBankStatementsData[0].importdate = importdate;
objectImportedBankStatementsData[0].statementdate = statementdate;
objectImportedBankStatementsData[0].filename = filename;
objectImportedBankStatementsData[0].finReconciliationId = finReconciliationId;
objectImportedBankStatementsData[0].notes = notes;
objectImportedBankStatementsData[0].posted = posted;
objectImportedBankStatementsData[0].postedBtn = postedBtn;
objectImportedBankStatementsData[0].emAprmProcessBsForce = emAprmProcessBsForce;
objectImportedBankStatementsData[0].emAprmProcessBsForceBtn = emAprmProcessBsForceBtn;
objectImportedBankStatementsData[0].emAprmProcessBs = emAprmProcessBs;
objectImportedBankStatementsData[0].emAprmProcessBsBtn = emAprmProcessBsBtn;
objectImportedBankStatementsData[0].adOrgId = adOrgId;
objectImportedBankStatementsData[0].processing = processing;
objectImportedBankStatementsData[0].processed = processed;
objectImportedBankStatementsData[0].finBankstatementId = finBankstatementId;
objectImportedBankStatementsData[0].adClientId = adClientId;
objectImportedBankStatementsData[0].finFinancialAccountId = finFinancialAccountId;
objectImportedBankStatementsData[0].language = "";
return objectImportedBankStatementsData;
}
/**
Select for auxiliar field
*/
public static String selectAuxB1C25B989C164EDFB7F9B26CB799DDAA(ConnectionProvider connectionProvider, String FIN_BankStatement_ID, String FIN_Financial_Account_ID) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT 1 FROM DUAL WHERE EXISTS (SELECT 1 FROM FIN_BANKSTATEMENTLINE WHERE FIN_FINACC_TRANSACTION_ID IS NOT NULL AND FIN_BANKSTATEMENT_ID = ?) OR EXISTS (SELECT 1 FROM FIN_BANKSTATEMENTLINE, FIN_BANKSTATEMENT WHERE DATETRX > (SELECT MAX(DATETRX) FROM FIN_BANKSTATEMENTLINE WHERE FIN_BANKSTATEMENT_ID = ?) AND FIN_BANKSTATEMENT.FIN_BANKSTATEMENT_ID = FIN_BANKSTATEMENTLINE.FIN_BANKSTATEMENT_ID AND FIN_BANKSTATEMENT.FIN_FINANCIAL_ACCOUNT_ID = ?) ";
ResultSet result;
String strReturn = "";
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, FIN_BankStatement_ID);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, FIN_BankStatement_ID);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, FIN_Financial_Account_ID);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "1");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
/**
Select for auxiliar field
*/
public static String selectDef8189F49FFEA56E56E040007F01003E83_0(ConnectionProvider connectionProvider, String CreatedbyR) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT ( COALESCE(TO_CHAR(TO_CHAR(COALESCE(TO_CHAR(table2.Name), ''))), '') ) as Createdby FROM AD_User left join (select AD_User_ID, Name from AD_User) table2 on (AD_User.AD_User_ID = table2.AD_User_ID) WHERE AD_User.isActive='Y' AND AD_User.AD_User_ID = ? ";
ResultSet result;
String strReturn = "";
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, CreatedbyR);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "CREATEDBY");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
/**
Select for auxiliar field
*/
public static String selectDef8189F49FFEA76E56E040007F01003E83_1(ConnectionProvider connectionProvider, String UpdatedbyR) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT ( COALESCE(TO_CHAR(TO_CHAR(COALESCE(TO_CHAR(table2.Name), ''))), '') ) as Updatedby FROM AD_User left join (select AD_User_ID, Name from AD_User) table2 on (AD_User.AD_User_ID = table2.AD_User_ID) WHERE AD_User.isActive='Y' AND AD_User.AD_User_ID = ? ";
ResultSet result;
String strReturn = "";
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, UpdatedbyR);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "UPDATEDBY");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
/**
return the parent ID
*/
public static String selectParentID(ConnectionProvider connectionProvider, String key) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT FIN_BankStatement.FIN_Financial_Account_ID AS NAME" +
" FROM FIN_BankStatement" +
" WHERE FIN_BankStatement.FIN_Bankstatement_ID = ?";
ResultSet result;
String strReturn = "";
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, key);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "NAME");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
/**
Select for parent field
*/
public static String selectParent(ConnectionProvider connectionProvider, String finFinancialAccountId) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT (TO_CHAR(COALESCE(TO_CHAR(table1.Name), '')) || ' - ' || TO_CHAR(COALESCE(TO_CHAR(table2.ISO_Code), '')) || ' - ' || TO_CHAR(COALESCE(TO_CHAR(table1.EM_Gac_Noperkiraan), ''))) AS NAME FROM FIN_Financial_Account left join (select FIN_Financial_Account_ID, Name, C_Currency_ID, EM_Gac_Noperkiraan from FIN_Financial_Account) table1 on (FIN_Financial_Account.FIN_Financial_Account_ID = table1.FIN_Financial_Account_ID) left join (select C_Currency_ID, ISO_Code from C_Currency) table2 on (table1.C_Currency_ID = table2.C_Currency_ID) WHERE FIN_Financial_Account.FIN_Financial_Account_ID = ? ";
ResultSet result;
String strReturn = "";
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finFinancialAccountId);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "NAME");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
/**
Select for parent field
*/
public static String selectParentTrl(ConnectionProvider connectionProvider, String finFinancialAccountId) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT (TO_CHAR(COALESCE(TO_CHAR(table1.Name), '')) || ' - ' || TO_CHAR(COALESCE(TO_CHAR(table2.ISO_Code), '')) || ' - ' || TO_CHAR(COALESCE(TO_CHAR(table1.EM_Gac_Noperkiraan), ''))) AS NAME FROM FIN_Financial_Account left join (select FIN_Financial_Account_ID, Name, C_Currency_ID, EM_Gac_Noperkiraan from FIN_Financial_Account) table1 on (FIN_Financial_Account.FIN_Financial_Account_ID = table1.FIN_Financial_Account_ID) left join (select C_Currency_ID, ISO_Code from C_Currency) table2 on (table1.C_Currency_ID = table2.C_Currency_ID) WHERE FIN_Financial_Account.FIN_Financial_Account_ID = ? ";
ResultSet result;
String strReturn = "";
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finFinancialAccountId);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "NAME");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
public int update(Connection conn, ConnectionProvider connectionProvider) throws ServletException {
String strSql = "";
strSql = strSql +
" UPDATE FIN_BankStatement" +
" SET DocumentNo = (?) , C_Doctype_ID = (?) , Name = (?) , Isactive = (?) , Importdate = TO_DATE(?) , Statementdate = TO_DATE(?) , Filename = (?) , FIN_Reconciliation_ID = (?) , Notes = (?) , Posted = (?) , EM_APRM_Process_BS_Force = (?) , EM_APRM_Process_BS = (?) , AD_Org_ID = (?) , Processing = (?) , Processed = (?) , FIN_Bankstatement_ID = (?) , AD_Client_ID = (?) , FIN_Financial_Account_ID = (?) , updated = now(), updatedby = ? " +
" WHERE FIN_BankStatement.FIN_Bankstatement_ID = ? " +
" AND FIN_BankStatement.FIN_Financial_Account_ID = ? " +
" AND FIN_BankStatement.AD_Client_ID IN (";
strSql = strSql + ((adUserClient==null || adUserClient.equals(""))?"":adUserClient);
strSql = strSql +
") " +
" AND FIN_BankStatement.AD_Org_ID IN (";
strSql = strSql + ((adOrgClient==null || adOrgClient.equals(""))?"":adOrgClient);
strSql = strSql +
") ";
int updateCount = 0;
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(conn, strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, documentno);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, cDoctypeId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, name);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, isactive);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, importdate);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, statementdate);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, filename);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finReconciliationId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, notes);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, posted);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, emAprmProcessBsForce);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, emAprmProcessBs);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, adOrgId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, processing);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, processed);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finBankstatementId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, adClientId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finFinancialAccountId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, updatedby);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finBankstatementId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finFinancialAccountId);
if (adUserClient != null && !(adUserClient.equals(""))) {
}
if (adOrgClient != null && !(adOrgClient.equals(""))) {
}
updateCount = st.executeUpdate();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releaseTransactionalPreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(updateCount);
}
public int insert(Connection conn, ConnectionProvider connectionProvider) throws ServletException {
String strSql = "";
strSql = strSql +
" INSERT INTO FIN_BankStatement " +
" (DocumentNo, C_Doctype_ID, Name, Isactive, Importdate, Statementdate, Filename, FIN_Reconciliation_ID, Notes, Posted, EM_APRM_Process_BS_Force, EM_APRM_Process_BS, AD_Org_ID, Processing, Processed, FIN_Bankstatement_ID, AD_Client_ID, FIN_Financial_Account_ID, created, createdby, updated, updatedBy)" +
" VALUES ((?), (?), (?), (?), TO_DATE(?), TO_DATE(?), (?), (?), (?), (?), (?), (?), (?), (?), (?), (?), (?), (?), now(), ?, now(), ?)";
int updateCount = 0;
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(conn, strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, documentno);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, cDoctypeId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, name);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, isactive);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, importdate);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, statementdate);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, filename);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finReconciliationId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, notes);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, posted);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, emAprmProcessBsForce);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, emAprmProcessBs);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, adOrgId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, processing);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, processed);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finBankstatementId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, adClientId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finFinancialAccountId);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, createdby);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, updatedby);
updateCount = st.executeUpdate();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releaseTransactionalPreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(updateCount);
}
public static int delete(ConnectionProvider connectionProvider, String param1, String finFinancialAccountId, String adUserClient, String adOrgClient) throws ServletException {
String strSql = "";
strSql = strSql +
" DELETE FROM FIN_BankStatement" +
" WHERE FIN_BankStatement.FIN_Bankstatement_ID = ? " +
" AND FIN_BankStatement.FIN_Financial_Account_ID = ? " +
" AND FIN_BankStatement.AD_Client_ID IN (";
strSql = strSql + ((adUserClient==null || adUserClient.equals(""))?"":adUserClient);
strSql = strSql +
") " +
" AND FIN_BankStatement.AD_Org_ID IN (";
strSql = strSql + ((adOrgClient==null || adOrgClient.equals(""))?"":adOrgClient);
strSql = strSql +
") ";
int updateCount = 0;
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, param1);
iParameter++; UtilSql.setValue(st, iParameter, 12, null, finFinancialAccountId);
if (adUserClient != null && !(adUserClient.equals(""))) {
}
if (adOrgClient != null && !(adOrgClient.equals(""))) {
}
updateCount = st.executeUpdate();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(updateCount);
}
/**
Select for relation
*/
public static String selectOrg(ConnectionProvider connectionProvider, String id) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT AD_ORG_ID" +
" FROM FIN_BankStatement" +
" WHERE FIN_BankStatement.FIN_Bankstatement_ID = ? ";
ResultSet result;
String strReturn = null;
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, id);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "AD_ORG_ID");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
public static String getCurrentDBTimestamp(ConnectionProvider connectionProvider, String id) throws ServletException {
String strSql = "";
strSql = strSql +
" SELECT to_char(Updated, 'YYYYMMDDHH24MISS') as Updated_Time_Stamp" +
" FROM FIN_BankStatement" +
" WHERE FIN_BankStatement.FIN_Bankstatement_ID = ? ";
ResultSet result;
String strReturn = null;
PreparedStatement st = null;
int iParameter = 0;
try {
st = connectionProvider.getPreparedStatement(strSql);
QueryTimeOutUtil.getInstance().setQueryTimeOut(st, SessionInfo.getQueryProfile());
iParameter++; UtilSql.setValue(st, iParameter, 12, null, id);
result = st.executeQuery();
if(result.next()) {
strReturn = UtilSql.getValue(result, "UPDATED_TIME_STAMP");
}
result.close();
} catch(SQLException e){
log4j.error("SQL error in query: " + strSql + "Exception:"+ e);
throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
} catch(Exception ex){
log4j.error("Exception in query: " + strSql + "Exception:"+ ex);
throw new ServletException("@CODE=@" + ex.getMessage());
} finally {
try {
connectionProvider.releasePreparedStatement(st);
} catch(Exception ignore){
ignore.printStackTrace();
}
}
return(strReturn);
}
}
| [
"msodikinn@bitbucket.org"
] | msodikinn@bitbucket.org |
e876f82e16c5439e1d66efc7b3d5a92cd321c544 | 4dad57732b162bb3015234d4e65639e378c26a1e | /src/gestor/GestorBD.java | 0a57e6545e0d70deaeab8130c355eaea30baa7b0 | [] | no_license | PontVergesJuanPedro/EjLab | 698075e048d808358984fca3332da7240fa9883f | 06c10dcffd3e4bc455e61f85f7eb05923178db0d | refs/heads/master | 2022-12-12T00:12:44.042396 | 2020-09-04T00:54:27 | 2020-09-04T00:54:27 | 292,708,986 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,635 | java | package gestor;
import java.util.ArrayList;
import model.Articulo;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Rubro;
public class GestorBD {
private String CONN = "jdbc:sqlserver://JUANPEDRO;databaseName=javaABM";
private String USER = "sa";
private String PASS = "1234";
public ArrayList<Articulo> obtenerArticulos() {
ArrayList<Articulo> lista = new ArrayList<>();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(CONN,USER,PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select a.*, r.nombre as nombreRubro from articulos a join rubros r on a.id_rubro = r.id_rubro");
while(rs.next()) {
int id = rs.getInt("codigo");
String descripcion = rs.getString("descripcion");
float precio = rs.getFloat("precio");
int id_rubro = rs.getInt("id_rubro");
String nombreRubro = rs.getString("nombreRubro");
Rubro r = new Rubro(id_rubro, nombreRubro);
Articulo a = new Articulo(id,descripcion,precio,r);
lista.add(a);
}
stmt.close();
conn.close();
rs.close();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
public void agregarArticulo(Articulo a) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(CONN,USER,PASS);
PreparedStatement pstmt = conn.prepareStatement("insert into articulos values (?,?,?)");
pstmt.setString(1,a.getDescripcion());
pstmt.setFloat(2, a.getPrecio());
pstmt.setInt(3, a.getRubro().getId());
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void eliminarArticulo(int codigo){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(CONN,USER,PASS);
PreparedStatement pstmt = conn.prepareStatement("delete from articulos where codigo = ?");
pstmt.setInt(1,codigo);
pstmt.executeUpdate();
conn.close();
pstmt.close();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void modificarArticulo(Articulo a) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(CONN,USER,PASS);
PreparedStatement pstmt = conn.prepareStatement("update articulos set descripcion = ?, precio = ? where codigo = ?");
pstmt.setString(1,a.getDescripcion());
pstmt.setFloat(2,a.getPrecio());
pstmt.setInt(3,a.getCodigo());
pstmt.executeUpdate();
conn.close();
pstmt.close();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<Rubro> obtenerRubros() {
ArrayList<Rubro> lista = new ArrayList<>();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(CONN,USER,PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from rubros");
while(rs.next()) {
int id = rs.getInt(1);
String nombre = rs.getString(2);
Rubro r = new Rubro(id,nombre);
lista.add(r);
}
conn.close();
stmt.close();
rs.close();
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
}
| [
"110959@tecnicatura.frc.utn.edu.ar"
] | 110959@tecnicatura.frc.utn.edu.ar |
d7158f0607329ec7c75e440210f0424d8ff86b1b | ce02b467cf6d0eeeec8994f28e9b3d8be0ff4e30 | /src/com/subhash/javabasics/collections/JavaLinkedList.java | e21cd47823bc7a672612aec8fe56af041b3adc70 | [] | no_license | subhashrsrivatsa/Java-Basics | 5ff73bccbe4f296c311e3d617ffc703e964f61a4 | abbba370ef53d0b0a9dea2dfd71ad5e5772aec85 | refs/heads/master | 2023-03-15T01:18:08.268374 | 2021-03-08T20:04:16 | 2021-03-08T20:04:16 | 312,100,922 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 992 | java | /**
*
*/
package com.subhash.javabasics.collections;
import java.util.Iterator;
import java.util.LinkedList;
/**
* @author Subhash SRIVATSA
*
*/
public class JavaLinkedList {
/**
* @param args
*/
public static void main(String[] args) {
LinkedList<Integer> li = new LinkedList<>();
for(int i = 10; i>0;i--) {
li.add(i);
}
displayNumbers(li);
li.addFirst(11);
li.addLast(0);
System.out.println("\nLinked List after adding new elements");
displayNumbers(li);
System.out.println("\nLinked List after puahing an element");
li.push(12);
displayNumbers(li);
System.out.println("\nLinked List after popping an element");
li.pop();
displayNumbers(li);
System.out.println("\nThe First element is : "+li.getFirst());
System.out.println("The last element is : "+li.getLast());
}
private static void displayNumbers(LinkedList<Integer> li) {
Iterator<Integer> it = li.iterator();
while(it.hasNext()) {
System.out.print(" "+it.next());
}
}
}
| [
"Subhash SRIVATSA@SubhashSRIVATSA.home"
] | Subhash SRIVATSA@SubhashSRIVATSA.home |
d56229ad95db3fe1a299eb8596a9475992d71b77 | 17c0193d54e97a1e0cdfcaaec883953b31a189df | /src/main/java/com/example/hrms/business/abstracts/CvSchoolService.java | 520a104660363627f5f057a06f8923c2a9aaf0de | [] | no_license | kubils/Java-ReactCamp-HRMS | 66728a0b71c2de51275542077006f32e0f11d9e9 | 3d8021088a25378fcdccb6aeb790c65f75e22d2d | refs/heads/master | 2023-05-24T07:01:55.783189 | 2021-06-16T19:47:54 | 2021-06-16T19:47:54 | 369,224,630 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 388 | java | package com.example.hrms.business.abstracts;
import com.example.hrms.core.concretes.utilities.DataResult;
import com.example.hrms.core.concretes.utilities.Result;
import com.example.hrms.entities.concretes.CV.CvSchools;
import java.util.List;
public interface CvSchoolService {
Result add(CvSchools cvSchool);
DataResult<List<CvSchools>> getByDateOfFinish(int candidateId);
}
| [
"kubils19@gmail.com"
] | kubils19@gmail.com |
dbdcdb45b79d8d5658854182d93ef2e2c5903680 | 3e8dbd1b3ea30971ac350cdb8ac382ae21f405ea | /jvm/jdbc/src/main/java/org/ballistacompute/jdbc/ResultSetHelper.java | f796c8a81ed840e18804a253d0dd83c526571db3 | [
"Apache-2.0"
] | permissive | houqp/ballista | 537abbc8994587178993813ad1f0d008fd0385c1 | 7011dec497090403ae861b6ce78ec48349755090 | refs/heads/master | 2022-11-12T09:20:08.498428 | 2020-05-15T06:28:10 | 2020-05-15T06:28:10 | 262,223,654 | 0 | 0 | Apache-2.0 | 2020-05-08T04:05:48 | 2020-05-08T04:05:48 | null | UTF-8 | Java | false | false | 4,491 | java | package org.ballistacompute.jdbc;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Time;
import java.sql.Timestamp;
/**
* Helper methods for converting between data types.
*/
public class ResultSetHelper {
/** Convert value to String. */
public static String getString(final Object value) throws SQLException {
return value == null ? null : String.valueOf(value);
}
/** Convert value to boolean. */
public static boolean getBoolean(final Object value) throws SQLException {
if (value == null) {
return false;
} else if (value instanceof Boolean) {
return (Boolean) value;
} else if (value instanceof String) {
return ((String) value).equalsIgnoreCase("true");
} else {
throw unsupportedConversion("boolean", value);
}
}
/** Convert value to byte. */
public static byte getByte(final Object value) throws SQLException {
if (value == null) {
return 0;
} else if (value instanceof Number) {
return ((Number) value).byteValue();
} else if (value instanceof String) {
return Byte.parseByte((String) value);
} else {
throw unsupportedConversion("byte", value);
}
}
/** Convert value to short. */
public static short getShort(final Object value) throws SQLException {
if (value == null) {
return 0;
} else if (value instanceof Number) {
return ((Number) value).shortValue();
} else if (value instanceof String) {
return Short.parseShort((String) value);
} else {
throw unsupportedConversion("short", value);
}
}
/** Convert value to int. */
public static int getInt(final Object value) throws SQLException {
if (value == null) {
return 0;
} else if (value instanceof Number) {
return ((Number) value).intValue();
} else if (value instanceof String) {
return Integer.parseInt((String) value);
} else {
throw unsupportedConversion("int", value);
}
}
/** Convert value to String. */
public static long getLong(final Object value) throws SQLException {
if (value == null) {
return 0;
} else if (value instanceof Number) {
return ((Number) value).longValue();
} else if (value instanceof String) {
return Long.parseLong((String) value);
} else {
throw unsupportedConversion("long", value);
}
}
/** Convert value to float. */
public static float getFloat(final Object value) throws SQLException {
if (value == null) {
return 0;
} else if (value instanceof Number) {
return ((Number) value).floatValue();
} else if (value instanceof String) {
return Float.parseFloat((String) value);
} else {
throw unsupportedConversion("float", value);
}
}
/** Convert value to double. */
public static double getDouble(final Object value) throws SQLException {
if (value == null) {
return 0;
} else if (value instanceof Number) {
return ((Number) value).doubleValue();
} else if (value instanceof String) {
return Double.parseDouble((String) value);
} else {
throw unsupportedConversion("double", value);
}
}
/** Convert value to BigDecimal. */
public static BigDecimal getBigDecimal(final Object value) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
/** Convert value to byte[]. */
public static byte[] getBytes(final Object value) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
/** Convert value to Date. */
public static Date getDate(final Object value) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
/** Convert value to Time. */
public static Time getTime(final Object value) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
/** Convert value to Timestamp. */
public static Timestamp getTimestamp(final Object value) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
/** Convenience method for building an exception for unsupported conversions. */
private static SQLException unsupportedConversion(String t, Object value) {
if (value == null) {
return new SQLException(String.format("Cannot convert null value to type %s", t));
} else {
return new SQLException(String.format("Cannot convert %s value '%s' to type %s", value.getClass(), value, t));
}
}
}
| [
"andygrove73@gmail.com"
] | andygrove73@gmail.com |
a85d2ab70c3f96415b61b0c746d26072693bbd4e | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/processing--processing/b94acc4b695eb8079e263f2ca21a8aab36811e0e/after/ASTGenerator.java | 4b3dda7f7b5b2dd841d275fb21d4cdfff3442636 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 142,483 | java | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-15 The Processing Foundation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package processing.mode.java.pdex;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.PlainDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ArrayAccess;
import org.eclipse.jdt.core.dom.ArrayType;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.Comment;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.NodeFinder;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationExpression;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
import processing.app.Base;
import processing.app.Library;
import processing.app.SketchCode;
import processing.app.Toolkit;
import processing.app.syntax.JEditTextArea;
import processing.mode.java.JavaEditor;
import processing.mode.java.JavaMode;
import processing.mode.java.preproc.PdePreprocessor;
import com.google.classpath.ClassPath;
import com.google.classpath.ClassPathFactory;
import com.google.classpath.RegExpResourceFilter;
@SuppressWarnings({ "deprecation", "unchecked" })
public class ASTGenerator {
protected ErrorCheckerService errorCheckerService;
protected JavaEditor editor;
public DefaultMutableTreeNode codeTree = new DefaultMutableTreeNode();
protected DefaultMutableTreeNode currentParent = null;
/**
* AST Window
*/
protected JFrame frmASTView;
protected JFrame frameAutoComp;
/**
* Swing component wrapper for AST, used for internal testing
*/
protected JTree jtree;
/**
* JTree used for testing refactoring operations
*/
protected JTree treeRename;
protected CompilationUnit compilationUnit;
protected JTable tableAuto;
protected JEditorPane javadocPane;
protected JScrollPane scrollPane;
protected JFrame frmRename;
protected JButton btnRename;
protected JButton btnListOccurrence;
protected JTextField txtRenameField;
protected JFrame frmOccurenceList;
protected JLabel lblRefactorOldName;
public ASTGenerator(ErrorCheckerService ecs) {
this.errorCheckerService = ecs;
this.editor = ecs.getEditor();
setupGUI();
//addCompletionPopupListner();
addListeners();
//loadJavaDoc();
predictionOngoing = new AtomicBoolean(false);
}
protected void setupGUI(){
frmASTView = new JFrame();
jtree = new JTree();
frmASTView.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmASTView.setBounds(new Rectangle(680, 100, 460, 620));
frmASTView.setTitle("AST View - " + editor.getSketch().getName());
JScrollPane sp = new JScrollPane();
sp.setViewportView(jtree);
frmASTView.add(sp);
btnRename = new JButton("Rename");
btnListOccurrence = new JButton("Show Usage");
frmRename = new JFrame();
frmRename.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmRename.setSize(250, 130);
frmRename.setLayout(new BoxLayout(frmRename.getContentPane(), BoxLayout.Y_AXIS));
Toolkit.setIcon(frmRename);
JPanel panelTop = new JPanel(), panelBottom = new JPanel();
panelTop.setLayout(new BoxLayout(panelTop, BoxLayout.Y_AXIS));
panelTop.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelBottom.setLayout(new BoxLayout(panelBottom, BoxLayout.X_AXIS));
panelBottom.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelBottom.add(Box.createHorizontalGlue());
panelBottom.add(btnListOccurrence);
panelBottom.add(Box.createRigidArea(new Dimension(15, 0)));
panelBottom.add(btnRename);
frmRename.setTitle("Enter new name:");
txtRenameField = new JTextField();
txtRenameField.setPreferredSize(new Dimension(150, 60));
panelTop.add(txtRenameField);
//renameWindow.setVisible(true);
lblRefactorOldName = new JLabel();
lblRefactorOldName.setText("Old Name: ");
panelTop.add(Box.createRigidArea(new Dimension(0, 10)));
panelTop.add(lblRefactorOldName);
frmRename.add(panelTop);
frmRename.add(panelBottom);
frmRename.setMinimumSize(frmRename.getSize());
frmRename.setLocation(editor.getX()
+ (editor.getWidth() - frmRename.getWidth()) / 2,
editor.getY()
+ (editor.getHeight() - frmRename.getHeight())
/ 2);
frmOccurenceList = new JFrame();
frmOccurenceList.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmOccurenceList.setSize(300, 400);
Toolkit.setIcon(frmOccurenceList);
JScrollPane sp2 = new JScrollPane();
treeRename = new JTree();
sp2.setViewportView(treeRename);
frmOccurenceList.add(sp2);
//occurenceListFrame.setVisible(true);
// frameAutoComp = new JFrame();
// frameAutoComp.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// frameAutoComp.setBounds(new Rectangle(1280, 100, 460, 620));
// Toolkit.setIcon(frameAutoComp);
// tableAuto = new JTable();
// JScrollPane sp3 = new JScrollPane();
// sp3.setViewportView(tableAuto);
// frameAutoComp.add(sp3);
// frmJavaDoc = new JFrame();
// frmJavaDoc.setTitle("P5 InstaHelp");
// //jdocWindow.setUndecorated(true);
// frmJavaDoc.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
// javadocPane = new JEditorPane();
// javadocPane.setContentType("text/html");
// javadocPane.setText("<html> </html>");
// javadocPane.setEditable(false);
// scrollPane = new JScrollPane();
// scrollPane.setViewportView(javadocPane);
// frmJavaDoc.add(scrollPane);
//frmJavaDoc.setUndecorated(true);
}
/**
* Toggle AST View window
*/
public static final boolean SHOWAST = !true;
protected DefaultMutableTreeNode buildAST(String source, CompilationUnit cu) {
if (cu == null) {
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(source.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_6, options);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);
parser.setCompilerOptions(options);
compilationUnit = (CompilationUnit) parser.createAST(null);
} else {
compilationUnit = cu;
//log("Other cu");
}
// OutlineVisitor visitor = new OutlineVisitor();
// compilationUnit.accept(visitor);
getCodeComments();
codeTree = new DefaultMutableTreeNode(new ASTNodeWrapper((ASTNode) compilationUnit
.types().get(0)));
//log("Total CU " + compilationUnit.types().size());
if(compilationUnit.types() == null || compilationUnit.types().isEmpty()){
Base.loge("No CU found!");
}
visitRecur((ASTNode) compilationUnit.types().get(0), codeTree);
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
return null;
}
protected void done() {
if (codeTree != null) {
if(SHOWAST){
if (jtree.hasFocus() || frmASTView.hasFocus())
return;
jtree.setModel(new DefaultTreeModel(codeTree));
((DefaultTreeModel) jtree.getModel()).reload();
jtree.validate();
if (!frmASTView.isVisible()) {
frmASTView.setVisible(true);
}
}
// if (!frameAutoComp.isVisible()) {
//
// frameAutoComp.setVisible(true);
//
// }
// if (!frmJavaDoc.isVisible()) {
// long t = System.currentTimeMillis();
// loadJavaDoc();
// log("Time taken: "
// + (System.currentTimeMillis() - t));
// frmJavaDoc.setBounds(new Rectangle(errorCheckerService.getEditor()
// .getX() + errorCheckerService.getEditor().getWidth(),
// errorCheckerService.getEditor()
// .getY(), 450, 600));
// frmJavaDoc.setVisible(true);
// }
}
}
};
worker.execute();
// Base.loge("++>" + System.getProperty("java.class.path"));
// log(System.getProperty("java.class.path"));
// log("-------------------------------");
return codeTree;
}
protected ClassPathFactory factory;
/**
* Used for searching for package declaration of a class
*/
protected ClassPath classPath;
//protected JFrame frmJavaDoc;
/**
* Loads up .jar files and classes defined in it for completion lookup
*/
protected void loadJars() {
// SwingWorker worker = new SwingWorker() {
// protected void done(){
// }
// protected Object doInBackground() throws Exception {
// return null;
// }
// };
// worker.execute();
Thread t = new Thread(new Runnable() {
public void run() {
try {
factory = new ClassPathFactory();
StringBuilder tehPath = new StringBuilder(System
.getProperty("java.class.path"));
// Starting with JDK 1.7, no longer using Apple's Java, so
// rt.jar has the same path on all OSes
tehPath.append(File.pathSeparatorChar
+ System.getProperty("java.home") + File.separator + "lib"
+ File.separator + "rt.jar" + File.pathSeparatorChar);
if (errorCheckerService.classpathJars != null) {
synchronized (errorCheckerService.classpathJars) {
for (URL jarPath : errorCheckerService.classpathJars) {
//log(jarPath.getPath());
tehPath.append(jarPath.getPath() + File.pathSeparatorChar);
}
}
}
// String paths[] = tehPath.toString().split(File.separatorChar +"");
// StringTokenizer st = new StringTokenizer(tehPath.toString(),
// File.pathSeparatorChar + "");
// while (st.hasMoreElements()) {
// String sstr = (String) st.nextElement();
// log(sstr);
// }
classPath = factory.createFromPath(tehPath.toString());
log("Classpath created " + (classPath != null));
// for (String packageName : classPath.listPackages("")) {
// log(packageName);
// }
// RegExpResourceFilter regExpResourceFilter = new RegExpResourceFilter(
// ".*",
// "ArrayList.class");
// String[] resources = classPath.findResources("", regExpResourceFilter);
// for (String className : resources) {
// log("-> " + className);
// }
log("Sketch classpath jars loaded.");
if (Base.isMacOS()) {
File f = new File(System.getProperty("java.home") + File.separator + "bundle"
+ File.separator + "Classes" + File.separator + "classes.jar");
log(f.getAbsolutePath() + " | classes.jar found?"
+ f.exists());
} else {
File f = new File(System.getProperty("java.home") + File.separator
+ "lib" + File.separator + "rt.jar" + File.separator);
log(f.getAbsolutePath() + " | rt.jar found?"
+ f.exists());
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
protected TreeMap<String, String> jdocMap;
protected void loadJavaDoc() {
jdocMap = new TreeMap<String, String>();
// presently loading only p5 reference for PApplet
Thread t = new Thread(new Runnable() {
@Override
public void run() {
JavadocHelper.loadJavaDoc(jdocMap, editor.getMode().getReferenceFolder());
}
});
t.start();
}
public DefaultMutableTreeNode buildAST(CompilationUnit cu) {
return buildAST(errorCheckerService.sourceCode, cu);
}
public static CompletionCandidate[] checkForTypes(ASTNode node) {
List<VariableDeclarationFragment> vdfs = null;
switch (node.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
return new CompletionCandidate[] { new CompletionCandidate((TypeDeclaration) node) };
case ASTNode.METHOD_DECLARATION:
MethodDeclaration md = (MethodDeclaration) node;
log(getNodeAsString(md));
List<ASTNode> params = (List<ASTNode>) md
.getStructuralProperty(MethodDeclaration.PARAMETERS_PROPERTY);
CompletionCandidate[] cand = new CompletionCandidate[params.size() + 1];
cand[0] = new CompletionCandidate(md);
for (int i = 0; i < params.size(); i++) {
// cand[i + 1] = new CompletionCandidate(params.get(i).toString(), "", "",
// CompletionCandidate.LOCAL_VAR);
cand[i + 1] = new CompletionCandidate((SingleVariableDeclaration)params.get(i));
}
return cand;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
return new CompletionCandidate[] { new CompletionCandidate((SingleVariableDeclaration)node) };
case ASTNode.FIELD_DECLARATION:
vdfs = ((FieldDeclaration) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
vdfs = ((VariableDeclarationStatement) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
vdfs = ((VariableDeclarationExpression) node).fragments();
break;
default:
break;
}
if (vdfs != null) {
CompletionCandidate ret[] = new CompletionCandidate[vdfs.size()];
int i = 0;
for (VariableDeclarationFragment vdf : vdfs) {
// ret[i++] = new CompletionCandidate(getNodeAsString2(vdf), "", "",
// CompletionCandidate.LOCAL_VAR);
ret[i++] = new CompletionCandidate(vdf);
}
return ret;
}
return null;
}
/**
* Find the parent of the expression in a().b, this would give me the return
* type of a(), so that we can find all children of a() begininng with b
*
* @param nearestNode
* @param expression
* @return
*/
public static ASTNode resolveExpression(ASTNode nearestNode,
ASTNode expression, boolean noCompare) {
log("Resolving " + getNodeAsString(expression) + " noComp "
+ noCompare);
if (expression instanceof SimpleName) {
return findDeclaration2(((SimpleName) expression), nearestNode);
} else if (expression instanceof MethodInvocation) {
log("3. Method Invo "
+ ((MethodInvocation) expression).getName());
return findDeclaration2(((MethodInvocation) expression).getName(),
nearestNode);
} else if (expression instanceof FieldAccess) {
log("2. Field access "
+ getNodeAsString(((FieldAccess) expression).getExpression()) + "|||"
+ getNodeAsString(((FieldAccess) expression).getName()));
if (noCompare) {
/*
* ASTNode ret = findDeclaration2(((FieldAccess) expression).getName(),
* nearestNode); log("Found as ->"+getNodeAsString(ret));
* return ret;
*/
return findDeclaration2(((FieldAccess) expression).getName(),
nearestNode);
} else {
/*
* Note how for the next recursion, noCompare is reversed. Let's say
* I've typed getABC().quark.nin where nin is incomplete(ninja being the
* field), when execution first enters here, it calls resolveExpr again
* for "getABC().quark" where we know that quark field must be complete,
* so we toggle noCompare. And kaboom.
*/
return resolveExpression(nearestNode,
((FieldAccess) expression).getExpression(),
!noCompare);
}
//return findDeclaration2(((FieldAccess) expression).getExpression(), nearestNode);
} else if (expression instanceof QualifiedName) {
log("1. Resolving "
+ ((QualifiedName) expression).getQualifier() + " ||| "
+ ((QualifiedName) expression).getName());
if (noCompare) { // no compare, as in "abc.hello." need to resolve hello here
return findDeclaration2(((QualifiedName) expression).getName(),
nearestNode);
} else {
//User typed "abc.hello.by" (bye being complete), so need to resolve "abc.hello." only
return findDeclaration2(((QualifiedName) expression).getQualifier(),
nearestNode);
}
}
return null;
}
/**
* Finds the type of the expression in foo.bar().a().b, this would give me the
* type of b if it exists in return type of a(). If noCompare is true,
* it'll return type of a()
* @param nearestNode
* @param astNode
* @return
*/
public ClassMember resolveExpression3rdParty(ASTNode nearestNode,
ASTNode astNode, boolean noCompare) {
log("Resolve 3rdParty expr-- " + getNodeAsString(astNode)
+ " nearest node " + getNodeAsString(nearestNode));
if(astNode == null) return null;
ClassMember scopeParent = null;
SimpleType stp = null;
if(astNode instanceof SimpleName){
ASTNode decl = findDeclaration2(((SimpleName)astNode),nearestNode);
if(decl != null){
// see if locally defined
log(getNodeAsString(astNode)+" found decl -> " + getNodeAsString(decl));
return new ClassMember(extracTypeInfo(decl));
}
else {
// or in a predefined class?
Class<?> tehClass = findClassIfExists(((SimpleName) astNode).toString());
if (tehClass != null) {
return new ClassMember(tehClass);
}
}
astNode = astNode.getParent();
}
switch (astNode.getNodeType()) {
//TODO: Notice the redundancy in the 3 cases, you can simplify things even more.
case ASTNode.FIELD_ACCESS:
FieldAccess fa = (FieldAccess) astNode;
if (fa.getExpression() == null) {
// TODO: Check for existence of 'new' keyword. Could be a ClassInstanceCreation
// Local code or belongs to super class
log("FA,Not implemented.");
return null;
} else {
if (fa.getExpression() instanceof SimpleName) {
stp = extracTypeInfo(findDeclaration2((SimpleName) fa.getExpression(),
nearestNode));
if(stp == null){
/*The type wasn't found in local code, so it might be something like
* log(), or maybe belonging to super class, etc.
*/
Class<?> tehClass = findClassIfExists(((SimpleName)fa.getExpression()).toString());
if (tehClass != null) {
// Method Expression is a simple name and wasn't located locally, but found in a class
// so look for method in this class.
return definedIn3rdPartyClass(new ClassMember(tehClass), fa
.getName().toString());
}
log("FA resolve 3rd par, Can't resolve " + fa.getExpression());
return null;
}
log("FA, SN Type " + getNodeAsString(stp));
scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
} else {
scopeParent = resolveExpression3rdParty(nearestNode,
fa.getExpression(), noCompare);
}
log("FA, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(scopeParent, fa.getName().toString());
}
case ASTNode.METHOD_INVOCATION:
MethodInvocation mi = (MethodInvocation) astNode;
ASTNode temp = findDeclaration2(mi.getName(), nearestNode);
if(temp instanceof MethodDeclaration){
// method is locally defined
log(mi.getName() + " was found locally," + getNodeAsString(extracTypeInfo(temp)));
return new ClassMember(extracTypeInfo(temp));
}
if (mi.getExpression() == null) {
// if()
//Local code or belongs to super class
log("MI,Not implemented.");
return null;
} else {
if (mi.getExpression() instanceof SimpleName) {
stp = extracTypeInfo(findDeclaration2((SimpleName) mi.getExpression(),
nearestNode));
if(stp == null){
/*The type wasn't found in local code, so it might be something like
* System.console()., or maybe belonging to super class, etc.
*/
Class<?> tehClass = findClassIfExists(((SimpleName)mi.getExpression()).toString());
if (tehClass != null) {
// Method Expression is a simple name and wasn't located locally, but found in a class
// so look for method in this class.
return definedIn3rdPartyClass(new ClassMember(tehClass), mi
.getName().toString());
}
log("MI resolve 3rd par, Can't resolve " + mi.getExpression());
return null;
}
log("MI, SN Type " + getNodeAsString(stp));
ASTNode typeDec = findDeclaration2(stp.getName(),nearestNode);
if(typeDec == null){
log(stp.getName() + " couldn't be found locally..");
Class<?> tehClass = findClassIfExists(stp.getName().toString());
if (tehClass != null) {
// Method Expression is a simple name and wasn't located locally, but found in a class
// so look for method in this class.
return definedIn3rdPartyClass(new ClassMember(tehClass), mi
.getName().toString());
}
//return new ClassMember(findClassIfExists(stp.getName().toString()));
}
//scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
return definedIn3rdPartyClass(new ClassMember(typeDec), mi
.getName().toString());
} else {
log("MI EXP.."+getNodeAsString(mi.getExpression()));
// return null;
scopeParent = resolveExpression3rdParty(nearestNode,
mi.getExpression(), noCompare);
log("MI, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(scopeParent, mi.getName().toString());
}
}
case ASTNode.QUALIFIED_NAME:
QualifiedName qn = (QualifiedName) astNode;
ASTNode temp2 = findDeclaration2(qn.getName(), nearestNode);
if(temp2 instanceof FieldDeclaration){
// field is locally defined
log(qn.getName() + " was found locally," + getNodeAsString(extracTypeInfo(temp2)));
return new ClassMember(extracTypeInfo(temp2));
}
if (qn.getQualifier() == null) {
log("QN,Not implemented.");
return null;
} else {
if (qn.getQualifier() instanceof SimpleName) {
stp = extracTypeInfo(findDeclaration2(qn.getQualifier(), nearestNode));
if(stp == null){
/*The type wasn't found in local code, so it might be something like
* log(), or maybe belonging to super class, etc.
*/
Class<?> tehClass = findClassIfExists(qn.getQualifier().toString());
if (tehClass != null) {
// note how similar thing is called on line 690. Check check.
return definedIn3rdPartyClass(new ClassMember(tehClass), qn
.getName().toString());
}
log("QN resolve 3rd par, Can't resolve " + qn.getQualifier());
return null;
}
log("QN, SN Local Type " + getNodeAsString(stp));
//scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
ASTNode typeDec = findDeclaration2(stp.getName(),nearestNode);
if(typeDec == null){
log(stp.getName() + " couldn't be found locally..");
Class<?> tehClass = findClassIfExists(stp.getName().toString());
if (tehClass != null) {
// note how similar thing is called on line 690. Check check.
return definedIn3rdPartyClass(new ClassMember(tehClass), qn
.getName().toString());
}
log("QN resolve 3rd par, Can't resolve " + qn.getQualifier());
return null;
}
return definedIn3rdPartyClass(new ClassMember(typeDec), qn
.getName().toString());
} else {
scopeParent = resolveExpression3rdParty(nearestNode,
qn.getQualifier(), noCompare);
log("QN, ScopeParent " + scopeParent);
return definedIn3rdPartyClass(scopeParent, qn.getName().toString());
}
}
case ASTNode.ARRAY_ACCESS:
ArrayAccess arac = (ArrayAccess)astNode;
return resolveExpression3rdParty(nearestNode, arac.getArray(), noCompare);
default:
log("Unaccounted type " + getNodeAsString(astNode));
break;
}
return null;
}
/**
* For a().abc.a123 this would return a123
*
* @param expression
* @return
*/
public static ASTNode getChildExpression(ASTNode expression) {
// ASTNode anode = null;
if (expression instanceof SimpleName) {
return expression;
} else if (expression instanceof FieldAccess) {
return ((FieldAccess) expression).getName();
} else if (expression instanceof QualifiedName) {
return ((QualifiedName) expression).getName();
}else if (expression instanceof MethodInvocation) {
return ((MethodInvocation) expression).getName();
}else if(expression instanceof ArrayAccess){
return ((ArrayAccess)expression).getArray();
}
log(" getChildExpression returning NULL for "
+ getNodeAsString(expression));
return null;
}
public static ASTNode getParentExpression(ASTNode expression) {
// ASTNode anode = null;
if (expression instanceof SimpleName) {
return expression;
} else if (expression instanceof FieldAccess) {
return ((FieldAccess) expression).getExpression();
} else if (expression instanceof QualifiedName) {
return ((QualifiedName) expression).getQualifier();
} else if (expression instanceof MethodInvocation) {
return ((MethodInvocation) expression).getExpression();
} else if (expression instanceof ArrayAccess) {
return ((ArrayAccess) expression).getArray();
}
log("getParentExpression returning NULL for "
+ getNodeAsString(expression));
return null;
}
protected void trimCandidates(String newWord){
ArrayList<CompletionCandidate> newCandidate = new ArrayList<CompletionCandidate>();
newWord = newWord.toLowerCase();
for (CompletionCandidate comp : candidates) {
if(comp.getNoHtmlLabel().toLowerCase().startsWith(newWord)){
newCandidate.add(comp);
}
}
candidates = newCandidate;
}
/**
* List of CompletionCandidates
*/
protected ArrayList<CompletionCandidate> candidates;
protected String lastPredictedWord = " ";
//protected AtomicBoolean predictionsEnabled;
protected int predictionMinLength = 2;
private AtomicBoolean predictionOngoing;
/**
* The main function that calculates possible code completion candidates
*
* @param word
* @param line
* @param lineStartNonWSOffset
*/
public void preparePredictions(final String word, final int line, final int lineStartNonWSOffset) {
if(predictionOngoing.get()) return;
if (!JavaMode.codeCompletionsEnabled) return;
if (word.length() < predictionMinLength) return;
predictionOngoing.set(true);
// This method is called from TextArea.fetchPhrase, which is called via a SwingWorker instance
// in TextArea.processKeyEvent
if(caretWithinLineComment()){
log("No predictions.");
predictionOngoing.set(false);
return;
}
// SwingWorker worker = new SwingWorker() {
//
// @Override
// protected Object doInBackground() throws Exception {
// return null;
// }
//
// protected void done() {
// If the parsed code contains pde enhancements, take 'em out.
String word2 = ASTNodeWrapper.getJavaCode(word);
//After typing 'arg.' all members of arg type are to be listed. This one is a flag for it
boolean noCompare = false;
if (word2.endsWith(".")) {
// return all matches
word2 = word2.substring(0, word2.length() - 1);
noCompare = true;
}
if (word2.length() >= predictionMinLength && !noCompare
&& word2.length() > lastPredictedWord.length()) {
if (word2.startsWith(lastPredictedWord)) {
log(word + " starts with " + lastPredictedWord);
log("Don't recalc");
if (word2.contains(".")) {
int x = word2.lastIndexOf('.');
trimCandidates(word2.substring(x + 1));
} else {
trimCandidates(word2);
}
showPredictions(word);
lastPredictedWord = word2;
predictionOngoing.set(false);
return;
}
}
int lineNumber = line;
// Adjust line number for tabbed sketches
if (errorCheckerService != null) {
editor = errorCheckerService.getEditor();
int codeIndex = editor.getSketch().getCodeIndex(editor
.getCurrentTab());
if (codeIndex > 0)
for (int i = 0; i < codeIndex; i++) {
SketchCode sc = editor.getSketch().getCode(i);
int len = Base.countLines(sc.getProgram()) + 1;
lineNumber += len;
}
}
// Ensure that we're not inside a comment. TODO: Binary search
/*for (Comment comm : getCodeComments()) {
int commLineNo = PdeToJavaLineNumber(compilationUnit
.getLineNumber(comm.getStartPosition()));
if(commLineNo == lineNumber){
log("Found a comment line " + comm);
log("Comment LSO "
+ javaCodeOffsetToLineStartOffset(compilationUnit
.getLineNumber(comm.getStartPosition()),
comm.getStartPosition()));
break;
}
}*/
// Now parse the expression into an ASTNode object
ASTNode nearestNode = null;
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setKind(ASTParser.K_EXPRESSION);
parser.setSource(word2.toCharArray());
ASTNode testnode = parser.createAST(null);
//Base.loge("PREDICTION PARSER PROBLEMS: " + parser);
// Find closest ASTNode of the document to this word
Base.loge("Typed: " + word2 + "|" + " temp Node type: " + testnode.getClass().getSimpleName());
if(testnode instanceof MethodInvocation){
MethodInvocation mi = (MethodInvocation)testnode;
log(mi.getName() + "," + mi.getExpression() + "," + mi.typeArguments().size());
}
// find nearest ASTNode
nearestNode = findClosestNode(lineNumber, (ASTNode) errorCheckerService.getLastCorrectCU().types()
.get(0));
if (nearestNode == null) {
// Make sure nearestNode is not NULL if couldn't find a closeset node
nearestNode = (ASTNode) errorCheckerService.getLastCorrectCU().types().get(0);
}
Base.loge(lineNumber + " Nearest ASTNode to PRED "
+ getNodeAsString(nearestNode));
candidates = new ArrayList<CompletionCandidate>();
lastPredictedWord = word2;
// Determine the expression typed
if (testnode instanceof SimpleName && !noCompare) {
Base.loge("One word expression " + getNodeAsString(testnode));
//==> Simple one word exprssion - so is just an identifier
// Bottom up traversal of the AST to look for possible definitions at
// higher levels.
//nearestNode = nearestNode.getParent();
while (nearestNode != null) {
// If the current class has a super class, look inside it for
// definitions.
if (nearestNode instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) nearestNode;
if (td
.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY) != null) {
SimpleType st = (SimpleType) td
.getStructuralProperty(TypeDeclaration.SUPERCLASS_TYPE_PROPERTY);
log("Superclass " + st.getName());
for (CompletionCandidate can : getMembersForType(st.getName()
.toString(), word2, noCompare, false)) {
candidates.add(can);
}
//findDeclaration(st.getName())
}
}
List<StructuralPropertyDescriptor> sprops = nearestNode
.structuralPropertiesForType();
for (StructuralPropertyDescriptor sprop : sprops) {
ASTNode cnode = null;
if (!sprop.isChildListProperty()) {
if (nearestNode.getStructuralProperty(sprop) instanceof ASTNode) {
cnode = (ASTNode) nearestNode.getStructuralProperty(sprop);
CompletionCandidate[] types = checkForTypes(cnode);
if (types != null) {
for (int i = 0; i < types.length; i++) {
if (types[i].getElementName().toLowerCase().startsWith(word2.toLowerCase()))
candidates.add(types[i]);
}
}
}
} else {
// Childlist prop
List<ASTNode> nodelist = (List<ASTNode>) nearestNode
.getStructuralProperty(sprop);
for (ASTNode clnode : nodelist) {
CompletionCandidate[] types = checkForTypes(clnode);
if (types != null) {
for (int i = 0; i < types.length; i++) {
if (types[i].getElementName().toLowerCase().startsWith(word2.toLowerCase()))
candidates.add(types[i]);
}
}
}
}
}
nearestNode = nearestNode.getParent();
}
// We're seeing a simple name that's not defined locally or in
// the parent class. So most probably a pre-defined type.
log("Empty can. " + word2);
if (classPath != null) {
RegExpResourceFilter regExpResourceFilter;
regExpResourceFilter = new RegExpResourceFilter(
Pattern
.compile(".*"),
Pattern
.compile(word2
+ "[a-zA-Z_0-9]*.class",
Pattern.CASE_INSENSITIVE));
String[] resources = classPath.findResources("",
regExpResourceFilter);
for (String matchedClass2 : resources) {
matchedClass2 = matchedClass2.replace('/', '.'); //package name
String matchedClass = matchedClass2.substring(0, matchedClass2
.length() - 6);
int d = matchedClass.lastIndexOf('.');
if (ignorableImport(matchedClass2,matchedClass.substring(d + 1)))
continue;
matchedClass = matchedClass.substring(d + 1); //class name
candidates
.add(new CompletionCandidate(matchedClass, "<html>"
+ matchedClass + " : <font color=#777777>"
+ matchedClass2.substring(0, d) + "</font></html>",
matchedClass,
CompletionCandidate.PREDEF_CLASS)); // display package name in grey
//log("-> " + className);
}
}
} else {
// ==> Complex expression of type blah.blah2().doIt,etc
// Have to resolve it by carefully traversing AST of testNode
Base.loge("Complex expression " + getNodeAsString(testnode));
log("candidates empty");
ASTNode childExpr = getChildExpression(testnode);
log("Parent expression : " + getParentExpression(testnode));
log("Child expression : " + childExpr);
if (childExpr != null) {
if (!noCompare) {
log("Original testnode "
+ getNodeAsString(testnode));
testnode = getParentExpression(testnode);
log("Corrected testnode "
+ getNodeAsString(testnode));
}
ClassMember expr = resolveExpression3rdParty(nearestNode, testnode,
noCompare);
if (expr == null) {
log("Expr is null");
} else {
log("Expr is " + expr.toString());
candidates = getMembersForType(expr, childExpr.toString(),
noCompare, false);
}
}
else
{
log("ChildExpr is null");
}
}
showPredictions(word);
predictionOngoing.set(false);
// }
// };
//
// worker.execute();
}
protected void showPredictions(final String word) {
if (sketchOutline != null)
if (sketchOutline.isVisible()) return;
Collections.sort(candidates);
// CompletionCandidate[][] candi = new CompletionCandidate[candidates.size()][1];
// DefaultListModel<CompletionCandidate> defListModel = new DefaultListModel<CompletionCandidate>();
//
// for (int i = 0; i < candidates.size(); i++) {
//// candi[i][0] = candidates.get(i);
// defListModel.addElement(candidates.get(i));
// }
// log("Total preds = " + candidates.size());
DefaultListModel<CompletionCandidate> defListModel = filterPredictions();
// DefaultTableModel tm = new DefaultTableModel(candi,
// new String[] { "Suggestions" });
// if (tableAuto.isVisible()) {
// tableAuto.setModel(tm);
// tableAuto.validate();
// tableAuto.repaint();
// }
errorCheckerService.getEditor().getJavaTextArea().showSuggestion(defListModel, word);
}
private DefaultListModel<CompletionCandidate> filterPredictions(){
DefaultListModel<CompletionCandidate> defListModel = new DefaultListModel<CompletionCandidate>();
if (candidates.isEmpty())
return defListModel;
// check if first & last CompCandidate are the same methods, only then show all overloaded methods
if (candidates.get(0).getElementName()
.equals(candidates.get(candidates.size() - 1).getElementName())) {
log("All CC are methods only: " + candidates.get(0).getElementName());
for (int i = 0; i < candidates.size(); i++) {
candidates.get(i).regenerateCompletionString();
defListModel.addElement(candidates.get(i));
}
}
else {
boolean ignoredSome = false;
for (int i = 0; i < candidates.size(); i++) {
if(i > 0 && (candidates.get(i).getElementName()
.equals(candidates.get(i - 1).getElementName()))){
if (candidates.get(i).getType() == CompletionCandidate.LOCAL_METHOD
|| candidates.get(i).getType() == CompletionCandidate.PREDEF_METHOD) {
CompletionCandidate cc = candidates.get(i - 1);
String label = cc.getLabel();
int x = label.lastIndexOf(')');
if(candidates.get(i).getType() == CompletionCandidate.PREDEF_METHOD) {
cc.setLabel((cc.getLabel().contains("<html>") ? "<html>" : "")
+ cc.getElementName() + "(...)" + label.substring(x + 1));
}
else {
cc.setLabel(cc.getElementName() + "(...)" + label.substring(x + 1));
}
cc.setCompletionString(cc.getElementName() + "(");
ignoredSome = true;
continue;
}
}
defListModel.addElement(candidates.get(i));
}
if (ignoredSome) {
log("Some suggestions hidden");
}
}
return defListModel;
}
/**
* Loads classes from .jar files in sketch classpath
*
* @param typeName
* @param child
* @param noCompare
* @return
*/
public ArrayList<CompletionCandidate> getMembersForType(String typeName,
String child,
boolean noCompare,
boolean staticOnly) {
ArrayList<CompletionCandidate> candidates = new ArrayList<CompletionCandidate>();
log("In GMFT(), Looking for match " + child.toString()
+ " in class " + typeName + " noCompare " + noCompare + " staticOnly "
+ staticOnly);
Class<?> probableClass = findClassIfExists(typeName);
if(probableClass == null){
log("In GMFT(), class not found.");
return candidates;
}
return getMembersForType(new ClassMember(probableClass), child, noCompare, staticOnly);
}
public ArrayList<CompletionCandidate> getMembersForType(ClassMember tehClass,
String childToLookFor,
boolean noCompare,
boolean staticOnly) {
String child = childToLookFor.toLowerCase();
ArrayList<CompletionCandidate> candidates = new ArrayList<CompletionCandidate>();
log("getMemFoType-> Looking for match " + child.toString()
+ " inside " + tehClass + " noCompare " + noCompare + " staticOnly "
+ staticOnly);
if(tehClass == null){
return candidates;
}
// tehClass will either be a TypeDecl defined locally
if(tehClass.getDeclaringNode() instanceof TypeDeclaration){
TypeDeclaration td = (TypeDeclaration) tehClass.getDeclaringNode();
for (int i = 0; i < td.getFields().length; i++) {
List<VariableDeclarationFragment> vdfs = td.getFields()[i]
.fragments();
for (VariableDeclarationFragment vdf : vdfs) {
if (noCompare) {
candidates
.add(new CompletionCandidate(vdf));
} else if (vdf.getName().toString().toLowerCase()
.startsWith(child))
candidates
.add(new CompletionCandidate(vdf));
}
}
for (int i = 0; i < td.getMethods().length; i++) {
if (noCompare) {
candidates.add(new CompletionCandidate(td.getMethods()[i]));
} else if (td.getMethods()[i].getName().toString().toLowerCase()
.startsWith(child))
candidates.add(new CompletionCandidate(td.getMethods()[i]));
}
ArrayList<CompletionCandidate> superClassCandidates = new ArrayList<CompletionCandidate>();
if(td.getSuperclassType() != null){
log(getNodeAsString(td.getSuperclassType()) + " <-Looking into superclass of " + tehClass);
superClassCandidates = getMembersForType(new ClassMember(td
.getSuperclassType()),
childToLookFor, noCompare, staticOnly);
}
else
{
superClassCandidates = getMembersForType(new ClassMember(Object.class),
childToLookFor, noCompare, staticOnly);
}
for (CompletionCandidate cc : superClassCandidates) {
candidates.add(cc);
}
return candidates;
}
// Or tehClass will be a predefined class
Class<?> probableClass;
if (tehClass.getClass_() != null) {
probableClass = tehClass.getClass_();
} else {
probableClass = findClassIfExists(tehClass.getTypeAsString());
if (probableClass == null) {
log("Couldn't find class " + tehClass.getTypeAsString());
return candidates;
}
log("Loaded " + probableClass.toString());
}
for (Method method : probableClass.getMethods()) {
if (!Modifier.isStatic(method.getModifiers()) && staticOnly) {
continue;
}
StringBuilder label = new StringBuilder(method.getName() + "(");
for (int i = 0; i < method.getParameterTypes().length; i++) {
label.append(method.getParameterTypes()[i].getSimpleName());
if (i < method.getParameterTypes().length - 1)
label.append(",");
}
label.append(")");
if (noCompare) {
candidates.add(new CompletionCandidate(method));
} else if (label.toString().toLowerCase().startsWith(child)) {
candidates.add(new CompletionCandidate(method));
}
}
for (Field field : probableClass.getFields()) {
if (!Modifier.isStatic(field.getModifiers()) && staticOnly) {
continue;
}
if (noCompare) {
candidates.add(new CompletionCandidate(field));
} else if (field.getName().toLowerCase().startsWith(child)) {
candidates.add(new CompletionCandidate(field));
}
}
return candidates;
}
public String getPDESourceCodeLine(int javaLineNumber) {
int res[] = errorCheckerService
.calculateTabIndexAndLineNumber(javaLineNumber);
if (res != null) {
return errorCheckerService.getPDECodeAtLine(res[0], res[1]);
}
return null;
}
/**
* Returns the java source code line at the given line number
* @param javaLineNumber
* @return
*/
public String getJavaSourceCodeLine(int javaLineNumber) {
try {
PlainDocument javaSource = new PlainDocument();
javaSource.insertString(0, errorCheckerService.sourceCode, null);
Element lineElement = javaSource.getDefaultRootElement()
.getElement(javaLineNumber - 1);
if (lineElement == null) {
log("Couldn't fetch jlinenum " + javaLineNumber);
return null;
}
String javaLine = javaSource.getText(lineElement.getStartOffset(),
lineElement.getEndOffset()
- lineElement.getStartOffset());
return javaLine;
} catch (BadLocationException e) {
Base.loge(e + " in getJavaSourceCodeline() for jinenum: " + javaLineNumber);
}
return null;
}
/**
* Returns the java source code line Element at the given line number.
* The Element object stores the offset data, but not the actual line
* of code.
* @param javaLineNumber
* @return
*/
public Element getJavaSourceCodeElement(int javaLineNumber) {
try {
PlainDocument javaSource = new PlainDocument();
javaSource.insertString(0, errorCheckerService.sourceCode, null);
Element lineElement = javaSource.getDefaultRootElement()
.getElement(javaLineNumber - 1);
if (lineElement == null) {
log("Couldn't fetch jlinenum " + javaLineNumber);
return null;
}
// String javaLine = javaSource.getText(lineElement.getStartOffset(),
// lineElement.getEndOffset()
// - lineElement.getStartOffset());
return lineElement;
} catch (BadLocationException e) {
Base.loge(e + " in getJavaSourceCodeline() for jinenum: " + javaLineNumber);
}
return null;
}
/**
* Searches for the particular class in the default list of imports as well as
* the Sketch classpath
* @param className
* @return
*/
protected Class<?> findClassIfExists(String className){
if(className == null){
return null;
}
Class<?> tehClass = null;
// First, see if the classname is a fully qualified name and loads straightaway
tehClass = loadClass(className);
if (tehClass != null) {
//log(tehClass.getName() + " located straightaway");
return tehClass;
}
log("Looking in the classloader for " + className);
ArrayList<ImportStatement> imports = errorCheckerService
.getProgramImports();
for (ImportStatement impS : imports) {
String temp = impS.getPackageName();
if (temp.endsWith("*")) {
temp = temp.substring(0, temp.length() - 1) + className;
} else {
int x = temp.lastIndexOf('.');
//log("fclife " + temp.substring(x + 1));
if (!temp.substring(x + 1).equals(className)) {
continue;
}
}
tehClass = loadClass(temp);
if (tehClass != null) {
log(tehClass.getName() + " located.");
return tehClass;
}
//log("Doesn't exist in package: " + impS.getImportName());
}
PdePreprocessor p = new PdePreprocessor(null);
for (String impS : p.getCoreImports()) {
tehClass = loadClass(impS.substring(0,impS.length()-1) + className);
if (tehClass != null) {
log(tehClass.getName() + " located.");
return tehClass;
}
//log("Doesn't exist in package: " + impS);
}
for (String impS : p.getDefaultImports()) {
if(className.equals(impS) || impS.endsWith(className)){
tehClass = loadClass(impS);
if (tehClass != null) {
log(tehClass.getName() + " located.");
return tehClass;
}
// log("Doesn't exist in package: " + impS);
}
}
// And finally, the daddy
String daddy = "java.lang." + className;
tehClass = loadClass(daddy);
if (tehClass != null) {
log(tehClass.getName() + " located.");
return tehClass;
}
//log("Doesn't exist in java.lang");
return tehClass;
}
protected Class<?> loadClass(String className){
Class<?> tehClass = null;
if (className != null) {
try {
tehClass = Class.forName(className, false,
errorCheckerService.getSketchClassLoader());
} catch (ClassNotFoundException e) {
//log("Doesn't exist in package: ");
}
}
return tehClass;
}
public ClassMember definedIn3rdPartyClass(String className,String memberName){
Class<?> probableClass = findClassIfExists(className);
if (probableClass == null) {
log("Couldn't load " + className);
return null;
}
if (memberName.equals("THIS")) {
return new ClassMember(probableClass);
} else {
return definedIn3rdPartyClass(new ClassMember(probableClass), memberName);
}
}
public ClassMember definedIn3rdPartyClass(ClassMember tehClass,String memberName){
if(tehClass == null)
return null;
log("definedIn3rdPartyClass-> Looking for " + memberName
+ " in " + tehClass);
String memberNameL = memberName.toLowerCase();
if (tehClass.getDeclaringNode() instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) tehClass.getDeclaringNode();
for (int i = 0; i < td.getFields().length; i++) {
List<VariableDeclarationFragment> vdfs =
td.getFields()[i].fragments();
for (VariableDeclarationFragment vdf : vdfs) {
if (vdf.getName().toString().toLowerCase()
.startsWith(memberNameL))
return new ClassMember(vdf);
}
}
for (int i = 0; i < td.getMethods().length; i++) {
if (td.getMethods()[i].getName().toString().toLowerCase()
.startsWith(memberNameL))
return new ClassMember(td.getMethods()[i]);
}
if (td.getSuperclassType() != null) {
log(getNodeAsString(td.getSuperclassType()) + " <-Looking into superclass of " + tehClass);
return definedIn3rdPartyClass(new ClassMember(td
.getSuperclassType()),memberName);
} else {
return definedIn3rdPartyClass(new ClassMember(Object.class),memberName);
}
}
Class probableClass = null;
if (tehClass.getClass_() != null) {
probableClass = tehClass.getClass_();
} else {
probableClass = findClassIfExists(tehClass.getTypeAsString());
log("Loaded " + probableClass.toString());
}
for (Method method : probableClass.getMethods()) {
if (method.getName().equalsIgnoreCase(memberName)) {
return new ClassMember(method);
}
}
for (Field field : probableClass.getFields()) {
if (field.getName().equalsIgnoreCase(memberName)) {
return new ClassMember(field);
}
}
return null;
}
public void updateJavaDoc(final CompletionCandidate candidate) {
//TODO: Work on this later.
return;
/* String methodmatch = candidate.toString();
if (methodmatch.indexOf('(') != -1) {
methodmatch = methodmatch.substring(0, methodmatch.indexOf('('));
}
//log("jdoc match " + methodmatch);
String temp = "<html> </html>";
for (final String key : jdocMap.keySet()) {
if (key.startsWith(methodmatch) && key.length() > 3) {
log("Matched jdoc " + key);
if (candidate.getWrappedObject() != null) {
String definingClass = "";
if (candidate.getWrappedObject() instanceof Field)
definingClass = ((Field) candidate.getWrappedObject())
.getDeclaringClass().getName();
else if (candidate.getWrappedObject() instanceof Method)
definingClass = ((Method) candidate.getWrappedObject())
.getDeclaringClass().getName();
if (definingClass.equals("processing.core.PApplet")) {
temp = (jdocMap.get(key));
break;
}
}
}
}
final String jdocString = temp;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
javadocPane.setText(jdocString);
scrollPane.getVerticalScrollBar().setValue(0);
//frmJavaDoc.setVisible(!jdocString.equals("<html> </html>"));
editor.toFront();
editor.ta.requestFocus();
}
});
*/
}
protected static ASTNode findClosestParentNode(int lineNumber, ASTNode node) {
Iterator<StructuralPropertyDescriptor> it = node
.structuralPropertiesForType().iterator();
// Base.loge("Props of " + node.getClass().getName());
while (it.hasNext()) {
StructuralPropertyDescriptor prop = it.next();
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (node.getStructuralProperty(prop) != null) {
// System.out
// .println(node.getStructuralProperty(prop) + " -> " + (prop));
if (node.getStructuralProperty(prop) instanceof ASTNode) {
ASTNode cnode = (ASTNode) node.getStructuralProperty(prop);
// log("Looking at " + getNodeAsString(cnode)+ " for line num " + lineNumber);
int cLineNum = ((CompilationUnit) cnode.getRoot())
.getLineNumber(cnode.getStartPosition() + cnode.getLength());
if (getLineNumber(cnode) <= lineNumber && lineNumber <= cLineNum) {
return findClosestParentNode(lineNumber, cnode);
}
}
}
}
else if (prop.isChildListProperty()) {
List<ASTNode> nodelist = (List<ASTNode>) node
.getStructuralProperty(prop);
for (ASTNode cnode : nodelist) {
int cLineNum = ((CompilationUnit) cnode.getRoot())
.getLineNumber(cnode.getStartPosition() + cnode.getLength());
// log("Looking at " + getNodeAsString(cnode)+ " for line num " + lineNumber);
if (getLineNumber(cnode) <= lineNumber && lineNumber <= cLineNum) {
return findClosestParentNode(lineNumber, cnode);
}
}
}
}
return node;
}
protected static ASTNode findClosestNode(int lineNumber, ASTNode node) {
log("findClosestNode to line " + lineNumber);
ASTNode parent = findClosestParentNode(lineNumber, node);
log("findClosestParentNode returned " + getNodeAsString(parent));
if (parent == null)
return null;
if (getLineNumber(parent) == lineNumber){
log(parent + "|PNode " + getLineNumber(parent) + ", lfor " + lineNumber );
return parent;
}
List<ASTNode> nodes = null;
if (parent instanceof TypeDeclaration) {
nodes = ((TypeDeclaration) parent).bodyDeclarations();
} else if (parent instanceof Block) {
nodes = ((Block) parent).statements();
} else {
System.err.println("THIS CONDITION SHOULD NOT OCCUR - findClosestNode "
+ getNodeAsString(parent));
return null;
}
if (nodes.size() > 0) {
ASTNode retNode = parent;
for (int i = 0; i < nodes.size(); i++) {
ASTNode cNode = nodes.get(i);
log(cNode + "|cNode " + getLineNumber(cNode) + ", lfor " + lineNumber );
if (getLineNumber(cNode) <= lineNumber)
retNode = cNode;
}
return retNode;
}
return parent;
}
public DefaultMutableTreeNode getAST() {
return codeTree;
}
public String getLabelForASTNode(int lineNumber, String name, int offset) {
return getASTNodeAt(lineNumber, name, offset, false).getLabel();
//return "";
}
protected String getLabelIfType(ASTNodeWrapper node, SimpleName sn){
ASTNode current = node.getNode().getParent();
String type = "";
StringBuilder fullName = new StringBuilder();
Stack<String> parents = new Stack<String>();
String simpleName = (sn == null) ? node.getNode().toString() : sn.toString();
switch (node.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
case ASTNode.METHOD_DECLARATION:
case ASTNode.FIELD_DECLARATION:
while (current != null) {
if (current instanceof TypeDeclaration) {
parents.push(((TypeDeclaration) current).getName().toString());
}
current = current.getParent();
}
while (parents.size() > 0) {
fullName.append(parents.pop() + ".");
}
fullName.append(simpleName);
if (node.getNode() instanceof MethodDeclaration) {
MethodDeclaration md = (MethodDeclaration) node.getNode();
if (!md.isConstructor())
type = md.getReturnType2().toString();
fullName.append('(');
if (!md.parameters().isEmpty()) {
List<ASTNode> params = md.parameters();
for (ASTNode par : params) {
if (par instanceof SingleVariableDeclaration) {
SingleVariableDeclaration svd = (SingleVariableDeclaration) par;
fullName.append(svd.getType() + " " + svd.getName() + ",");
}
}
}
if(fullName.charAt(fullName.length() - 1) == ',')
fullName.deleteCharAt(fullName.length() - 1);
fullName.append(')');
}
else if(node.getNode() instanceof FieldDeclaration){
type = ((FieldDeclaration) node.getNode()).getType().toString();
}
int x = fullName.indexOf(".");
fullName.delete(0, x + 1);
return type + " " + fullName;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
SingleVariableDeclaration svd = (SingleVariableDeclaration)node.getNode();
return svd.getType() + " " + svd.getName();
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
return ((VariableDeclarationStatement) node.getNode()).getType() + " "
+ simpleName;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
return ((VariableDeclarationExpression) node.getNode()).getType() + " "
+ simpleName;
default:
break;
}
return "";
}
public void scrollToDeclaration(int lineNumber, String name, int offset) {
getASTNodeAt(lineNumber, name, offset, true);
}
/**
* Given a word(identifier) in pde code, finds its location in the ASTNode
* @param lineNumber
* @param name
* @param offset - line start nonwhitespace offset
* @param scrollOnly
* @return
*/
public ASTNodeWrapper getASTNodeAt(int lineNumber, String name, int offset,
boolean scrollOnly) {
// Convert tab based pde line number to actual line number
int pdeLineNumber = lineNumber + errorCheckerService.mainClassOffset;
// log("----getASTNodeAt---- CU State: "
// + errorCheckerService.compilationUnitState);
if (errorCheckerService != null) {
editor = errorCheckerService.getEditor();
int codeIndex = editor.getSketch().getCodeIndex(editor.getCurrentTab());
if (codeIndex > 0) {
for (int i = 0; i < codeIndex; i++) {
SketchCode sc = editor.getSketch().getCode(i);
int len = Base.countLines(sc.getProgram()) + 1;
pdeLineNumber += len;
}
}
}
// Find closest ASTNode to the linenumber
// log("getASTNodeAt: Node line number " + pdeLineNumber);
ASTNode lineNode = findLineOfNode(compilationUnit, pdeLineNumber, offset,
name);
// log("Node text +> " + lineNode);
ASTNode decl = null;
String nodeLabel = null;
String nameOfNode = null; // The node name which is to be scrolled to
// Obtain correspondin java code at that line, match offsets
if (lineNode != null) {
String pdeCodeLine = errorCheckerService.getPDECodeAtLine(editor
.getSketch().getCurrentCodeIndex(), lineNumber);
String javaCodeLine = getJavaSourceCodeLine(pdeLineNumber);
// log(lineNumber + " Original Line num.\nPDE :" + pdeCodeLine);
// log("JAVA:" + javaCodeLine);
// log("Clicked on: " + name + " start offset: " + offset);
// Calculate expected java offset based on the pde line
OffsetMatcher ofm = new OffsetMatcher(pdeCodeLine, javaCodeLine);
int javaOffset = ofm.getJavaOffForPdeOff(offset, name.length())
+ lineNode.getStartPosition();
// log("JAVA ast offset: " + (javaOffset));
// Find the corresponding node in the AST
ASTNode simpName = dfsLookForASTNode(errorCheckerService.getLatestCU(),
name, javaOffset,
javaOffset + name.length());
// If node wasn't found in the AST, lineNode may contain something
if (simpName == null && lineNode instanceof SimpleName) {
switch (lineNode.getParent().getNodeType()) {
case ASTNode.TYPE_DECLARATION:
case ASTNode.METHOD_DECLARATION:
case ASTNode.FIELD_DECLARATION:
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
decl = lineNode.getParent();
return new ASTNodeWrapper(decl, "");
default:
break;
}
}
// SimpleName instance found, now find its declaration in code
if (simpName instanceof SimpleName) {
nameOfNode = simpName.toString();
// log(getNodeAsString(simpName));
decl = findDeclaration((SimpleName) simpName);
if (decl != null) {
// Base.loge("DECLA: " + decl.getClass().getName());
nodeLabel = getLabelIfType(new ASTNodeWrapper(decl),
(SimpleName) simpName);
//retLabelString = getNodeAsString(decl);
} else {
// Base.loge("null");
if (scrollOnly) {
editor.statusMessage(simpName + " is not defined in this sketch",
JavaEditor.STATUS_ERR);
}
}
// log(getNodeAsString(decl));
/*
// - findDecl3 testing
ASTNode nearestNode = findClosestNode(lineNumber,
(ASTNode) compilationUnit.types()
.get(0));
ClassMember cmem = resolveExpression3rdParty(nearestNode,
(SimpleName) simpName,
false);
if (cmem != null) {
log("CMEM-> " + cmem);
} else
log("CMEM-> null");
*/
}
}
if (decl != null && scrollOnly) {
/*
* For scrolling, we highlight just the name of the node, i.e., a
* SimpleName instance. But the declared node always points to the
* declared node itself, like TypeDecl, MethodDecl, etc. This is important
* since it contains all the properties.
*/
ASTNode simpName2 = getNodeName(decl, nameOfNode);
// Base.loge("FINAL String decl: " + getNodeAsString(decl));
// Base.loge("FINAL String label: " + getNodeAsString(simpName2));
//errorCheckerService.highlightNode(simpName2);
ASTNodeWrapper declWrap = new ASTNodeWrapper(simpName2, nodeLabel);
//errorCheckerService.highlightNode(declWrap);
if (!declWrap.highlightNode(this)) {
Base.loge("Highlighting failed.");
}
}
// Return the declaration wrapped as ASTNodeWrapper
return new ASTNodeWrapper(decl, nodeLabel);
}
/**
* Given a declaration type astnode, returns the SimpleName peroperty
* of that node.
* @param node
* @param name - The name we're looking for.
* @return SimpleName
*/
protected static ASTNode getNodeName(ASTNode node, String name){
List<VariableDeclarationFragment> vdfs = null;
switch (node.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
return ((TypeDeclaration) node).getName();
case ASTNode.METHOD_DECLARATION:
return ((MethodDeclaration) node).getName();
case ASTNode.SINGLE_VARIABLE_DECLARATION:
return ((SingleVariableDeclaration) node).getName();
case ASTNode.FIELD_DECLARATION:
vdfs = ((FieldDeclaration) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
vdfs = ((VariableDeclarationStatement) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
vdfs = ((VariableDeclarationExpression) node).fragments();
break;
default:
break;
}
if (vdfs != null) {
for (VariableDeclarationFragment vdf : vdfs) {
if (vdf.getName().toString().equals(name)) {
return vdf.getName();
}
}
}
return null;
}
/**
* Fetches line number of the node in its CompilationUnit.
* @param node
* @return
*/
public static int getLineNumber(ASTNode node) {
return ((CompilationUnit) node.getRoot()).getLineNumber(node
.getStartPosition());
}
public static int getLineNumber(ASTNode node, int pos) {
return ((CompilationUnit) node.getRoot()).getLineNumber(pos);
}
public static void main(String[] args) {
//traversal2();
}
public static void traversal2() {
ASTParser parser = ASTParser.newParser(AST.JLS4);
String source = readFile("/media/quarkninja/Work/TestStuff/low.java");
// String source = "package decl; \npublic class ABC{\n int ret(){\n}\n}";
parser.setSource(source.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_6, options);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6);
parser.setCompilerOptions(options);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
log(CompilationUnit.propertyDescriptors(AST.JLS4).size());
DefaultMutableTreeNode astTree = new DefaultMutableTreeNode("CompilationUnit");
Base.loge("Errors: " + cu.getProblems().length);
visitRecur(cu, astTree);
Base.log("" + astTree.getChildCount());
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame2 = new JFrame();
JTree jtree = new JTree(astTree);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setBounds(new Rectangle(100, 100, 460, 620));
JScrollPane sp = new JScrollPane();
sp.setViewportView(jtree);
frame2.add(sp);
frame2.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
ASTNode found = NodeFinder.perform(cu, 468, 5);
if (found != null) {
Base.log(found.toString());
}
}
final ASTGenerator thisASTGenerator = this;
protected void addListeners(){
jtree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
Base.log(e.toString());
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
return null;
}
protected void done() {
if(jtree
.getLastSelectedPathComponent() == null){
return;
}
DefaultMutableTreeNode tnode = (DefaultMutableTreeNode) jtree
.getLastSelectedPathComponent();
if (tnode.getUserObject() instanceof ASTNodeWrapper) {
ASTNodeWrapper awrap = (ASTNodeWrapper) tnode.getUserObject();
awrap.highlightNode(thisASTGenerator);
// errorCheckerService.highlightNode(awrap);
//--
try {
int javaLineNumber = getLineNumber(awrap.getNode());
int pdeOffs[] = errorCheckerService
.calculateTabIndexAndLineNumber(javaLineNumber);
PlainDocument javaSource = new PlainDocument();
javaSource.insertString(0, errorCheckerService.sourceCode, null);
Element lineElement = javaSource.getDefaultRootElement()
.getElement(javaLineNumber-1);
if(lineElement == null) {
return;
}
String javaLine = javaSource.getText(lineElement.getStartOffset(),
lineElement.getEndOffset()
- lineElement.getStartOffset());
editor.getSketch().setCurrentCode(pdeOffs[0]);
String pdeLine = editor.getLineText(pdeOffs[1]);
//String lookingFor = nodeName.toString();
//log(lookingFor + ", " + nodeName.getStartPosition());
log("JL " + javaLine + " LSO " + lineElement.getStartOffset() + ","
+ lineElement.getEndOffset());
log("PL " + pdeLine);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
};
worker.execute();
}
});
btnRename.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(txtRenameField.getText().length() == 0)
return;
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
return null;
}
protected void done() {
refactorIt();
}
};
worker.execute();
}
});
btnListOccurrence.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
return null;
}
protected void done() {
handleShowUsage();
}
};
worker.execute();
}
});
treeRename.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
log(e);
SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
return null;
}
protected void done() {
if(treeRename
.getLastSelectedPathComponent() == null){
return;
}
DefaultMutableTreeNode tnode = (DefaultMutableTreeNode) treeRename
.getLastSelectedPathComponent();
if (tnode.getUserObject() instanceof ASTNodeWrapper) {
ASTNodeWrapper awrap = (ASTNodeWrapper) tnode.getUserObject();
//errorCheckerService.highlightNode(awrap);
awrap.highlightNode(thisASTGenerator);
}
}
};
worker.execute();
}
});
}
protected void refactorIt(){
String newName = txtRenameField.getText().trim();
String selText = lastClickedWord == null ? getSelectedText()
: lastClickedWord;
// Find all occurrences of last clicked word
DefaultMutableTreeNode defCU = findAllOccurrences(); //TODO: Repetition here
if(defCU == null){
editor.statusMessage("Can't locate definition of " + selText,
JavaEditor.STATUS_ERR);
return;
}
// Verify if the new name is a valid java identifier
if(!newName.matches("([a-zA-Z][a-zA-Z0-9_]*)|([_][a-zA-Z0-9_]+)"))
{
JOptionPane.showConfirmDialog(new JFrame(), newName
+ " isn't a valid name.", "Uh oh..", JOptionPane.PLAIN_MESSAGE);
return;
}
//else log("New name looks K.");
errorCheckerService.pauseThread();
if(treeRename.isVisible()){
treeRename.setModel(new DefaultTreeModel(defCU));
((DefaultTreeModel) treeRename.getModel()).reload();
}
// frmOccurenceList.setTitle("Usage of \"" + selText + "\" : "
// + defCU.getChildCount() + " time(s)");
// frmOccurenceList.setLocation(editor.getX() + editor.getWidth(),editor.getY());
// frmOccurenceList.setVisible(true);
int lineOffsetDisplacementConst = newName.length()
- selText.length();
HashMap<Integer, Integer> lineOffsetDisplacement = new HashMap<Integer, Integer>();
// I need to store the pde and java offsets beforehand because once
// the replace starts, all offsets returned are affected
//int offsetsMap[][][] = new int[defCU.getChildCount()][2][];
int pdeOffsets[][] = new int[defCU.getChildCount()][3];
for (int i = 0; i < defCU.getChildCount(); i++) {
ASTNodeWrapper awrap = (ASTNodeWrapper) ((DefaultMutableTreeNode) (defCU
.getChildAt(i))).getUserObject();
int ans[] = errorCheckerService.calculateTabIndexAndLineNumber(awrap
.getLineNumber());
pdeOffsets[i][0] = ans[0];
pdeOffsets[i][1] = ans[1];
pdeOffsets[i][2] = awrap.getPDECodeOffsetForSN(this);
}
editor.startCompoundEdit();
for (int i = 0; i < defCU.getChildCount(); i++) {
ASTNodeWrapper awrap = (ASTNodeWrapper) ((DefaultMutableTreeNode) (defCU
.getChildAt(i))).getUserObject();
// correction for pde enhancements related displacement on a line
int off = 0;
if (lineOffsetDisplacement.get(awrap.getLineNumber()) != null) {
off = lineOffsetDisplacement.get(awrap.getLineNumber());
lineOffsetDisplacement.put(awrap.getLineNumber(),
lineOffsetDisplacementConst + off);
} else {
lineOffsetDisplacement.put(awrap.getLineNumber(),
lineOffsetDisplacementConst);
}
// Base.loge(getNodeAsString(awrap.getNode()) + ", T:" + pdeOffsets[i][0]
// + ", L:" + pdeOffsets[i][1] + ", O:" + pdeOffsets[i][2]);
highlightPDECode(pdeOffsets[i][0],
pdeOffsets[i][1], pdeOffsets[i][2]
+ off, awrap.getNode()
.toString().length());
//int k = JOptionPane.showConfirmDialog(new JFrame(), "Rename?","", JOptionPane.INFORMATION_MESSAGE);
editor.getTextArea().setSelectedText(newName);
}
editor.stopCompoundEdit();
errorCheckerService.resumeThread();
editor.getSketch().setModified(true);
errorCheckerService.runManualErrorCheck();
// frmOccurenceList.setVisible(false);
frmRename.setVisible(false);
lastClickedWord = null;
lastClickedWordNode = null;
}
/**
* Highlights text in the editor
* @param tab
* @param lineNumber
* @param lineStartWSOffset - line start offset including initial white space
* @param length
*/
public void highlightPDECode(int tab, int lineNumber, int lineStartWSOffset,
int length) {
// log("ASTGen.highlightPDECode: T " + tab + ",L: " + lineNumber + ",LSO: "
// + lineStartWSOffset + ",Len: " + length);
editor.toFront();
editor.getSketch().setCurrentCode(tab);
lineStartWSOffset += editor.getTextArea().getLineStartOffset(lineNumber);
editor.getTextArea().select(lineStartWSOffset, lineStartWSOffset + length);
}
public void handleShowUsage() {
if (editor.hasJavaTabs()) return; // show usage disabled if java tabs
log("Last clicked word:" + lastClickedWord);
if (lastClickedWord == null &&
getSelectedText() == null) {
editor.statusMessage("Highlight the class/function/variable name first"
, JavaEditor.STATUS_INFO);
return;
}
if(errorCheckerService.hasSyntaxErrors()){
editor.statusMessage("Can't perform action until syntax errors are " +
"fixed :(", JavaEditor.STATUS_WARNING);
return;
}
DefaultMutableTreeNode defCU = findAllOccurrences();
String selText = lastClickedWord == null ?
getSelectedText() : lastClickedWord;
if (defCU == null) {
editor.statusMessage("Can't locate definition of " + selText,
JavaEditor.STATUS_ERR);
return;
}
if(defCU.getChildCount() == 0)
return;
treeRename.setModel(new DefaultTreeModel(defCU));
((DefaultTreeModel) treeRename.getModel()).reload();
treeRename.setRootVisible(false);
frmOccurenceList.setTitle("Usage of \"" + selText + "\" : "
+ defCU.getChildCount() + " time(s)");
frmOccurenceList.setLocation(editor.getX() + editor.getWidth(),editor.getY());
frmOccurenceList.setVisible(true);
lastClickedWord = null;
lastClickedWordNode = null;
}
protected String lastClickedWord = null;
protected ASTNodeWrapper lastClickedWordNode = null;
public String getLastClickedWord() {
return lastClickedWord;
}
public void setLastClickedWord(int lineNumber, String lastClickedWord, int offset) {
this.lastClickedWord = lastClickedWord;
lastClickedWordNode = getASTNodeAt(lineNumber, lastClickedWord, offset, false);
log("Last clicked node: " + lastClickedWordNode);
}
protected DefaultMutableTreeNode findAllOccurrences(){
final JEditTextArea ta = editor.getTextArea();
log("Last clicked word:" + lastClickedWord);
String selText = lastClickedWord == null ? ta.getSelectedText() :
lastClickedWord;
int line = ta.getSelectionStartLine();
log(selText
+ "<- offsets "
+ (line)
+ ", "
+ (ta.getSelectionStart() - ta.getLineStartOffset(line))
+ ", "
+ (ta.getSelectionStop() - ta.getLineStartOffset(line)));
int offwhitespace = ta.getLineStartNonWhiteSpaceOffset(line);
ASTNodeWrapper wnode;
if (lastClickedWord == null || lastClickedWordNode.getNode() == null) {
wnode = getASTNodeAt(line + errorCheckerService.mainClassOffset, selText,
ta.getSelectionStart() - offwhitespace, false);
}
else{
wnode = lastClickedWordNode;
}
if(wnode.getNode() == null){
return null;
}
Base.loge("Gonna find all occurrences of "
+ getNodeAsString(wnode.getNode()));
//If wnode is a constructor, find the TD instead.
if (wnode.getNodeType() == ASTNode.METHOD_DECLARATION) {
MethodDeclaration md = (MethodDeclaration) wnode.getNode();
ASTNode node = md.getParent();
while (node != null) {
if (node instanceof TypeDeclaration) {
// log("Parent class " + getNodeAsString(node));
break;
}
node = node.getParent();
}
if(node != null && node instanceof TypeDeclaration){
TypeDeclaration td = (TypeDeclaration) node;
if(td.getName().toString().equals(md.getName().toString())){
Base.loge("Renaming constructor of " + getNodeAsString(td));
wnode = new ASTNodeWrapper(td);
}
}
}
DefaultMutableTreeNode defCU = new DefaultMutableTreeNode(
new ASTNodeWrapper(
wnode
.getNode(),
selText));
dfsNameOnly(defCU, wnode.getNode(), selText);
// Reverse the list obtained via dfs
Stack<Object> tempS = new Stack<Object>();
for (int i = 0; i < defCU.getChildCount(); i++) {
tempS.push(defCU.getChildAt(i));
}
defCU.removeAllChildren();
while (!tempS.isEmpty()) {
defCU.add((MutableTreeNode) tempS.pop());
}
log(wnode);
return defCU;
}
/**
* Generates AST Swing component
* @param node
* @param tnode
*/
public static void visitRecur(ASTNode node, DefaultMutableTreeNode tnode) {
Iterator<StructuralPropertyDescriptor> it =
node.structuralPropertiesForType().iterator();
//Base.loge("Props of " + node.getClass().getName());
DefaultMutableTreeNode ctnode = null;
while (it.hasNext()) {
StructuralPropertyDescriptor prop = it.next();
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (node.getStructuralProperty(prop) != null) {
// System.out
// .println(node.getStructuralProperty(prop) + " -> " + (prop));
if (node.getStructuralProperty(prop) instanceof ASTNode) {
ASTNode cnode = (ASTNode) node.getStructuralProperty(prop);
if (isAddableASTNode(cnode)) {
ctnode = new DefaultMutableTreeNode(
new ASTNodeWrapper((ASTNode) node
.getStructuralProperty(prop)));
tnode.add(ctnode);
visitRecur(cnode, ctnode);
}
} else {
tnode.add(new DefaultMutableTreeNode(node
.getStructuralProperty(prop)));
}
}
} else if (prop.isChildListProperty()) {
List<ASTNode> nodelist = (List<ASTNode>)
node.getStructuralProperty(prop);
for (ASTNode cnode : nodelist) {
if (isAddableASTNode(cnode)) {
ctnode = new DefaultMutableTreeNode(new ASTNodeWrapper(cnode));
tnode.add(ctnode);
visitRecur(cnode, ctnode);
} else {
visitRecur(cnode, tnode);
}
}
}
}
}
public void dfsNameOnly(DefaultMutableTreeNode tnode,ASTNode decl, String name) {
Stack<DefaultMutableTreeNode> temp = new Stack<DefaultMutableTreeNode>();
temp.push(codeTree);
while(!temp.isEmpty()){
DefaultMutableTreeNode cnode = temp.pop();
for (int i = 0; i < cnode.getChildCount(); i++) {
temp.push((DefaultMutableTreeNode) cnode.getChildAt(i));
}
if(!(cnode.getUserObject() instanceof ASTNodeWrapper))
continue;
ASTNodeWrapper awnode = (ASTNodeWrapper) cnode.getUserObject();
// log("Visiting: " + getNodeAsString(awnode.getNode()));
if(isInstanceOfType(awnode.getNode(), decl, name)){
int val[] = errorCheckerService
.JavaToPdeOffsets(awnode.getLineNumber(), 0);
tnode.add(new DefaultMutableTreeNode(new ASTNodeWrapper(awnode
.getNode(), "Line " + (val[1] + 1) + " | Tab: "
+ editor.getSketch().getCode(val[0]).getPrettyName())));
}
}
}
public ASTNode dfsLookForASTNode(ASTNode root, String name, int startOffset,
int endOffset) {
// log("dfsLookForASTNode() lookin for " + name + " Offsets: " + startOffset
// + "," + endOffset);
Stack<ASTNode> stack = new Stack<ASTNode>();
stack.push(root);
while (!stack.isEmpty()) {
ASTNode node = stack.pop();
//log("Popped from stack: " + getNodeAsString(node));
Iterator<StructuralPropertyDescriptor> it =
node.structuralPropertiesForType().iterator();
while (it.hasNext()) {
StructuralPropertyDescriptor prop = it.next();
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (node.getStructuralProperty(prop) instanceof ASTNode) {
ASTNode temp = (ASTNode) node.getStructuralProperty(prop);
if (temp.getStartPosition() <= startOffset
&& (temp.getStartPosition() + temp.getLength()) >= endOffset) {
if(temp instanceof SimpleName){
if(name.equals(temp.toString())){
// log("Found simplename: " + getNodeAsString(temp));
return temp;
}
// log("Bummer, didn't match");
}
else
stack.push(temp);
//log("Pushed onto stack: " + getNodeAsString(temp));
}
}
}
else if (prop.isChildListProperty()) {
List<ASTNode> nodelist =
(List<ASTNode>) node.getStructuralProperty(prop);
for (ASTNode temp : nodelist) {
if (temp.getStartPosition() <= startOffset
&& (temp.getStartPosition() + temp.getLength()) >= endOffset) {
stack.push(temp);
// log("Pushed onto stack: " + getNodeAsString(temp));
if(temp instanceof SimpleName){
if(name.equals(temp.toString())){
// log("Found simplename: " + getNodeAsString(temp));
return temp;
}
// log("Bummer, didn't match");
}
else
stack.push(temp);
//log("Pushed onto stack: " + getNodeAsString(temp));
}
}
}
}
}
// log("dfsLookForASTNode() not found " + name);
return null;
}
protected SketchOutline sketchOutline;
public void showSketchOutline() {
if (editor.hasJavaTabs()) return;
sketchOutline = new SketchOutline(codeTree, errorCheckerService);
sketchOutline.show();
}
public void showTabOutline() {
new TabOutline(errorCheckerService).show();
}
public int javaCodeOffsetToLineStartOffset(int line, int jOffset){
// Find the first node with this line number, return its offset - jOffset
line = pdeLineNumToJavaLineNum(line);
log("Looking for line: " + line + ", jOff " + jOffset);
Stack<DefaultMutableTreeNode> temp = new Stack<DefaultMutableTreeNode>();
temp.push(codeTree);
while (!temp.isEmpty()) {
DefaultMutableTreeNode cnode = temp.pop();
for (int i = 0; i < cnode.getChildCount(); i++) {
temp.push((DefaultMutableTreeNode) cnode.getChildAt(i));
}
if (!(cnode.getUserObject() instanceof ASTNodeWrapper))
continue;
ASTNodeWrapper awnode = (ASTNodeWrapper) cnode.getUserObject();
// log("Visiting: " + getNodeAsString(awnode.getNode()));
if (awnode.getLineNumber() == line) {
log("First element with this line no is: " + awnode
+ "LSO: " + (jOffset - awnode.getNode().getStartPosition()));
return (jOffset - awnode.getNode().getStartPosition());
}
}
return -1;
}
/**
* Converts pde line number to java line number
* @param pdeLineNum - pde line number
* @return
*/
protected int pdeLineNumToJavaLineNum(int pdeLineNum){
int javaLineNumber = pdeLineNum + errorCheckerService.getPdeImportsCount();
// Adjust line number for tabbed sketches
int codeIndex = editor.getSketch().getCodeIndex(editor.getCurrentTab());
if (codeIndex > 0)
for (int i = 0; i < codeIndex; i++) {
SketchCode sc = editor.getSketch().getCode(i);
int len = Base.countLines(sc.getProgram()) + 1;
javaLineNumber += len;
}
return javaLineNumber;
}
protected boolean isInstanceOfType(ASTNode node,ASTNode decl, String name){
if(node instanceof SimpleName){
SimpleName sn = (SimpleName) node;
if (sn.toString().equals(name)) {
ArrayList<ASTNode> nodesToBeMatched = new ArrayList<ASTNode>();
nodesToBeMatched.add(decl);
if(decl instanceof TypeDeclaration){
log("decl is a TD");
TypeDeclaration td = (TypeDeclaration)decl;
MethodDeclaration[] mlist = td.getMethods();
for (MethodDeclaration md : mlist) {
if(md.getName().toString().equals(name)){
nodesToBeMatched.add(md);
}
}
}
log("Visiting: " + getNodeAsString(node));
ASTNode decl2 = findDeclaration(sn);
Base.loge("It's decl: " + getNodeAsString(decl2));
log("But we need: "+getNodeAsString(decl));
for (ASTNode astNode : nodesToBeMatched) {
if(astNode.equals(decl2)){
return true;
}
}
}
}
return false;
}
public void handleRefactor() {
if (editor.hasJavaTabs()) return; // refactoring disabled w/ java tabs
log("Last clicked word:" + lastClickedWord);
if (lastClickedWord == null &&
getSelectedText() == null) {
editor.statusMessage("Highlight the class/function/variable name first",
JavaEditor.STATUS_INFO);
return;
}
if (errorCheckerService.hasSyntaxErrors()) {
editor.statusMessage("Can't perform action until syntax errors are fixed :(",
JavaEditor.STATUS_WARNING);
return;
}
DefaultMutableTreeNode defCU = findAllOccurrences();
String selText = lastClickedWord == null ?
getSelectedText() : lastClickedWord;
if (defCU == null) {
editor.statusMessage(selText + " isn't defined in this sketch, so it can't" +
" be renamed", JavaEditor.STATUS_ERR);
return;
}
if (!frmRename.isVisible()){
frmRename.setLocation(editor.getX()
+ (editor.getWidth() - frmRename.getWidth()) / 2,
editor.getY()
+ (editor.getHeight() - frmRename.getHeight())
/ 2);
frmRename.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String selText = lastClickedWord == null ? getSelectedText()
: lastClickedWord;
frmOccurenceList.setTitle("All occurrences of "
+ selText);
lblRefactorOldName.setText("Current name: "
+ selText);
txtRenameField.setText("");
txtRenameField.requestFocus();
}
});
}
frmRename.toFront();
}
public static void printRecur(ASTNode node) {
Iterator<StructuralPropertyDescriptor> it = node
.structuralPropertiesForType().iterator();
//Base.loge("Props of " + node.getClass().getName());
while (it.hasNext()) {
StructuralPropertyDescriptor prop = it.next();
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (node.getStructuralProperty(prop) != null) {
// System.out
// .println(node.getStructuralProperty(prop) + " -> " + (prop));
if (node.getStructuralProperty(prop) instanceof ASTNode) {
ASTNode cnode = (ASTNode) node.getStructuralProperty(prop);
log(getNodeAsString(cnode));
printRecur(cnode);
}
}
}
else if (prop.isChildListProperty()) {
List<ASTNode> nodelist = (List<ASTNode>) node
.getStructuralProperty(prop);
for (ASTNode cnode : nodelist) {
log(getNodeAsString(cnode));
printRecur(cnode);
}
}
}
}
protected static ASTNode findLineOfNode(ASTNode node, int lineNumber,
int offset, String name) {
CompilationUnit root = (CompilationUnit) node.getRoot();
// log("Inside "+getNodeAsString(node) + " | " + root.getLineNumber(node.getStartPosition()));
if (root.getLineNumber(node.getStartPosition()) == lineNumber) {
// Base.loge(3 + getNodeAsString(node) + " len " + node.getLength());
return node;
// if (offset < node.getLength())
// return node;
// else {
// Base.loge(-11);
// return null;
// }
}
for (Object oprop : node.structuralPropertiesForType()) {
StructuralPropertyDescriptor prop = (StructuralPropertyDescriptor) oprop;
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (node.getStructuralProperty(prop) != null) {
if (node.getStructuralProperty(prop) instanceof ASTNode) {
ASTNode retNode = findLineOfNode((ASTNode) node
.getStructuralProperty(prop),
lineNumber, offset, name);
if (retNode != null) {
// Base.loge(11 + getNodeAsString(retNode));
return retNode;
}
}
}
} else if (prop.isChildListProperty()) {
List<ASTNode> nodelist = (List<ASTNode>) node
.getStructuralProperty(prop);
for (ASTNode retNode : nodelist) {
ASTNode rr = findLineOfNode(retNode, lineNumber, offset, name);
if (rr != null) {
// Base.loge(12 + getNodeAsString(rr));
return rr;
}
}
}
}
// Base.loge("-1");
return null;
}
/**
*
* @param node
* @param offset
* - from textarea painter
* @param lineStartOffset
* - obtained from findLineOfNode
* @param name
* @param root
* @return
*/
public static ASTNode pinpointOnLine(ASTNode node, int offset,
int lineStartOffset, String name) {
//log("pinpointOnLine node class: " + node.getClass().getSimpleName());
if (node instanceof SimpleName) {
SimpleName sn = (SimpleName) node;
//log(offset+ "off,pol " + getNodeAsString(sn));
if ((lineStartOffset + offset) >= sn.getStartPosition()
&& (lineStartOffset + offset) <= sn.getStartPosition()
+ sn.getLength()) {
if (sn.toString().equals(name)) {
return sn;
}
else {
return null;
}
} else {
return null;
}
}
for (Object oprop : node.structuralPropertiesForType()) {
StructuralPropertyDescriptor prop = (StructuralPropertyDescriptor) oprop;
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (node.getStructuralProperty(prop) != null) {
if (node.getStructuralProperty(prop) instanceof ASTNode) {
ASTNode retNode = pinpointOnLine((ASTNode) node
.getStructuralProperty(prop),
offset, lineStartOffset, name);
if (retNode != null) {
// Base.loge(11 + getNodeAsString(retNode));
return retNode;
}
}
}
} else if (prop.isChildListProperty()) {
List<ASTNode> nodelist = (List<ASTNode>) node
.getStructuralProperty(prop);
for (ASTNode retNode : nodelist) {
ASTNode rr = pinpointOnLine(retNode, offset, lineStartOffset, name);
if (rr != null) {
// Base.loge(12 + getNodeAsString(rr));
return rr;
}
}
}
}
// Base.loge("-1");
return null;
}
/**
* Give this thing a {@link Name} instance - a {@link SimpleName} from the
* ASTNode for ex, and it tries its level best to locate its declaration in
* the AST. It really does.
*
* @param findMe
* @return
*/
protected static ASTNode findDeclaration(Name findMe) {
// WARNING: You're entering the Rube Goldberg territory of Experimental Mode.
// To debug this code, thou must take the Recursive Leap of Faith.
// log("entering --findDeclaration1 -- " + findMe.toString());
ASTNode declaringClass = null;
ASTNode parent = findMe.getParent();
ASTNode ret = null;
ArrayList<Integer> constrains = new ArrayList<Integer>();
if (parent.getNodeType() == ASTNode.METHOD_INVOCATION) {
Expression exp = (Expression) ((MethodInvocation) parent)
.getStructuralProperty(MethodInvocation.EXPRESSION_PROPERTY);
//TODO: Note the imbalance of constrains.add(ASTNode.METHOD_DECLARATION);
// Possibly a bug here. Investigate later.
if (((MethodInvocation) parent).getName().toString()
.equals(findMe.toString())) {
constrains.add(ASTNode.METHOD_DECLARATION);
if (exp != null) {
constrains.add(ASTNode.TYPE_DECLARATION);
// log("MI EXP: " + exp.toString() + " of type "
// + exp.getClass().getName() + " parent: " + exp.getParent());
if (exp instanceof MethodInvocation) {
SimpleType stp = extracTypeInfo(findDeclaration(((MethodInvocation) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains, declaringClass);
} else if (exp instanceof FieldAccess) {
SimpleType stp = extracTypeInfo(findDeclaration(((FieldAccess) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration((stp.getName()));
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains, declaringClass);
}
if (exp instanceof SimpleName) {
SimpleType stp = extracTypeInfo(findDeclaration(((SimpleName) exp)));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
// log("MI.SN " + getNodeAsString(declaringClass));
constrains.add(ASTNode.METHOD_DECLARATION);
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains, declaringClass);
}
}
} else {
parent = parent.getParent(); // Move one up the ast. V V IMP!!
}
} else if (parent.getNodeType() == ASTNode.FIELD_ACCESS) {
FieldAccess fa = (FieldAccess) parent;
Expression exp = fa.getExpression();
if (fa.getName().toString().equals(findMe.toString())) {
constrains.add(ASTNode.FIELD_DECLARATION);
if (exp != null) {
constrains.add(ASTNode.TYPE_DECLARATION);
// log("FA EXP: " + exp.toString() + " of type "
// + exp.getClass().getName() + " parent: " + exp.getParent());
if (exp instanceof MethodInvocation) {
SimpleType stp = extracTypeInfo(findDeclaration(((MethodInvocation) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
return definedIn(declaringClass, fa.getName().toString(),
constrains, declaringClass);
} else if (exp instanceof FieldAccess) {
SimpleType stp = extracTypeInfo(findDeclaration(((FieldAccess) exp)
.getName()));
if (stp == null)
return null;
declaringClass = findDeclaration((stp.getName()));
constrains.add(ASTNode.TYPE_DECLARATION);
return definedIn(declaringClass, fa.getName().toString(),
constrains, declaringClass);
}
if (exp instanceof SimpleName) {
SimpleType stp = extracTypeInfo(findDeclaration(((SimpleName) exp)));
if (stp == null)
return null;
declaringClass = findDeclaration(stp.getName());
// log("FA.SN " + getNodeAsString(declaringClass));
constrains.add(ASTNode.METHOD_DECLARATION);
return definedIn(declaringClass, fa.getName().toString(),
constrains, declaringClass);
}
}
} else {
parent = parent.getParent(); // Move one up the ast. V V IMP!!
}
} else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME) {
QualifiedName qn = (QualifiedName) parent;
if (!findMe.toString().equals(qn.getQualifier().toString())) {
SimpleType stp = extracTypeInfo(findDeclaration((qn.getQualifier())));
// log(qn.getQualifier() + "->" + qn.getName());
declaringClass = findDeclaration(stp.getName());
// log("QN decl class: " + getNodeAsString(declaringClass));
constrains.clear();
constrains.add(ASTNode.TYPE_DECLARATION);
constrains.add(ASTNode.FIELD_DECLARATION);
return definedIn(declaringClass, qn.getName().toString(), constrains,
null);
}
else{
if(findMe instanceof QualifiedName){
QualifiedName qnn = (QualifiedName) findMe;
// log("findMe is a QN, "
// + (qnn.getQualifier().toString() + " other " + qnn.getName()
// .toString()));
SimpleType stp = extracTypeInfo(findDeclaration((qnn.getQualifier())));
// log(qnn.getQualifier() + "->" + qnn.getName());
declaringClass = findDeclaration(stp.getName());
// log("QN decl class: "
// + getNodeAsString(declaringClass));
constrains.clear();
constrains.add(ASTNode.TYPE_DECLARATION);
constrains.add(ASTNode.FIELD_DECLARATION);
return definedIn(declaringClass, qnn.getName().toString(), constrains,
null);
}
}
} else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE) {
constrains.add(ASTNode.TYPE_DECLARATION);
if (parent.getParent().getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
constrains.add(ASTNode.CLASS_INSTANCE_CREATION);
} else if(parent.getNodeType() == ASTNode.TYPE_DECLARATION){
// The condition where we look up the name of a class decl
TypeDeclaration td = (TypeDeclaration) parent;
if(findMe.equals(td.getName()))
{
return parent;
}
}
else if (parent instanceof Expression) {
// constrains.add(ASTNode.TYPE_DECLARATION);
// constrains.add(ASTNode.METHOD_DECLARATION);
// constrains.add(ASTNode.FIELD_DECLARATION);
}
// else if(findMe instanceof QualifiedName){
// QualifiedName qn = (QualifiedName) findMe;
// System.out
// .println("findMe is a QN, "
// + (qn.getQualifier().toString() + " other " + qn.getName()
// .toString()));
// }
while (parent != null) {
// log("findDeclaration1 -> " + getNodeAsString(parent));
for (Object oprop : parent.structuralPropertiesForType()) {
StructuralPropertyDescriptor prop = (StructuralPropertyDescriptor) oprop;
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (parent.getStructuralProperty(prop) instanceof ASTNode) {
// log(prop + " C/S Prop of -> "
// + getNodeAsString(parent));
ret = definedIn((ASTNode) parent.getStructuralProperty(prop),
findMe.toString(), constrains, declaringClass);
if (ret != null)
return ret;
}
} else if (prop.isChildListProperty()) {
// log((prop) + " ChildList props of "
// + getNodeAsString(parent));
List<ASTNode> nodelist = (List<ASTNode>) parent
.getStructuralProperty(prop);
for (ASTNode retNode : nodelist) {
ret = definedIn(retNode, findMe.toString(), constrains,
declaringClass);
if (ret != null)
return ret;
}
}
}
parent = parent.getParent();
}
return null;
}
/**
* A variation of findDeclaration() but accepts an alternate parent ASTNode
* @param findMe
* @param alternateParent
* @return
*/
protected static ASTNode findDeclaration2(Name findMe, ASTNode alternateParent) {
ASTNode declaringClass = null;
ASTNode parent = findMe.getParent();
ASTNode ret = null;
ArrayList<Integer> constrains = new ArrayList<Integer>();
if (parent.getNodeType() == ASTNode.METHOD_INVOCATION) {
Expression exp = (Expression) ((MethodInvocation) parent)
.getStructuralProperty(MethodInvocation.EXPRESSION_PROPERTY);
//TODO: Note the imbalance of constrains.add(ASTNode.METHOD_DECLARATION);
// Possibly a bug here. Investigate later.
if (((MethodInvocation) parent).getName().toString()
.equals(findMe.toString())) {
constrains.add(ASTNode.METHOD_DECLARATION);
if (exp != null) {
constrains.add(ASTNode.TYPE_DECLARATION);
// log("MI EXP: " + exp.toString() + " of type "
// + exp.getClass().getName() + " parent: " + exp.getParent());
if (exp instanceof MethodInvocation) {
SimpleType stp = extracTypeInfo(findDeclaration2(((MethodInvocation) exp)
.getName(),
alternateParent));
if (stp == null)
return null;
declaringClass = findDeclaration2(stp.getName(), alternateParent);
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains, declaringClass);
} else if (exp instanceof FieldAccess) {
SimpleType stp = extracTypeInfo(findDeclaration2(((FieldAccess) exp)
.getName(),
alternateParent));
if (stp == null)
return null;
declaringClass = findDeclaration2((stp.getName()), alternateParent);
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains, declaringClass);
}
if (exp instanceof SimpleName) {
SimpleType stp = extracTypeInfo(findDeclaration2(((SimpleName) exp),
alternateParent));
if (stp == null)
return null;
declaringClass = findDeclaration2(stp.getName(), alternateParent);
// log("MI.SN " + getNodeAsString(declaringClass));
constrains.add(ASTNode.METHOD_DECLARATION);
return definedIn(declaringClass, ((MethodInvocation) parent)
.getName().toString(), constrains, declaringClass);
}
}
} else {
parent = parent.getParent(); // Move one up the ast. V V IMP!!
alternateParent = alternateParent.getParent();
}
} else if (parent.getNodeType() == ASTNode.FIELD_ACCESS) {
FieldAccess fa = (FieldAccess) parent;
Expression exp = fa.getExpression();
if (fa.getName().toString().equals(findMe.toString())) {
constrains.add(ASTNode.FIELD_DECLARATION);
if (exp != null) {
constrains.add(ASTNode.TYPE_DECLARATION);
// log("FA EXP: " + exp.toString() + " of type "
// + exp.getClass().getName() + " parent: " + exp.getParent());
if (exp instanceof MethodInvocation) {
SimpleType stp = extracTypeInfo(findDeclaration2(((MethodInvocation) exp)
.getName(),
alternateParent));
if (stp == null)
return null;
declaringClass = findDeclaration2(stp.getName(), alternateParent);
return definedIn(declaringClass, fa.getName().toString(),
constrains, declaringClass);
} else if (exp instanceof FieldAccess) {
SimpleType stp = extracTypeInfo(findDeclaration2(((FieldAccess) exp)
.getName(),
alternateParent));
if (stp == null)
return null;
declaringClass = findDeclaration2((stp.getName()), alternateParent);
constrains.add(ASTNode.TYPE_DECLARATION);
return definedIn(declaringClass, fa.getName().toString(),
constrains, declaringClass);
}
if (exp instanceof SimpleName) {
SimpleType stp = extracTypeInfo(findDeclaration2(((SimpleName) exp),
alternateParent));
if (stp == null)
return null;
declaringClass = findDeclaration2(stp.getName(), alternateParent);
// log("FA.SN " + getNodeAsString(declaringClass));
constrains.add(ASTNode.METHOD_DECLARATION);
return definedIn(declaringClass, fa.getName().toString(),
constrains, declaringClass);
}
}
} else {
parent = parent.getParent(); // Move one up the ast. V V IMP!!
alternateParent = alternateParent.getParent();
}
} else if (parent.getNodeType() == ASTNode.QUALIFIED_NAME) {
QualifiedName qn = (QualifiedName) parent;
if (!findMe.toString().equals(qn.getQualifier().toString())) {
SimpleType stp = extracTypeInfo(findDeclaration2((qn.getQualifier()),
alternateParent));
if(stp == null)
return null;
declaringClass = findDeclaration2(stp.getName(), alternateParent);
// log(qn.getQualifier() + "->" + qn.getName());
// log("QN decl class: " + getNodeAsString(declaringClass));
constrains.clear();
constrains.add(ASTNode.TYPE_DECLARATION);
constrains.add(ASTNode.FIELD_DECLARATION);
return definedIn(declaringClass, qn.getName().toString(), constrains,
null);
}
else{
if(findMe instanceof QualifiedName){
QualifiedName qnn = (QualifiedName) findMe;
// log("findMe is a QN, "
// + (qnn.getQualifier().toString() + " other " + qnn.getName()
// .toString()));
SimpleType stp = extracTypeInfo(findDeclaration2((qnn.getQualifier()), alternateParent));
// log(qnn.getQualifier() + "->" + qnn.getName());
declaringClass = findDeclaration2(stp.getName(), alternateParent);
// log("QN decl class: "
// + getNodeAsString(declaringClass));
constrains.clear();
constrains.add(ASTNode.TYPE_DECLARATION);
constrains.add(ASTNode.FIELD_DECLARATION);
return definedIn(declaringClass, qnn.getName().toString(), constrains,
null);
}
}
} else if (parent.getNodeType() == ASTNode.SIMPLE_TYPE) {
constrains.add(ASTNode.TYPE_DECLARATION);
if (parent.getParent().getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
constrains.add(ASTNode.CLASS_INSTANCE_CREATION);
} else if (parent instanceof Expression) {
// constrains.add(ASTNode.TYPE_DECLARATION);
// constrains.add(ASTNode.METHOD_DECLARATION);
// constrains.add(ASTNode.FIELD_DECLARATION);
} // TODO: in findDec, we also have a case where parent of type TD is handled.
// Figure out if needed here as well.
// log("Alternate parent: " + getNodeAsString(alternateParent));
while (alternateParent != null) {
// log("findDeclaration2 -> "
// + getNodeAsString(alternateParent));
for (Object oprop : alternateParent.structuralPropertiesForType()) {
StructuralPropertyDescriptor prop = (StructuralPropertyDescriptor) oprop;
if (prop.isChildProperty() || prop.isSimpleProperty()) {
if (alternateParent.getStructuralProperty(prop) instanceof ASTNode) {
// log(prop + " C/S Prop of -> "
// + getNodeAsString(alternateParent));
ret = definedIn((ASTNode) alternateParent
.getStructuralProperty(prop),
findMe.toString(), constrains, declaringClass);
if (ret != null)
return ret;
}
} else if (prop.isChildListProperty()) {
// log((prop) + " ChildList props of "
// + getNodeAsString(alternateParent));
List<ASTNode> nodelist = (List<ASTNode>) alternateParent
.getStructuralProperty(prop);
for (ASTNode retNode : nodelist) {
ret = definedIn(retNode, findMe.toString(), constrains,
declaringClass);
if (ret != null)
return ret;
}
}
}
alternateParent = alternateParent.getParent();
}
return null;
}
protected List<Comment> getCodeComments(){
List<Comment> commentList = compilationUnit.getCommentList();
// log("Total comments: " + commentList.size());
// int i = 0;
// for (Comment comment : commentList) {
// log(++i + ": "+comment + " Line:"
// + compilationUnit.getLineNumber(comment.getStartPosition()) + ", "
// + comment.getLength());
// }
return commentList;
}
protected boolean caretWithinLineComment() {
final JEditTextArea ta = editor.getTextArea();
String pdeLine = editor.getLineText(ta.getCaretLine()).trim();
int caretPos = ta.getCaretPosition() - ta.getLineStartNonWhiteSpaceOffset(ta.getCaretLine());
int x = pdeLine.indexOf("//");
if (x >= 0 && caretPos > x) {
return true;
}
return false;
}
/**
* A wrapper for java.lang.reflect types.
* Will have to see if the usage turns out to be internal only here or not
* and then accordingly decide where to place this class.
* @author quarkninja
*
*/
public class ClassMember {
private Field field;
private Method method;
private Constructor<?> cons;
private Class<?> thisclass;
private String stringVal;
private String classType;
private ASTNode astNode;
private ASTNode declaringNode;
public ClassMember(Class<?> m) {
thisclass = m;
stringVal = "Predefined Class " + m.getName();
classType = m.getName();
}
public ClassMember(Method m) {
method = m;
stringVal = "Method " + m.getReturnType().getName() + " | " + m.getName()
+ " defined in " + m.getDeclaringClass().getName();
classType = m.getReturnType().getName();
}
public ClassMember(Field m) {
field = m;
stringVal = "Field " + m.getType().getName() + " | " + m.getName()
+ " defined in " + m.getDeclaringClass().getName();
classType = m.getType().getName();
}
public ClassMember(Constructor<?> m) {
cons = m;
stringVal = "Cons " + " " + m.getName() + " defined in "
+ m.getDeclaringClass().getName();
}
public ClassMember(ASTNode node){
astNode = node;
stringVal = getNodeAsString(node);
if(node instanceof TypeDeclaration){
declaringNode = node;
}
if(node instanceof SimpleType){
classType = ((SimpleType)node).getName().toString();
}
SimpleType stp = (node instanceof SimpleType) ? (SimpleType) node
: extracTypeInfo(node);
if(stp != null){
ASTNode decl =findDeclaration(stp.getName());
// Czech out teh mutation
if(decl == null){
// a predefined type
classType = stp.getName().toString();
Class<?> probableClass = findClassIfExists(classType);
thisclass = probableClass;
}
else{
// a local type
declaringNode = decl;
}
}
}
public Class<?> getClass_() {
return thisclass;
}
public ASTNode getDeclaringNode(){
return declaringNode;
}
public Field getField() {
return field;
}
public Method getMethod() {
return method;
}
public Constructor<?> getCons() {
return cons;
}
public ASTNode getASTNode(){
return astNode;
}
public String toString() {
return stringVal;
}
public String getTypeAsString(){
return classType;
}
}
/**
* Find the SimpleType from FD, SVD, VDS, etc
*
* @param node
* @return
*/
public static SimpleType extracTypeInfo(ASTNode node) {
if (node == null) {
return null;
}
Type t = extracTypeInfo2(node);
if (t instanceof PrimitiveType) {
return null;
} else if (t instanceof ArrayType) {
ArrayType at = (ArrayType) t;
log(at.getComponentType() + " <-comp type, ele type-> "
+ at.getElementType() + ", "
+ at.getElementType().getClass().getName());
if (at.getElementType() instanceof PrimitiveType) {
return null;
} else if (at.getElementType() instanceof SimpleType) {
return (SimpleType) at.getElementType();
} else
return null;
} else if (t instanceof ParameterizedType) {
ParameterizedType pmt = (ParameterizedType) t;
log(pmt.getType() + ", " + pmt.getType().getClass());
if (pmt.getType() instanceof SimpleType) {
return (SimpleType) pmt.getType();
} else
return null;
}
return (SimpleType) t;
}
static public Type extracTypeInfo2(ASTNode node) {
if (node == null)
return null;
switch (node.getNodeType()) {
case ASTNode.METHOD_DECLARATION:
return ((MethodDeclaration) node).getReturnType2();
case ASTNode.FIELD_DECLARATION:
return ((FieldDeclaration) node).getType();
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
return ((VariableDeclarationExpression) node).getType();
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
return ((VariableDeclarationStatement) node).getType();
case ASTNode.SINGLE_VARIABLE_DECLARATION:
return ((SingleVariableDeclaration) node).getType();
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
return extracTypeInfo2(node.getParent());
}
log("Unknown type info request " + getNodeAsString(node));
return null;
}
static protected ASTNode definedIn(ASTNode node, String name,
ArrayList<Integer> constrains,
ASTNode declaringClass) {
if (node == null)
return null;
if (constrains != null) {
// log("Looking at " + getNodeAsString(node) + " for " + name
// + " in definedIn");
if (!constrains.contains(node.getNodeType()) && constrains.size() > 0) {
// System.err.print("definedIn -1 " + " But constrain was ");
// for (Integer integer : constrains) {
// System.out.print(ASTNode.nodeClassForType(integer) + ",");
// }
// log();
return null;
}
}
List<VariableDeclarationFragment> vdfList = null;
switch (node.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
//Base.loge(getNodeAsString(node));
TypeDeclaration td = (TypeDeclaration) node;
if (td.getName().toString().equals(name)) {
if (constrains.contains(ASTNode.CLASS_INSTANCE_CREATION)) {
// look for constructor;
MethodDeclaration[] methods = td.getMethods();
for (MethodDeclaration md : methods) {
if (md.getName().toString().equalsIgnoreCase(name)) {
log("Found a constructor.");
return md;
}
}
} else {
// it's just the TD we're lookin for
return node;
}
} else {
if (constrains.contains(ASTNode.FIELD_DECLARATION)) {
// look for fields
FieldDeclaration[] fields = td.getFields();
for (FieldDeclaration fd : fields) {
List<VariableDeclarationFragment> fragments = fd.fragments();
for (VariableDeclarationFragment vdf : fragments) {
if (vdf.getName().toString().equalsIgnoreCase(name))
return fd;
}
}
} else if (constrains.contains(ASTNode.METHOD_DECLARATION)) {
// look for methods
MethodDeclaration[] methods = td.getMethods();
for (MethodDeclaration md : methods) {
if (md.getName().toString().equalsIgnoreCase(name)) {
return md;
}
}
}
}
break;
case ASTNode.METHOD_DECLARATION:
//Base.loge(getNodeAsString(node));
if (((MethodDeclaration) node).getName().toString().equalsIgnoreCase(name))
return node;
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
//Base.loge(getNodeAsString(node));
if (((SingleVariableDeclaration) node).getName().toString().equalsIgnoreCase(name))
return node;
break;
case ASTNode.FIELD_DECLARATION:
//Base.loge("FD" + node);
vdfList = ((FieldDeclaration) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
//Base.loge("VDE" + node);
vdfList = ((VariableDeclarationExpression) node).fragments();
break;
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
//Base.loge("VDS" + node);
vdfList = ((VariableDeclarationStatement) node).fragments();
break;
default:
}
if (vdfList != null) {
for (VariableDeclarationFragment vdf : vdfList) {
if (vdf.getName().toString().equalsIgnoreCase(name))
return node;
}
}
return null;
}
public String[] getSuggestImports(final String className){
if(ignoredImportSuggestions == null) {
ignoredImportSuggestions = new TreeSet<String>();
} else {
if(ignoredImportSuggestions.contains(className)) {
log("Ignoring import suggestions for " + className);
return null;
}
}
log("Looking for class " + className);
RegExpResourceFilter regf = new RegExpResourceFilter(
Pattern.compile(".*"),
Pattern
.compile(className
+ ".class",
Pattern.CASE_INSENSITIVE));
String[] resources = classPath
.findResources("", regf);
ArrayList<String> candidates = new ArrayList<String>();
for (String res : resources) {
candidates.add(res);
}
// log("Couldn't find import for class " + className);
for (Library lib : editor.getMode().contribLibraries) {
ClassPath cp = factory.createFromPath(lib.getClassPath());
resources = cp.findResources("", regf);
for (String res : resources) {
candidates.add(res);
log("Res: " + res);
}
}
if (editor.getSketch().hasCodeFolder()) {
File codeFolder = editor.getSketch().getCodeFolder();
// get a list of .jar files in the "code" folder
// (class files in subfolders should also be picked up)
ClassPath cp = factory.createFromPath(Base
.contentsToClassPath(codeFolder));
resources = cp.findResources("", regf);
for (String res : resources) {
candidates.add(res);
log("Res: " + res);
}
}
resources = new String[candidates.size()];
for (int i = 0; i < resources.length; i++) {
resources[i] = candidates.get(i).replace('/', '.')
.substring(0, candidates.get(i).length() - 6);
}
// ArrayList<String> ans = new ArrayList<String>();
// for (int i = 0; i < resources.length; i++) {
// ans.add(resources[i]);
// }
return resources;
}
protected JFrame frmImportSuggest;
private TreeSet<String> ignoredImportSuggestions;
public void suggestImports(final String className){
if(ignoredImportSuggestions == null) {
ignoredImportSuggestions = new TreeSet<String>();
} else {
if(ignoredImportSuggestions.contains(className)) {
log("Ignoring import suggestions for " + className);
return;
}
}
if(frmImportSuggest != null)
if(frmImportSuggest.isVisible())
return;
log("Looking for class " + className);
RegExpResourceFilter regf = new RegExpResourceFilter(
Pattern.compile(".*"),
Pattern
.compile(className
+ ".class",
Pattern.CASE_INSENSITIVE));
String[] resources = classPath
.findResources("", regf);
ArrayList<String> candidates = new ArrayList<String>();
for (String res : resources) {
candidates.add(res);
}
// log("Couldn't find import for class " + className);
for (Library lib : editor.getMode().contribLibraries) {
ClassPath cp = factory.createFromPath(lib.getClassPath());
resources = cp.findResources("", regf);
for (String res : resources) {
candidates.add(res);
log("Res: " + res);
}
}
if (editor.getSketch().hasCodeFolder()) {
File codeFolder = editor.getSketch().getCodeFolder();
// get a list of .jar files in the "code" folder
// (class files in subfolders should also be picked up)
ClassPath cp = factory.createFromPath(Base
.contentsToClassPath(codeFolder));
resources = cp.findResources("", regf);
for (String res : resources) {
candidates.add(res);
log("Res: " + res);
}
}
resources = new String[candidates.size()];
for (int i = 0; i < resources.length; i++) {
resources[i] = candidates.get(i).replace('/', '.')
.substring(0, candidates.get(i).length() - 6);
}
if (resources.length >= 1) {
final JList<String> classList = new JList<String>(resources);
classList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
frmImportSuggest = new JFrame();
frmImportSuggest.setSize(350, 200);
Toolkit.setIcon(frmImportSuggest);
frmImportSuggest.setLayout(new BoxLayout(frmImportSuggest
.getContentPane(), BoxLayout.Y_AXIS));
((JComponent) frmImportSuggest.getContentPane()).setBorder(BorderFactory
.createEmptyBorder(5, 5, 5, 5));
JLabel lbl = new JLabel("<html>The class \"" + className
+ "\" couldn't be determined. You are probably missing one of the following imports:</html>");
JScrollPane jsp = new JScrollPane();
jsp.setViewportView(classList);
JButton btnInsertImport = new JButton("Insert import");
btnInsertImport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (classList.getSelectedValue() != null) {
try {
String impString = "import " + classList.getSelectedValue()
+ ";\n";
int ct = editor.getSketch().getCurrentCodeIndex();
editor.getSketch().setCurrentCode(0);
editor.getTextArea().getDocument().insertString(0, impString, null);
editor.getSketch().setCurrentCode(ct);
errorCheckerService.runManualErrorCheck();
frmImportSuggest.setVisible(false);
frmImportSuggest = null;
} catch (BadLocationException e) {
log("Failed to insert import for " + className);
e.printStackTrace();
}
}
}
});
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmImportSuggest.setVisible(false);
}
});
JPanel panelTop = new JPanel(), panelBottom = new JPanel(), panelLabel = new JPanel();
panelTop.setLayout(new BoxLayout(panelTop, BoxLayout.Y_AXIS));
panelTop.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelLabel.setLayout(new BorderLayout());
panelLabel.add(lbl,BorderLayout.CENTER);
panelTop.add(panelLabel);
panelTop.add(Box.createRigidArea(new Dimension(1, 5)));
panelTop.add(jsp);
panelBottom.setLayout(new BoxLayout(panelBottom, BoxLayout.X_AXIS));
panelBottom.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelBottom .setLayout(new BoxLayout(panelBottom, BoxLayout.X_AXIS));
panelBottom.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panelBottom.add(Box.createHorizontalGlue());
panelBottom.add(btnInsertImport);
panelBottom.add(Box.createRigidArea(new Dimension(15, 0)));
panelBottom.add(btnCancel);
JButton btnIgnore = new JButton("Ignore \"" + className + "\"");
btnIgnore.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ignoredImportSuggestions.add(className);
frmImportSuggest.setVisible(false);
}
});
panelBottom.add(Box.createRigidArea(new Dimension(15, 0)));
panelBottom.add(btnIgnore);
// frmImportSuggest.add(lbl);
// frmImportSuggest.add(jsp);
// frmImportSuggest.add(btnInsertImport);
frmImportSuggest.add(panelTop);
frmImportSuggest.add(panelBottom);
frmImportSuggest.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmImportSuggest.setTitle("Import Suggestion");
frmImportSuggest.setLocation(editor.getX()
+ (editor.getWidth() - frmImportSuggest.getWidth()) / 2,
editor.getY()
+ (editor.getHeight() - frmImportSuggest.getHeight())
/ 2);
hideSuggestion();
classList.setSelectedIndex(0);
frmImportSuggest.setVisible(true);
}
}
public void disposeAllWindows() {
disposeWindow(frmASTView, frameAutoComp, frmImportSuggest,
frmOccurenceList, frmRename);
}
public static void disposeWindow(JFrame... f) {
for (JFrame jFrame : f) {
if(jFrame != null)
jFrame.dispose();
}
}
public static final String ignoredImports[] = {
"com.oracle.", "sun.", "sunw.", "com.sun.", "javax.", "sunw.", "org.ietf.",
"org.jcp.", "org.omg.", "org.w3c.", "org.xml.", "org.eclipse.", "com.ibm.",
"org.netbeans.", "org.jsoup.", "org.junit.", "org.apache.", "antlr." };
public static final String allowedImports[] = {"java.lang.", "java.util.", "java.io.",
"java.math.", "processing.core.", "processing.data.", "processing.event.", "processing.opengl."};
protected boolean ignorableImport(String impName, String className) {
//TODO: Trie man.
for (ImportStatement impS : errorCheckerService.getProgramImports()) {
if(impName.startsWith(impS.getPackageName()))
return false;
}
for (String impS : allowedImports) {
if(impName.startsWith(impS) && className.indexOf('.') == -1)
return false;
}
return true;
}
public static boolean isAddableASTNode(ASTNode node) {
switch (node.getNodeType()) {
// case ASTNode.STRING_LITERAL:
// case ASTNode.NUMBER_LITERAL:
// case ASTNode.BOOLEAN_LITERAL:
// case ASTNode.NULL_LITERAL:
// return false;
default:
return true;
}
}
/**
* For any line or expression, finds the line start offset(java code).
* @param node
* @return
*/
public int getASTNodeLineStartOffset(ASTNode node){
int nodeLineNo = getLineNumber(node);
while(node.getParent() != null){
if (getLineNumber(node.getParent()) == nodeLineNo) {
node = node.getParent();
} else {
break;
}
}
return node.getStartPosition();
}
/**
* For any node, finds various offsets (java code).
*
* @param node
* @return int[]{line number, line number start offset, node start offset,
* node length}
*/
public int[] getASTNodeAllOffsets(ASTNode node){
int nodeLineNo = getLineNumber(node), nodeOffset = node.getStartPosition(), nodeLength = node
.getLength();
while(node.getParent() != null){
if (getLineNumber(node.getParent()) == nodeLineNo) {
node = node.getParent();
} else {
break;
}
}
return new int[]{nodeLineNo, node.getStartPosition(), nodeOffset,nodeLength};
}
static protected String getNodeAsString(ASTNode node) {
if (node == null)
return "NULL";
String className = node.getClass().getName();
int index = className.lastIndexOf(".");
if (index > 0)
className = className.substring(index + 1);
// if(node instanceof BodyDeclaration)
// return className;
String value = className;
if (node instanceof TypeDeclaration)
value = ((TypeDeclaration) node).getName().toString() + " | " + className;
else if (node instanceof MethodDeclaration)
value = ((MethodDeclaration) node).getName().toString() + " | "
+ className;
else if (node instanceof MethodInvocation)
value = ((MethodInvocation) node).getName().toString() + " | "
+ className;
else if (node instanceof FieldDeclaration)
value = ((FieldDeclaration) node).toString() + " FldDecl| ";
else if (node instanceof SingleVariableDeclaration)
value = ((SingleVariableDeclaration) node).getName() + " - "
+ ((SingleVariableDeclaration) node).getType() + " | SVD ";
else if (node instanceof ExpressionStatement)
value = node.toString() + className;
else if (node instanceof SimpleName)
value = ((SimpleName) node).getFullyQualifiedName() + " | " + className;
else if (node instanceof QualifiedName)
value = node.toString() + " | " + className;
else if(node instanceof FieldAccess)
value = node.toString() + " | ";
else if (className.startsWith("Variable"))
value = node.toString() + " | " + className;
else if (className.endsWith("Type"))
value = node.toString() + " |" + className;
value += " [" + node.getStartPosition() + ","
+ (node.getStartPosition() + node.getLength()) + "]";
value += " Line: "
+ ((CompilationUnit) node.getRoot()).getLineNumber(node
.getStartPosition());
return value;
}
/**
* CompletionPanel name
*
* @param node
* @return
*/
static protected String getNodeAsString2(ASTNode node) {
if (node == null)
return "NULL";
String className = node.getClass().getName();
int index = className.lastIndexOf(".");
if (index > 0)
className = className.substring(index + 1);
// if(node instanceof BodyDeclaration)
// return className;
String value = className;
if (node instanceof TypeDeclaration)
value = ((TypeDeclaration) node).getName().toString();
else if (node instanceof MethodDeclaration)
value = ((MethodDeclaration) node).getName().toString();
else if (node instanceof MethodInvocation)
value = ((MethodInvocation) node).getName().toString() + " | "
+ className;
else if (node instanceof FieldDeclaration)
value = ((FieldDeclaration) node).toString();
else if (node instanceof SingleVariableDeclaration)
value = ((SingleVariableDeclaration) node).getName().toString();
else if (node instanceof ExpressionStatement)
value = node.toString() + className;
else if (node instanceof SimpleName)
value = ((SimpleName) node).getFullyQualifiedName() + " | " + className;
else if (node instanceof QualifiedName)
value = node.toString();
else if (node instanceof VariableDeclarationFragment)
value = ((VariableDeclarationFragment) node).getName().toString();
else if (className.startsWith("Variable"))
value = node.toString();
else if (node instanceof VariableDeclarationStatement)
value = ((VariableDeclarationStatement) node).toString();
else if (className.endsWith("Type"))
value = node.toString();
// value += " [" + node.getStartPosition() + ","
// + (node.getStartPosition() + node.getLength()) + "]";
// value += " Line: "
// + ((CompilationUnit) node.getRoot()).getLineNumber(node
// .getStartPosition());
return value;
}
public void jdocWindowVisible(boolean visible) {
// frmJavaDoc.setVisible(visible);
}
public static String readFile(String path) {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(
new File(
path))));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
StringBuilder ret = new StringBuilder();
// ret.append("package " + className + ";\n");
String line;
while ((line = reader.readLine()) != null) {
ret.append(line);
ret.append("\n");
}
return ret.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
static private void log(Object object) {
Base.log(object == null ? "null" : object.toString());
}
private String getSelectedText() {
return editor.getTextArea().getSelectedText();
}
private void hideSuggestion() {
((JavaTextArea) editor.getTextArea()).hideSuggestion();
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
a7d0b81a4f52f70906bb4429421dc356d1af89ea | 16c286845f9a0cb829e69299737753f19b73e0cb | /nueva iteracion/ppp/business/api/src/main/java/com/abs/siif/programming/management/DepToObjLinkManagement.java | 5dd79235181a007f7943999c03a263bba7db310b | [] | no_license | erickone/ABSnewRepository | f06ab47970dac7c1553765c5b8de51b024b24c62 | cf3edf1ac6d0d646e2666c553f426dc682f5a0ed | refs/heads/master | 2020-05-17T20:06:31.193230 | 2012-09-20T15:25:13 | 2012-09-20T15:25:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,985 | java | /*
* Copyright (C) 2012 Advanced Business Systems S.A. de C.V.
* All rights reserved
* Filename: DepToObjLinkManagement
* Purpose: Interface to serve the Link between Dependencies and
* Objectives.
*
* The copyright to the computer program(s) herein is the property
* of Advanced Business Systems S.A. de C.V. The programs may be
* used and/or copied only with written permission from Advanced
* Business Systems S.A. de C.V. or in accordance with the terms
* and conditions stipulated in the agreement/contract under which
* the program(s) have been supplied.
*/
package com.abs.siif.programming.management;
import com.abs.siif.planning.dto.DepencenceDto;
import com.abs.siif.planning.entities.DependenceEntity;
import com.abs.siif.planning.entities.ObjectiveEntity;
import java.util.List;
/**
*
* @author FENIX-02
*/
public interface DepToObjLinkManagement {
/**
* Salva los datos del encuadre
* @param aDependenceEntity
* @return
*/
public boolean saveGeneralDataInvPreFile(DependenceEntity aDependenceEntity);
/**
* Obtiene la lista de los padres del nivel que se va a encuadrar.
* @param aNivelDependencia
* @return List<DependenceEntity>
*/
public List<DepencenceDto> getFathersList();
/**
* Obtiene una lista de dependencias basadas en el id del padre.
* @return List
*/
public List<DependenceEntity> getChildsList(Long idFather);
/**
* Este metodo se trae las dependencias relacionadas con algun objetivo.
* @param idObjective
* @return
*/
public List<DependenceEntity> getChildsRelatedObj(Long idDepFather, Long idObjective);
/**
* Este medoto guarda un Objetivo y en cascada las dependencias en la tabla
* de encuadre.
* @param dependencies
* @return
*/
public boolean saveObjectiveWithDependencies(ObjectiveEntity anObjectiveEntity, Long idpadre);
}
| [
"erickleija@hotmaill.com"
] | erickleija@hotmaill.com |
7081ed56fc9c3aa590ff5c708e86818e24d735e2 | 13ea5da0b7b8d4ba87d622a5f733dcf6b4c5f1e3 | /crash-reproduction-new-fitness/results/TIME-7b-4-5-Single_Objective_GGA-IntegrationSingleObjective-/org/joda/time/format/DateTimeParserBucket_ESTest.java | 5b9384ea02d6813bec994988106833e5f7953873 | [
"MIT",
"CC-BY-4.0"
] | permissive | STAMP-project/Botsing-basic-block-coverage-application | 6c1095c6be945adc0be2b63bbec44f0014972793 | 80ea9e7a740bf4b1f9d2d06fe3dcc72323b848da | refs/heads/master | 2022-07-28T23:05:55.253779 | 2022-04-20T13:54:11 | 2022-04-20T13:54:11 | 285,771,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,883 | java | /*
* This file was automatically generated by EvoSuite
* Sun May 17 13:20:20 UTC 2020
*/
package org.joda.time.format;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import java.util.Locale;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.joda.time.DateTimeFieldType;
import org.joda.time.DateTimeZone;
import org.joda.time.DurationFieldType;
import org.joda.time.chrono.GJChronology;
import org.joda.time.field.UnsupportedDurationField;
import org.joda.time.format.DateTimeParserBucket;
import org.joda.time.tz.FixedDateTimeZone;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(useVFS = true, useJEE = true)
public class DateTimeParserBucket_ESTest extends DateTimeParserBucket_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
DurationFieldType durationFieldType0 = DurationFieldType.eras();
UnsupportedDurationField unsupportedDurationField0 = UnsupportedDurationField.getInstance(durationFieldType0);
DateTimeParserBucket.compareReverse(unsupportedDurationField0, unsupportedDurationField0);
GJChronology gJChronology0 = GJChronology.getInstanceUTC();
Locale locale0 = new Locale("S:}gCLMkc-");
DateTimeParserBucket dateTimeParserBucket0 = new DateTimeParserBucket(0, gJChronology0, locale0);
dateTimeParserBucket0.computeMillis();
FixedDateTimeZone fixedDateTimeZone0 = (FixedDateTimeZone)DateTimeZone.UTC;
dateTimeParserBucket0.setZone(fixedDateTimeZone0);
dateTimeParserBucket0.computeMillis(false, "");
DateTimeFieldType dateTimeFieldType0 = DateTimeFieldType.dayOfMonth();
dateTimeParserBucket0.saveField(dateTimeFieldType0, 0);
// Undeclared exception!
dateTimeParserBucket0.computeMillis();
}
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
48996343cc088248849735c8b8ddcff8894434d1 | 07293c82eb75315d53a380c065b2228a197014d5 | /aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/transform/PolicyAttributeStaxUnmarshaller.java | 2f4cb587751cfa131b3e08ed2bdd985477f09b40 | [
"Apache-2.0",
"JSON"
] | permissive | harshith-ch/aws-sdk-java | 8f03aeaae326f09d5be0b3baab6c9fa210658925 | fbfd5fd9bb171b1ab5533822c1a201f6d12c6523 | refs/heads/master | 2021-01-15T13:35:19.031844 | 2016-04-17T00:28:10 | 2016-04-17T00:28:10 | 56,202,108 | 0 | 0 | null | 2016-04-14T02:46:58 | 2016-04-14T02:46:58 | null | UTF-8 | Java | false | false | 2,749 | java | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticloadbalancing.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.elasticloadbalancing.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* PolicyAttribute StAX Unmarshaller
*/
public class PolicyAttributeStaxUnmarshaller implements
Unmarshaller<PolicyAttribute, StaxUnmarshallerContext> {
public PolicyAttribute unmarshall(StaxUnmarshallerContext context)
throws Exception {
PolicyAttribute policyAttribute = new PolicyAttribute();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return policyAttribute;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("AttributeName", targetDepth)) {
policyAttribute.setAttributeName(StringStaxUnmarshaller
.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("AttributeValue", targetDepth)) {
policyAttribute.setAttributeValue(StringStaxUnmarshaller
.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return policyAttribute;
}
}
}
}
private static PolicyAttributeStaxUnmarshaller instance;
public static PolicyAttributeStaxUnmarshaller getInstance() {
if (instance == null)
instance = new PolicyAttributeStaxUnmarshaller();
return instance;
}
}
| [
"aws@amazon.com"
] | aws@amazon.com |
790da85cdbb5a6a274547c7c6cb199108d4a9be3 | 6c53b2b97e7d6873709ae1106e929bbe181a9379 | /src/java/com/eviware/soapui/impl/wsdl/submit/RequestTransport.java | a717a0dc63772f3a82e5fe460a0520959a51aa65 | [] | no_license | stallewar/soapui- | ca7824f4c4bc268b9a7798383f4f2a141d38214b | 0464f7826945709032964af67906e7d6e61b698a | refs/heads/master | 2023-03-19T05:23:56.746903 | 2011-07-12T08:29:36 | 2011-07-12T08:29:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,261 | java | /*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.submit;
import com.eviware.soapui.model.iface.Request;
import com.eviware.soapui.model.iface.Response;
import com.eviware.soapui.model.iface.SubmitContext;
/**
* Defines protocol-specific behaviour
*
* @author Ole.Matzura
*/
public interface RequestTransport
{
public final static String WSDL_REQUEST = "wsdlRequest";
public static final String REQUEST_TRANSPORT = "requestTransport";
public void addRequestFilter( RequestFilter filter );
public void removeRequestFilter( RequestFilter filter );
public void abortRequest( SubmitContext submitContext );
public Response sendRequest( SubmitContext submitContext, Request request ) throws Exception;
}
| [
"oysteigi@bluebear.(none)"
] | oysteigi@bluebear.(none) |
3f5e324bf90206d9bc09be76407ef64a8624b62b | 29de50a833d4270a0c8e48025c2320cbb7c8368e | /src/com/service/impl/EmployService.java | 22a3fc1ca0ede80a07c2f207cb70fac885392051 | [] | no_license | MCvolcano/EmployeeSys | d80088a4aaa549dbda112ff3d94d88d61688d515 | 4a3975beec5eb4633e827cb8fae5857091338a44 | refs/heads/master | 2021-06-29T18:00:40.032695 | 2017-09-13T14:28:01 | 2017-09-13T14:28:01 | 103,410,102 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,887 | java | package com.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.dao.IEmployeeDao;
import com.dao.impl.EmployeeDao;
import com.entity.Employee;
import com.service.IEmployeeService;
public class EmployService implements IEmployeeService {
private IEmployeeDao dao = new EmployeeDao();
/**
* 添加
* @param emp 雇员
*/
@Override
public void addEmp(Employee emp) {
//判断是否存在相同名称的数据
Employee employee = dao.findByName(emp.getName());
if(employee == null) {
try{
dao.addEmployee(emp);//执行添加操作
} catch(Exception e) {
throw new RuntimeException("员工数据异常");
}
} else {
throw new RuntimeException("存在相同姓名的员工,插入出错");
}
}
@Override
public void deleteEmpById(int id) {
try {
Employee employee = dao.findById(id);
if (employee != null) {
dao.deleteEmployeeById(id);
} else {
throw new RuntimeException("员工不存在,不能删除");
}
} catch (Exception e) {
throw new RuntimeException("员工不存在,不能删除");
}
}
@Override
public void updateEmp(Employee emp) {
dao.update(emp);
}
@Override
public List<Employee> findAllEmps() {
List<Employee> list = null;
try {
//获取数据
list = dao.findAll();
if (list == null) {
throw new RuntimeException("全体员工数据不存在");
}
} catch (Exception e) {
throw new RuntimeException("获取员工数据异常");
}
return list;
}
@Override
public Employee findEmyById(int id) {
Employee emp = null;
try {
emp = dao.findById(id);
if (emp == null) {
throw new RuntimeException("员工数据不存在");
}
} catch (Exception e) {
throw new RuntimeException("查询出现异常");
}
return emp;
}
}
| [
"2415575070@qq.com"
] | 2415575070@qq.com |
fb4da0b33ec7ebef35ab1c1ea9090a182f9a763a | 18eba99ba5bb960a94b96e23de024c835c449b1f | /baekjoon/graph/dfsBfs/getArea/Pair.java | f4114e15b7ad60ad864e83b29939584c707367d2 | [] | no_license | MinseongLee/algorithms | 592bdb0b21474badafe650a3a6a4ec5ebc140ab3 | bfd3d4d3da82b2bea3828c173d535fe518882472 | refs/heads/master | 2021-05-25T17:18:31.398913 | 2020-10-05T08:15:14 | 2020-10-05T08:15:14 | 253,839,621 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 163 | java | package baekjoon.graph.dfsBfs.getArea;
public class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
| [
"dexlee4567@gmail.com"
] | dexlee4567@gmail.com |
29e5a3e9616977d002cbd2bc62a5165af856b2d3 | af58eabf5360cb82082e1b0590696b627118d5a3 | /yunfu-db/src/main/java/com/zhongmei/bty/basemodule/orderdish/entity/DishUnitDictionary.java | 7033a9225f53815dac2b1658910b1c1d8ea968f5 | [] | no_license | sengeiou/marketing-app | f4b670f3996ba190decd2f1b8e4a276eb53b8b2a | 278f3da95584e2ab7d97dff1a067db848e70a9f3 | refs/heads/master | 2020-06-07T01:51:25.743676 | 2019-06-20T08:58:28 | 2019-06-20T08:58:28 | 192,895,799 | 0 | 1 | null | 2019-06-20T09:59:09 | 2019-06-20T09:59:08 | null | UTF-8 | Java | false | false | 2,882 | java | package com.zhongmei.bty.basemodule.orderdish.entity;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import com.zhongmei.yunfu.db.BasicEntityBase;
import com.zhongmei.yunfu.db.ICreator;
import com.zhongmei.yunfu.db.IUpdator;
/**
* DishUnitDictionary is a ORMLite bean type. Corresponds to the database table "dish_unit_dictionary"
*/
@DatabaseTable(tableName = "dish_unit_dictionary")
public class DishUnitDictionary extends BasicEntityBase implements ICreator, IUpdator {
private static final long serialVersionUID = 1L;
/**
* The columns of table "dish_unit_dictionary"
*/
public interface $ extends BasicEntityBase.$ {
/**
* alias_name
*/
public static final String aliasName = "alias_name";
/**
* creator_id
*/
public static final String creatorId = "creator_id";
/**
* creator_name
*/
public static final String creatorName = "creator_name";
/**
* name
*/
public static final String name = "name";
/**
* updator_id
*/
public static final String updatorId = "updator_id";
/**
* updator_name
*/
public static final String updatorName = "updator_name";
}
@DatabaseField(columnName = "alias_name")
private String aliasName;
@DatabaseField(columnName = "creator_id")
private Long creatorId;
@DatabaseField(columnName = "creator_name")
private String creatorName;
@DatabaseField(columnName = "name", canBeNull = false)
private String name;
@DatabaseField(columnName = "updator_id")
private Long updatorId;
@DatabaseField(columnName = "updator_name")
private String updatorName;
public String getAliasName() {
return aliasName;
}
public void setAliasName(String aliasName) {
this.aliasName = aliasName;
}
public Long getCreatorId() {
return creatorId;
}
public void setCreatorId(Long creatorId) {
this.creatorId = creatorId;
}
public String getCreatorName() {
return creatorName;
}
public void setCreatorName(String creatorName) {
this.creatorName = creatorName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getUpdatorId() {
return updatorId;
}
public void setUpdatorId(Long updatorId) {
this.updatorId = updatorId;
}
public String getUpdatorName() {
return updatorName;
}
public void setUpdatorName(String updatorName) {
this.updatorName = updatorName;
}
@Override
public boolean checkNonNull() {
return super.checkNonNull() && checkNonNull(name);
}
}
| [
"yangyuanping_cd@shishike.com"
] | yangyuanping_cd@shishike.com |
27a41351e75599ad99e9622c123f8e649a33112a | 70d9be5609a6c9c3252413ba4dd49970a0b0d1a6 | /EwasmSelectorFunctionProvider.java | 3e4d6f325670172e26d65be00b2d34434f4c3ae1 | [] | no_license | schwarzalex/ewasm-formalization | 7f5339fcd06380e51016ac58425ac224d2240caf | 7eb522f0914e5173b1aada605ce0176a3ed62255 | refs/heads/master | 2020-09-22T11:27:42.217470 | 2019-12-01T14:58:43 | 2019-12-01T14:58:43 | 225,175,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 50,887 | java | import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.lang3.EnumUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import secpriv.horst.data.tuples.*;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EwasmSelectorFunctionProvider {
private static final Logger LOGGER = LogManager.getLogger(EwasmSelectorFunctionProvider.class);
private static final int PAGESIZE = 65536;
Pattern fileIdPattern = Pattern.compile("\\[id(\\d+)\\]"); // matches for example [id3]
private List<Contract> contractList;
private List<Integer> noInits = new ArrayList<Integer>() {{
add(16);
add(100);
}};
public EwasmV13SelectorFunctionProvider() {
System.out.println("EwasmSelectorFunctionProvider was successfully loaded.");
}
public EwasmV13SelectorFunctionProvider(List<String> args) throws IOException {
contractList = new ArrayList<>();
for (String arg : args) {
Contract contract = parseContract(arg);
String fileName = Paths.get(arg).getFileName().toString();
Matcher matchId = fileIdPattern.matcher(fileName);
if (matchId.find()) {
// parse custom id from filename if available
contract.id = Integer.parseInt(matchId.group(1));
} else {
// generate id from filename if no custom id was provided
contract.id = Math.abs(fileName.hashCode());
}
contractList.add(contract);
System.out.println(contract);
if (fileName.contains("[r]")) {
// reentrancy contract has to be created
Contract reentrancyContract = new Contract(contract);
reentrancyContract.id = 100;
contractList.add(reentrancyContract);
System.out.println(reentrancyContract);
}
}
}
public Iterable<Tuple5<BigInteger, BigInteger, BigInteger, BigInteger, BigInteger>> contractInits() {
List<Tuple5<BigInteger, BigInteger, BigInteger, BigInteger, BigInteger>> result = new ArrayList<>();
for (Contract contract : contractList) {
if (noInits.contains(contract.id)) {
// do not create the initial state of certain contracts
// (usually combined with a manual init rule that contains for example abstract values)
continue;
}
result.add(new Tuple5<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(contract.getFirstPositionOfFunction(contract.mainFunctionIndex)), BigInteger.valueOf(100_000_000), BigInteger.valueOf(contract.initialMemorySize), BigInteger.valueOf(contract.getTableSize())));
}
return result;
}
public Iterable<Tuple3<BigInteger, BigInteger, BigInteger>> contractInit(BigInteger contractId) {
List<Tuple3<BigInteger, BigInteger, BigInteger>> result = new ArrayList<>();
Contract c = getContractForId(contractId.intValue());
result.add(new Tuple3<>(BigInteger.valueOf(c.getFirstPositionOfFunction(c.mainFunctionIndex)), BigInteger.valueOf(c.initialMemorySize), BigInteger.valueOf(c.getTableSize())));
return result;
}
public Iterable<BigInteger> interval(BigInteger a, BigInteger b) {
return new Iterable<BigInteger>() {
@Override
public Iterator<BigInteger> iterator() {
return new Iterator<BigInteger>() {
BigInteger state = a;
@Override
public boolean hasNext() {
return state.compareTo(b) <= 0;
}
@Override
public BigInteger next() {
BigInteger cur = state;
state = state.add(BigInteger.ONE);
return cur;
}
};
}
};
}
public Iterable<Tuple2<BigInteger, BigInteger>> contractAndPcForInstruction(BigInteger instruction) {
List<Tuple2<BigInteger, BigInteger>> result = new ArrayList<>();
for (Contract contract : contractList) {
for (OpcodeInstance opcodeInstance : contract.getOpcodeInstancesForOpcodeValue(instruction)) {
result.add(new Tuple2<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position)));
}
}
return result;
}
public Iterable<Tuple3<BigInteger, BigInteger, BigInteger>> contractAndPcAndValueForInstruction(BigInteger instruction) {
List<Tuple3<BigInteger, BigInteger, BigInteger>> result = new ArrayList<>();
for (Contract contract : contractList) {
for (OpcodeInstance opcodeInstance : contract.getOpcodeInstancesForOpcodeValue(instruction)) {
// special case for end_function opcode instances where each possible originating call has to be handled
if (opcodeInstance.opcode == Opcode.END_FUNCTION) {
for (Integer position : contract.findAllPositionsTargetingFunction(opcodeInstance.immediate.intValue())) {
result.add(new Tuple3<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position), BigInteger.valueOf(position)));
}
continue;
}
// ELSE opcode has to have the matching END position as value
if (opcodeInstance.opcode == Opcode.ELSE) {
OpcodeInstance matchingEnd = contract.getMatchingEndForControlOpcodeInstance(opcodeInstance);
result.add(new Tuple3<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position), BigInteger.valueOf(matchingEnd.position)));
continue;
}
// IF opcode has to either have the first position of the else branch or the position of the END branch if no ELSE exists
if (opcodeInstance.opcode == Opcode.IF) {
int position;
OpcodeInstance matchingElse = contract.getMatchingElseOpcodeInstanceForIf(opcodeInstance);
if (matchingElse != null) {
position = matchingElse.position + 1;
} else {
// IF does not have an else branch
position = contract.getMatchingEndForControlOpcodeInstance(opcodeInstance).position;
}
result.add(new Tuple3<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position), BigInteger.valueOf(position)));
continue;
}
result.add(new Tuple3<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position), opcodeInstance.immediate));
}
}
return result;
}
public Iterable<Tuple4<BigInteger, BigInteger, BigInteger, BigInteger>> callInformation(BigInteger instruction) {
List<Tuple4<BigInteger, BigInteger, BigInteger, BigInteger>> result = new ArrayList<>();
for (Contract contract : contractList) {
for (OpcodeInstance opcodeInstance : contract.getOpcodeInstancesForOpcodeValue(instruction)) {
int functionIdx = opcodeInstance.immediate.intValue();
result.add(new Tuple4<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position),
BigInteger.valueOf(contract.getNumberOfParametersOfFunction(functionIdx)), BigInteger.valueOf(contract.getFirstPositionOfFunction(functionIdx))));
}
}
return result;
}
public Iterable<Tuple5<BigInteger, BigInteger, BigInteger, BigInteger, Boolean>> callIndirectInformation(BigInteger instruction) {
List<Tuple5<BigInteger, BigInteger, BigInteger, BigInteger, Boolean>> result = new ArrayList<>();
for (Contract contract : contractList) {
for (OpcodeInstance opcodeInstance : contract.getOpcodeInstancesForOpcodeValue(instruction)) {
// each possible table element has to be addressed
for (Integer functionIdx : contract.table) {
if (functionIdx == null) {
// function not initialized, so typeValid is set to false
result.add(new Tuple5<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position), BigInteger.valueOf(-1), BigInteger.valueOf(-1), false));
}
int numparam = contract.getNumberOfParametersOfFunction(functionIdx);
int targetPc = contract.getFirstPositionOfFunction(functionIdx);
boolean typeValid = opcodeInstance.immediate.intValue() == contract.getCustomTypeOfFunction(functionIdx).index;
result.add(new Tuple5<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position), BigInteger.valueOf(numparam), BigInteger.valueOf(targetPc), typeValid));
}
}
}
return result;
}
public Iterable<Tuple5<BigInteger, BigInteger, BigInteger, BigInteger, BigInteger>> branchInformation(BigInteger instruction) {
List<Tuple5<BigInteger, BigInteger, BigInteger, BigInteger, BigInteger>> result = new ArrayList<>();
for (Contract contract : contractList) {
// BR
for (OpcodeInstance opcodeInstance : contract.getOpcodeInstancesForOpcodeValue(instruction)) {
BigInteger targetPc = BigInteger.valueOf(contract.getTargetPcForBr(opcodeInstance));
BigInteger heightDifference = BigInteger.valueOf(contract.getStackHeightDifferenceForBranch(opcodeInstance));
BigInteger numpopped = BigInteger.valueOf(contract.getNumberOfPoppedValuesForBr(opcodeInstance));
result.add(new Tuple5<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(opcodeInstance.position), targetPc, heightDifference, numpopped));
}
if (instruction.intValue() != 12) {
continue;
}
// also RETURN opcodes are handled with the BR rule
BigInteger returnOpcodeValue = BigInteger.valueOf(15);
for (OpcodeInstance returnOpcodeInstance : contract.getOpcodeInstancesForOpcodeValue(returnOpcodeValue)) {
int enclosingFunctionIndex = contract.getFunctionIndexForOpcodeInstance(returnOpcodeInstance);
OpcodeInstance functionStart = contract.getOpcodeInstanceForPosition(contract.getFirstPositionOfFunction(enclosingFunctionIndex));
OpcodeInstance functionEnd = contract.getFunctionEndForOpcodeInstance(returnOpcodeInstance);
// targetPc is equal to the function end
BigInteger targetPc = BigInteger.valueOf(functionEnd.position);
// height difference is between the function start and the return opcode instance
BigInteger stackModificationFromFunctionStart = BigInteger.valueOf(contract.getStackModificationBetweenOpcodeInstances(functionStart, returnOpcodeInstance));
BigInteger numpopped = BigInteger.valueOf(contract.getCustomTypeOfFunction(enclosingFunctionIndex).getNumberOfReturnValues());
result.add(new Tuple5<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(returnOpcodeInstance.position), targetPc, stackModificationFromFunctionStart, numpopped));
}
}
return result;
}
public Iterable<Tuple6<BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger>> branchTableInformation(BigInteger instruction) {
List<Tuple6<BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger>> result = new ArrayList<>();
for (Contract contract : contractList) {
// BR_TABLE
for (OpcodeInstance opcodeInstance : contract.getOpcodeInstancesForOpcodeValue(instruction)) {
// iterate over all target elements
for (int i = 0; i < opcodeInstance.targets.length; i++) {
OpcodeInstance tempBrOpcodeInstance = new OpcodeInstance();
// pretend that for each possible branch value there exists a BR instance
tempBrOpcodeInstance.opcode = Opcode.BR;
tempBrOpcodeInstance.position = opcodeInstance.position;
tempBrOpcodeInstance.immediate = BigInteger.valueOf(opcodeInstance.targets[i]);
BigInteger targetPc = BigInteger.valueOf(contract.getTargetPcForBr(tempBrOpcodeInstance));
// the reason for the -1 is that a BR_TABLE always has a const before itself which has to be excluded since it is consumed in this step
BigInteger heightDifference = BigInteger.valueOf(contract.getStackHeightDifferenceForBranch(tempBrOpcodeInstance) - 1);
BigInteger numpopped = BigInteger.valueOf(contract.getNumberOfPoppedValuesForBr(tempBrOpcodeInstance));
result.add(new Tuple6<>(BigInteger.valueOf(contract.id), BigInteger.valueOf(tempBrOpcodeInstance.position), targetPc, heightDifference, numpopped, BigInteger.valueOf(i)));
}
}
}
return result;
}
public Iterable<Tuple2<BigInteger, BigInteger>> globalInits(BigInteger contractId) {
List<Tuple2<BigInteger, BigInteger>> result = new ArrayList<>();
Contract c = getContractForId(contractId.intValue());
for (int i = 0; i < c.globals.size(); i++) {
result.add(new Tuple2<>(c.globals.get(i), BigInteger.valueOf(i)));
}
return result;
}
public Iterable<Tuple2<BigInteger, BigInteger>> tableInits(BigInteger contractId) {
List<Tuple2<BigInteger, BigInteger>> result = new ArrayList<>();
Contract c = getContractForId(contractId.intValue());
if (!c.hasTable()) {
return result;
}
for (int i = 0; i < c.table.length; i++) {
result.add(new Tuple2<>(c.getTableTargetPc(i), BigInteger.valueOf(i)));
}
return result;
}
public Iterable<Tuple2<BigInteger, BigInteger>> memoryInits(BigInteger contractId) {
List<Tuple2<BigInteger, BigInteger>> result = new ArrayList<>();
Contract c = getContractForId(contractId.intValue());
for (Map.Entry<Integer, Integer> memoryEntry : c.memoryData.entrySet()) {
result.add(new Tuple2<>(BigInteger.valueOf(memoryEntry.getValue()), BigInteger.valueOf(memoryEntry.getKey())));
}
return result;
}
public Iterable<BigInteger> pcForContractAndOpcode(BigInteger contractId, BigInteger opcode) {
List<BigInteger> result = new ArrayList<>();
Contract c = getContractForId(contractId.intValue());
for (OpcodeInstance opcodeInstance : c.getOpcodeInstancesForOpcodeValue(opcode)) {
result.add(BigInteger.valueOf(opcodeInstance.position));
}
return result;
}
public Iterable<BigInteger> constOps() {
List<BigInteger> result = new ArrayList<>();
result.add(BigInteger.valueOf(Opcode.CONSTI32.code));
result.add(BigInteger.valueOf(Opcode.CONSTI64.code));
return result;
}
public Iterable<BigInteger> cvtOps() {
List<BigInteger> result = new ArrayList<>();
result.add(BigInteger.valueOf(Opcode.WRAP_I64.code));
return result;
}
public Iterable<BigInteger> relOps() {
List<BigInteger> result = new ArrayList<>();
result.add(BigInteger.valueOf(Opcode.EQI32.code));
result.add(BigInteger.valueOf(Opcode.NEI32.code));
result.add(BigInteger.valueOf(Opcode.LT_SI32.code));
result.add(BigInteger.valueOf(Opcode.LT_UI32.code));
result.add(BigInteger.valueOf(Opcode.GT_SI32.code));
result.add(BigInteger.valueOf(Opcode.GT_UI32.code));
result.add(BigInteger.valueOf(Opcode.LE_SI32.code));
result.add(BigInteger.valueOf(Opcode.LE_UI32.code));
result.add(BigInteger.valueOf(Opcode.GE_SI32.code));
result.add(BigInteger.valueOf(Opcode.GE_UI32.code));
result.add(BigInteger.valueOf(Opcode.EQI64.code));
result.add(BigInteger.valueOf(Opcode.NEI64.code));
return result;
}
public Iterable<BigInteger> binOps() {
List<BigInteger> result = new ArrayList<>();
result.add(BigInteger.valueOf(Opcode.ADDI32.code));
result.add(BigInteger.valueOf(Opcode.SUBI32.code));
result.add(BigInteger.valueOf(Opcode.MULI32.code));
result.add(BigInteger.valueOf(Opcode.ANDI32.code));
result.add(BigInteger.valueOf(Opcode.ORI32.code));
result.add(BigInteger.valueOf(Opcode.XORI32.code));
result.add(BigInteger.valueOf(Opcode.SHLI32.code));
result.add(BigInteger.valueOf(Opcode.SHR_UI32.code));
result.add(BigInteger.valueOf(Opcode.ANDI64.code));
result.add(BigInteger.valueOf(Opcode.ORI64.code));
result.add(BigInteger.valueOf(Opcode.XORI64.code));
result.add(BigInteger.valueOf(Opcode.SHLI64.code));
result.add(BigInteger.valueOf(Opcode.SHR_UI64.code));
return result;
}
/* EEI get functions */
public Iterable<BigInteger> eeiGetOnePZeroROps() {
List<BigInteger> result = new ArrayList<>();
result.add(BigInteger.valueOf(Opcode.EEI_GETADDRESS.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETCALLER.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETCALLVALUE.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETBLOCKCOINBASE.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETBLOCKDIFFICULTY.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETTXGASPRICE.code));
return result;
}
public Iterable<BigInteger> eeiGetZeroPOneROps() {
List<BigInteger> result = new ArrayList<>();
// does not include EEI_GETGASLEFT since there is a separate rule for that
result.add(BigInteger.valueOf(Opcode.EEI_GETCALLDATASIZE.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETCODESIZE.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETBLOCKGASLIMIT.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETBLOCKNUMBER.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETRETURNDATASIZE.code));
result.add(BigInteger.valueOf(Opcode.EEI_GETBLOCKTIMESTAMP.code));
return result;
}
public Iterable<BigInteger> eeiCopyOps() {
List<BigInteger> result = new ArrayList<>();
// does not include EEI_GETGASLEFT since there is a separate rule for that
result.add(BigInteger.valueOf(Opcode.EEI_CODECOPY.code));
result.add(BigInteger.valueOf(Opcode.EEI_RETURNDATACOPY.code));
result.add(BigInteger.valueOf(Opcode.EEI_CALLDATACOPY.code));
return result;
}
private Contract getContractForId(int contractId) {
return contractList.stream().filter(c -> c.id == contractId).findFirst().get();
}
/*-------------- contract parsing --------------*/
private static class Contract {
public int id;
public List<Integer> functionTypeIndices;
public int mainFunctionIndex;
public int initialMemorySize;
public CustomType[] customTypes;
public ArrayList<ArrayList<OpcodeInstance>> functions = new ArrayList<>();
public ArrayList<BigInteger> globals = new ArrayList<>();
// map of EEI function opcodes and their function index
public Map<Opcode, Integer> eeiFunctions = new HashMap<>();
// contains the function ids
public Integer[] table;
// data segments as elements for the respective index
public Map<Integer, Integer> memoryData = new HashMap<>();
public List<OpcodeInstance> allOpcodeInstances;
private Map<Opcode, List<OpcodeInstance>> opcodeToOpcodeInstances;
public Contract() {
}
public Contract(Contract otherContract) {
/*
the shallow copying below is only fine as long as the objects are immutable
this is implicitly the case since they are only read in the current setup
if this changes in the future deep copy mechanisms have to be implemented
*/
id = otherContract.id;
functionTypeIndices = otherContract.functionTypeIndices;
mainFunctionIndex = otherContract.mainFunctionIndex;
initialMemorySize = otherContract.initialMemorySize;
customTypes = otherContract.customTypes;
functions = otherContract.functions;
globals = otherContract.globals;
eeiFunctions = otherContract.eeiFunctions;
table = otherContract.table;
memoryData = otherContract.memoryData;
allOpcodeInstances = otherContract.allOpcodeInstances;
opcodeToOpcodeInstances = otherContract.opcodeToOpcodeInstances;
}
public void generateHelperCollections() {
if (allOpcodeInstances == null) {
allOpcodeInstances = new ArrayList<>();
functions.forEach(opcodeInstances -> allOpcodeInstances.addAll(opcodeInstances));
}
if (opcodeToOpcodeInstances == null) {
opcodeToOpcodeInstances = new HashMap<>();
for (OpcodeInstance opcodeInstance : allOpcodeInstances) {
opcodeToOpcodeInstances.computeIfAbsent(opcodeInstance.opcode, k -> new ArrayList<>());
opcodeToOpcodeInstances.get(opcodeInstance.opcode).add(opcodeInstance);
}
}
}
public List<OpcodeInstance> getOpcodeInstancesForOpcodeValue(BigInteger opcodeValue) {
Opcode opcode = Opcode.getOpcode(opcodeValue.intValue());
return opcodeToOpcodeInstances.getOrDefault(opcode, Collections.emptyList());
}
public List<OpcodeInstance> getOpcodeInstancesForOpcode(Opcode opcode) {
return opcodeToOpcodeInstances.getOrDefault(opcode, Collections.emptyList());
}
public OpcodeInstance getOpcodeInstanceForPosition(int position) {
for (OpcodeInstance opcodeInstance : allOpcodeInstances) {
if (opcodeInstance.position == position) {
return opcodeInstance;
}
}
return null;
}
public int getTableSize() {
if (table == null) {
return 0;
} else {
return table.length;
}
}
public boolean hasTable() {
return table != null;
}
/**
* Returns a list of all positions from which the specified function is called.
* This includes CALL as well as CALL_INDIRECT. Even though for indirect calls it could be checked
* more precise (if the function is really in the table), for now all CALL_INDIRECT instructions
* are simply added.
*
* @param functionId the id of the targeted function
* @return a list of possible source positions of calls (and all indirect call positions)
*/
public List<Integer> findAllPositionsTargetingFunction(int functionId) {
List<Integer> positionList = new ArrayList<>();
for (OpcodeInstance opcodeInstance : getOpcodeInstancesForOpcode(Opcode.CALL)) {
if (BigInteger.valueOf(functionId).compareTo(opcodeInstance.immediate) == 0) {
positionList.add(opcodeInstance.position);
}
}
for (OpcodeInstance opcodeInstance : getOpcodeInstancesForOpcode(Opcode.CALL_INDIRECT)) {
positionList.add(opcodeInstance.position);
}
return positionList;
}
public int getFirstPositionOfFunction(int functionId) {
return functions.get(functionId).get(0).position;
}
public int getLastPositionOfFunction(int functionId) {
return functions.get(functionId).get(functions.get(functionId).size() - 1).position;
}
public CustomType getCustomTypeOfFunction(int functionIndex) {
return customTypes[functionTypeIndices.get(functionIndex)];
}
public int getNumberOfParametersOfFunction(int functionIndex) {
return getCustomTypeOfFunction(functionIndex).getNumberOfParamters();
}
public int getFunctionIndexForOpcodeInstance(OpcodeInstance opcodeInstance) {
for (int i = 0; i < functions.size(); i++) {
List<OpcodeInstance> currentFunction = functions.get(i);
for (OpcodeInstance currentOpcodeInstance : currentFunction) {
if (currentOpcodeInstance.position == opcodeInstance.position) {
return i;
}
}
}
throw new RuntimeException("Opcode instance has to be inside a function.");
}
/**
* Returns the first position of the function which is saved in the table at the specified index
*
* @param tableIndex index of table where function index is saved
* @return first position of function or -1 if table/table element is null
*/
public BigInteger getTableTargetPc(int tableIndex) {
if (table == null || tableIndex >= table.length || table[tableIndex] == null) {
return BigInteger.valueOf(-1);
} else {
return BigInteger.valueOf(getFirstPositionOfFunction(table[tableIndex]));
}
}
public OpcodeInstance getFunctionEndForOpcodeInstance(OpcodeInstance opcodeInstance) {
return getOpcodeInstanceForPosition(getLastPositionOfFunction(getFunctionIndexForOpcodeInstance(opcodeInstance)));
}
/**
* Find the matching END opcode instance for a control opcode instance (BLOCK,LOOP,IF).
*
* @param controlOpcodeInstance instance of a control opcode
* @return the matching END opcode instance
*/
public OpcodeInstance getMatchingEndForControlOpcodeInstance(OpcodeInstance controlOpcodeInstance) {
if (controlOpcodeInstance.opcode != Opcode.BLOCK && controlOpcodeInstance.opcode != Opcode.LOOP && controlOpcodeInstance.opcode != Opcode.IF && controlOpcodeInstance.opcode != Opcode.ELSE) {
throw new IllegalArgumentException("getMatchingEndForIf can only be called for a control opcode instance (BLOCK,LOOP,IF,ELSE)");
}
// Since control structures can be nested the nesting depth has to be tracked.
// Only if an END on the same level is found it is the correct one.
int depth = 0;
for (int i = controlOpcodeInstance.position + 1; i < getLastPositionOfFunction(getFunctionIndexForOpcodeInstance(controlOpcodeInstance)); i++) {
OpcodeInstance cur = getOpcodeInstanceForPosition(i);
if (cur.opcode == Opcode.END && depth == 0) {
return cur;
}
if (cur.opcode == Opcode.IF || cur.opcode == Opcode.BLOCK || cur.opcode == Opcode.LOOP) {
// Depth has to be increased because IF, BLOCK and LOOP all have matching ENDs.
// ELSE does not increase the depth since it shares the END opcode with an IF.
depth++;
}
if (cur.opcode == Opcode.END) {
depth--;
}
}
throw new RuntimeException("END opcode instance for control opcode instance has to exist.");
}
/**
* Find the matching ELSE opcode instance for an IF opcode instance, or return null if ELSE does not exist.
*
* @param opcodeInstanceIf if opcode instance
* @return matching ELSE or null
*/
public OpcodeInstance getMatchingElseOpcodeInstanceForIf(OpcodeInstance opcodeInstanceIf) {
if (opcodeInstanceIf.opcode != Opcode.IF) {
throw new IllegalArgumentException("getMatchingElseOpcodeInstanceForIf can only be called for an IF instance.");
}
int depth = 0;
for (int i = opcodeInstanceIf.position + 1; i < getMatchingEndForControlOpcodeInstance(opcodeInstanceIf).position; i++) {
OpcodeInstance cur = getOpcodeInstanceForPosition(i);
if (cur.opcode == Opcode.ELSE && depth == 0) {
return cur;
}
if (cur.opcode == Opcode.IF || cur.opcode == Opcode.BLOCK || cur.opcode == Opcode.LOOP) {
// depth has to be increased because nested control structures could also contain ELSE opcode instances
depth++;
}
if (cur.opcode == Opcode.END) {
depth--;
}
}
return null;
}
/**
* Find the target opcode instance for the provided BR or BR_IF opcode instance (and not label opcode).
* The target in this case is the control opcode instance itself (i.e. LOOP, BLOCK, IF) even though the final target of
* BLOCKs and IFs are the end code. The reason for this is that in several cases information about the control opcodes are
* needed (e.g. result type).
* <p>
* In case of a branch to a function null is returned, since there is no dedicated function opcode.
*
* @param opcodeInstanceBr opcode instance of BR or BR_IF
* @return target opcode instance, or null if not found (i.e. function)
*/
private OpcodeInstance getTargetOpcodeInstanceForBr(OpcodeInstance opcodeInstanceBr) {
if (opcodeInstanceBr.opcode != Opcode.BR && opcodeInstanceBr.opcode != Opcode.BR_IF) {
throw new IllegalArgumentException("getTargetOpcodeInstanceForBr can only be called for a BR or BR_IF instance.");
}
int currentDepth = opcodeInstanceBr.immediate.intValue();
for (int i = opcodeInstanceBr.position - 1; i >= 0; i--) {
OpcodeInstance cur = getOpcodeInstanceForPosition(i);
if (currentDepth == 0 && cur.isBlockType()) {
return cur;
} else if (cur.opcode == Opcode.END) {
currentDepth++;
} else if (cur.isBlockType()) {
currentDepth--;
}
}
return null;
}
/**
* Find the target position for the provided BR or BR_IF opcode instance.
* - LOOP: the position of the LOOP opcode.
* - BLOCK/IF/function: the position of the matching END opcode.
*
* @param opcodeInstanceBr opcode instance of BR or BR_IF
* @return position int
*/
public int getTargetPcForBr(OpcodeInstance opcodeInstanceBr) {
OpcodeInstance targetOpcodeInstance = getTargetOpcodeInstanceForBr(opcodeInstanceBr);
if (targetOpcodeInstance == null) {
// branch to a function
return getFunctionEndForOpcodeInstance(opcodeInstanceBr).position;
}
if (targetOpcodeInstance.opcode == Opcode.LOOP) {
return targetOpcodeInstance.position;
} else {
// BLOCK or IF
OpcodeInstance matchingEnd = getMatchingEndForControlOpcodeInstance(targetOpcodeInstance);
return matchingEnd.position;
}
}
/**
* Find the number of values popped from the value stack which are needed for the branch.
*
* @param opcodeInstanceBr opcode instance of BR or BR_IF
* @return number of values to pop
*/
public int getNumberOfPoppedValuesForBr(OpcodeInstance opcodeInstanceBr) {
if (opcodeInstanceBr.opcode != Opcode.BR && opcodeInstanceBr.opcode != Opcode.BR_IF) {
throw new IllegalArgumentException("getNumberOfPoppedValuesForBr can only be called for a BR or BR_IF instance.");
}
OpcodeInstance targetOpcodeInstance = getTargetOpcodeInstanceForBr(opcodeInstanceBr);
if (targetOpcodeInstance == null) {
// branch to function
return getCustomTypeOfFunction(getFunctionIndexForOpcodeInstance(opcodeInstanceBr)).getNumberOfReturnValues();
} else if (targetOpcodeInstance.opcode == Opcode.LOOP) {
// Current WASM specification limits LOOP parameter to 0
return 0;
} else if (targetOpcodeInstance.immediateResultType != null) {
// Current WASM specification limits number of BLOCK or IF results to 0 or 1
return 1;
} else {
return 0;
}
}
/**
* Returns the value stack height modification for an opcode instance.
* For example an ADDI32 instance would result in the modification -1 (since two values are popped and one is pushed).
*
* @param opcodeInstance opcode instance
* @return stack height modification
*/
public int getStackModificationForOpcodeInstance(OpcodeInstance opcodeInstance) {
Integer modification = Opcode.getStackModificationIfNonDynamic(opcodeInstance.opcode);
if (modification != null) {
return modification;
}
// dynamic modification value has to be found
if (opcodeInstance.opcode == Opcode.CALL) {
return getCustomTypeOfFunction(opcodeInstance.immediate.intValue()).getStackModification();
} else if (opcodeInstance.opcode == Opcode.CALL_INDIRECT) {
return customTypes[opcodeInstance.immediate.intValue()].getStackModification();
}
throw new RuntimeException("Stack height modification has to exist.");
}
/**
* Calculate the height of the value stack inside the current function.
*
* @param opcodeInstance opcode instance
* @return stack height
* @deprecated use {@link #getStackHeightDifferenceForBranch} instead.
*/
@Deprecated
public int getStackHeightInsideFunction(OpcodeInstance opcodeInstance) {
int functionIndex = getFunctionIndexForOpcodeInstance(opcodeInstance);
int currentStackHeight = 0;
for (int i = getFirstPositionOfFunction(functionIndex); i < opcodeInstance.position; i++) {
OpcodeInstance currentOpcodeInstance = getOpcodeInstanceForPosition(i);
// if there is a BLOCK, LOOP or IF it can potentially be skipped and the only change is a possible result type
if (currentOpcodeInstance.isBlockType() && getMatchingEndForControlOpcodeInstance(currentOpcodeInstance).position <= opcodeInstance.position) {
if (currentOpcodeInstance.immediateResultType != null) {
currentStackHeight++;
}
i = getMatchingEndForControlOpcodeInstance(currentOpcodeInstance).position;
continue;
}
currentStackHeight += getStackModificationForOpcodeInstance(currentOpcodeInstance);
}
return currentStackHeight;
}
/**
* Calculate the value stack modification between the start and end opcode instance.
* Start should have a lower position than end.
* The result for a start and end opcode instances which have two i32.const instructions in-between
* is +2.
*
* @param startOpcodeInstance start opcode instance
* @param endOpcodeInstance end opcode instance
* @return stack height modification
*/
public int getStackModificationBetweenOpcodeInstances(OpcodeInstance startOpcodeInstance, OpcodeInstance endOpcodeInstance) {
int currentStackHeight = 0;
for (int i = startOpcodeInstance.position; i < endOpcodeInstance.position; i++) {
OpcodeInstance currentOpcodeInstance = getOpcodeInstanceForPosition(i);
// if there is a BLOCK, LOOP or IF it can potentially be skipped and the only change is a possible result type
if (currentOpcodeInstance.isBlockType() && getMatchingEndForControlOpcodeInstance(currentOpcodeInstance).position <= endOpcodeInstance.position) {
if (currentOpcodeInstance.immediateResultType != null) {
currentStackHeight++;
}
i = getMatchingEndForControlOpcodeInstance(currentOpcodeInstance).position;
continue;
}
currentStackHeight += getStackModificationForOpcodeInstance(currentOpcodeInstance);
}
return currentStackHeight;
}
/**
* Returns the target stack height for a BR or BR_IF opcode instance.
*
* @param opcodeInstanceBr the BR or BR_IF opcode instance
* @return the stack height of the branch target
* @deprecated use {@link #getStackHeightDifferenceForBranch} instead.
*/
@Deprecated
public int getTargetStackHeightForBr(OpcodeInstance opcodeInstanceBr) {
OpcodeInstance target = getTargetOpcodeInstanceForBr(opcodeInstanceBr);
if (target == null) {
// branch to function
return 0;
}
return getStackHeightInsideFunction(target);
}
/**
* Returns the relative stack height modification between the BR and the target.
* For example, a block with a i32.const inside followed by a branch to 0 results in -1.
* This negative value is then added in the horst rule to the current ssize.
* <p>
* The existence of a result value at the target BLOCK does not influence the result
* (this is handled directly in the horst rule).
*
* @param brOpcodeInstance the BR or BR_IF opcode instance
* @return the stack height modification
*/
public int getStackHeightDifferenceForBranch(OpcodeInstance brOpcodeInstance) {
OpcodeInstance start = getTargetOpcodeInstanceForBr(brOpcodeInstance);
if (start == null) {
// branch to function
start = getOpcodeInstanceForPosition(getFirstPositionOfFunction(getFunctionIndexForOpcodeInstance(brOpcodeInstance)));
}
return getStackModificationBetweenOpcodeInstances(start, brOpcodeInstance);
}
@Override
public String toString() {
return "Contract{" +
"id=" + id +
", functionTypeIndices=" + functionTypeIndices +
", mainFunctionIndex=" + mainFunctionIndex +
", initialMemorySize=" + initialMemorySize +
", customTypes=" + Arrays.toString(customTypes) +
", functions=" + functions +
", globals=" + globals +
", eeiFunctions=" + eeiFunctions +
", table=" + Arrays.toString(table) +
", memoryData=" + memoryData +
",\n\tallOpcodeInstances=" + allOpcodeInstances +
",\n\topcodeToOpcodeInstances=" + opcodeToOpcodeInstances +
'}';
}
}
private static class CustomType {
public int index;
public List<LanguageType> parameters;
public LanguageType return_type;
CustomType(int index, List<LanguageType> parameters, LanguageType return_type) {
this.index = index;
this.parameters = parameters;
this.return_type = return_type;
}
public int getNumberOfParamters() {
return parameters.size();
}
public int getNumberOfReturnValues() {
return return_type == null ? 0 : 1;
}
/**
* Returns the number of result values (0 or 1) minus the consumed parameters.
*
* @return the height modification
*/
public int getStackModification() {
int modification = 0;
if (return_type != null) {
modification++;
}
return modification - getNumberOfParamters();
}
@Override
public String toString() {
return "CustomType{" +
"index=" + index +
", parameters=" + parameters +
", return_type=" + return_type +
'}';
}
}
private static class OpcodeInstance {
public int position;
public Opcode opcode;
public BigInteger immediate;
// only used for br_table targets
public int[] targets;
// some opcodes (e.g. IF) have an immediate result type
public LanguageType immediateResultType;
public boolean isBlockType() {
return Opcode.isBlockType(opcode);
}
@Override
public String toString() {
return "OpcodeInstance{" +
"position=" + position +
", opcode=" + opcode +
", immediate=" + immediate +
", immediateResultType=" + immediateResultType +
(targets != null ? (", targets=" + Arrays.toString(targets)) : "") +
'}';
}
}
public enum LanguageType {
I32(0x7f),
I64(0x74),
ANYFUNC(0x70),
FUNC(0x60),
BLOCKTYPE(0x40);
public final int code;
LanguageType(int code) {
this.code = code;
}
public static LanguageType getLanguateTypeIgnoreCase(String name) {
return EnumUtils.getEnumIgnoreCase(LanguageType.class, name);
}
}
public enum Opcode {
UNREACHABLE(0x00, 0),
BLOCK(0x02, 0),
LOOP(0x03, 0),
IF(0x04, -1),
ELSE(0x05, 0),
BR(0x0C, 0),
BR_IF(0x0D, -1),
BR_TABLE(0x0E, -1),
RETURN(0x0F, 0),
DROP(0x1A, -1),
SELECT(0x1B, -2),
GET_GLOBAL(0x17, +1),
SET_GLOBAL(0x18, -1),
GET_LOCAL(0x20, +1),
SET_LOCAL(0x21, -1),
TEE_LOCAL(0x22, 0),
CURRENT_MEMORY(0x3F, +1),
GROW_MEMORY(0x40, 0),
CONSTI32(0x41, +1),
CONSTI64(0x42, +1),
ADDI32(0x6A, -1),
SUBI32(0x6B, -1),
MULI32(0x6C, -1),
EQZI32(0x45, 0),
EQI32(0x46, -1),
NEI32(0x47, -1),
LT_SI32(0x48, -1),
LT_UI32(0x49, -1),
GT_SI32(0x4A, -1),
GT_UI32(0x4B, -1),
LE_SI32(0x4C, -1),
LE_UI32(0x4D, -1),
GE_SI32(0x4E, -1),
GE_UI32(0x4F, -1),
EQI64(0x51, -1),
NEI64(0x52, -1),
DIV_UI32(0x6E, -1),
ANDI32(0x71, -1),
ORI32(0x72, -1),
XORI32(0x73, -1),
SHLI32(0x74, -1),
SHR_UI32(0x76, -1),
ANDI64(0x83, -1),
ORI64(0x84, -1),
XORI64(0x85, -1),
SHLI64(0x86, -1),
SHR_UI64(0x88, -1),
END(0x0B, 0),
END_FUNCTION(0x10B, 0), // custom opcode in order to differentiate between function end and normal end
LOADI32(0x28, 0),
LOADI64(0x29, 0),
LOAD8_UI32(0x2D, 0),
STOREI32(0x36, -2),
STOREI64(0x37, -2),
STORE8I32(0x3A, -2),
STORE16I32(0x3B, -2),
WRAP_I64(0xA7, 0),
CALL(0x10, 999), // placeholder value since CALL has a dynamic stack modification
CALL_INDIRECT(0x11, 999),
// EEI, custom opcodes starting at 0x200
EEI_GETADDRESS(0x200, -1),
EEI_GETEXTERNALBALANCE(0x201, -2),
EEI_GETBLOCKHASH(0x202, -1),
EEI_GETCALLDATASIZE(0x203, +1),
EEI_GETCALLER(0x204, -1),
EEI_GETCALLVALUE(0x205, -1),
EEI_GETCODESIZE(0x206, +1),
EEI_GETBLOCKCOINBASE(0x207, -1),
EEI_GETBLOCKDIFFICULTY(0x208, -1),
EEI_GETEXTERNALCODESIZE(0x209, 0),
EEI_GETGASLEFT(0x20A, +1),
EEI_GETBLOCKGASLIMIT(0x20B, +1),
EEI_GETTXGASPRICE(0x20C, -1),
EEI_GETBLOCKNUMBER(0x20D, +1),
EEI_GETTXORIGIN(0x20E, -1),
EEI_GETRETURNDATASIZE(0x20F, +1),
EEI_GETBLOCKTIMESTAMP(0x210, +1),
EEI_CODECOPY(0x211, -3),
EEI_EXTERNALCODECOPY(0x212, -4),
EEI_RETURNDATACOPY(0x213, -3),
EEI_CALLDATACOPY(0x214, -3),
EEI_STORAGESTORE(0x215, -2),
EEI_STORAGELOAD(0x216, -2),
EEI_CALL(0x217, -4),
EEI_CALLCODE(0x218, -4),
EEI_CALLDELEGATE(0x219, -3),
EEI_CALLSTATIC(0x21A, -3),
EEI_FINISH(0x21B, -2),
EEI_REVERT(0x21C, -2),
EEI_USEGAS(0x21D, -1),
EEI_LOG(0x21E, -7),
EEI_SELFDESTRUCT(0x21F, -1),
EEI_CREATE(0x220, -4);
public final int code;
// specifies how the value stack is changed (e.g. const is +1 since a value is pushed onto the stack
private final int stackModification;
Opcode(int code, int stackModification) {
this.code = code;
this.stackModification = stackModification;
}
public static Opcode getOpcode(int code) {
for (Opcode opcode : Opcode.values()) {
if (opcode.code == code) {
return opcode;
}
}
return null;
}
public static Opcode getOpcode(String name) {
return getOpcode(name, null);
}
public static Opcode getOpcode(String name, LanguageType type) {
Opcode foundOpcode = null;
// some operations contain a "/" in the name which cannot be used as enum name
String cleanName = name.replace("/", "_");
foundOpcode = EnumUtils.getEnumIgnoreCase(Opcode.class, cleanName);
if (foundOpcode == null) {
foundOpcode = EnumUtils.getEnumIgnoreCase(Opcode.class, cleanName + type);
}
if (foundOpcode == null) {
throw new UnsupportedOperationException("The opcode " + name.toUpperCase() + " (" + type + ") is currently not supported.");
}
return foundOpcode;
}
/**
* Returns the stack modification value or null if opcode updates the stack height dynamically.
* For example CALL dynamically reduces the value stack height based on the number or parameters of the target function.
*
* @param opcode the opcode
* @return stack modification value or null
*/
public static Integer getStackModificationIfNonDynamic(Opcode opcode) {
if (opcode.stackModification == 999) {
return null;
} else {
return opcode.stackModification;
}
}
/**
* Checks whether the given opcode is of type BLOCK, LOOP or IF
*
* @param opcode the opcode to check
* @return true if block type, false otherwise
*/
public static boolean isBlockType(Opcode opcode) {
List<Opcode> blockTypeOpcodes = Arrays.asList(Opcode.LOOP, Opcode.BLOCK, Opcode.IF);
return blockTypeOpcodes.contains(opcode);
}
}
/**
* Parses the contract at the provided path and returns the new Contract object.
* The supported format of a contract is currently limited to the the output of the wasm2json tool
* (https://github.com/ewasm/wasm-json-toolkit).
*
* @param path file path of the json contract
* @return contract object
* @throws IOException
*/
private static Contract parseContract(String path) throws IOException {
String source = new String(Files.readAllBytes(Paths.get(path)));
JsonArray jsonContract = new JsonParser().parse(source).getAsJsonArray();
Contract contract = new Contract();
// function types
JsonArray functionTypes = getSection(jsonContract, "function").get("entries").getAsJsonArray();
contract.functionTypeIndices = new ArrayList<>();
for (JsonElement functionTypeInt : functionTypes) {
contract.functionTypeIndices.add(functionTypeInt.getAsInt());
}
// custom types
JsonArray customTypes = getSection(jsonContract, "type").get("entries").getAsJsonArray();
contract.customTypes = new CustomType[customTypes.size()];
for (int i = 0; i < customTypes.size(); i++) {
JsonObject currentType = customTypes.get(i).getAsJsonObject();
List<LanguageType> parameters = new ArrayList<>();
for (JsonElement typeJsonElement : currentType.get("params").getAsJsonArray()) {
String typeString = typeJsonElement.getAsString();
parameters.add(LanguageType.getLanguateTypeIgnoreCase(typeString));
}
LanguageType return_type = null;
if (currentType.has("return_type")) {
return_type = LanguageType.getLanguateTypeIgnoreCase(currentType.get("return_type").getAsString());
}
contract.customTypes[i] = new CustomType(i, parameters, return_type);
}
// main function index
JsonArray exports = getSection(jsonContract, "export").get("entries").getAsJsonArray();
for (JsonElement export : exports) {
if (export.getAsJsonObject().get("kind").getAsString().equals("function")) {
// only the main function is exported
contract.mainFunctionIndex = export.getAsJsonObject().get("index").getAsInt();
}
}
// imported EEI function indices
JsonObject imports = getSection(jsonContract, "import");
if (imports != null) {
int currentFunctionIndex = 0; // functions start at index 0 and no other function is parsed at this point
JsonArray importArray = imports.get("entries").getAsJsonArray();
for (JsonElement importElem : importArray) {
if (importElem.getAsJsonObject().get("kind").getAsString().equals("function") && importElem.getAsJsonObject().get("moduleStr").getAsString().equals("ethereum")) {
String name = importElem.getAsJsonObject().get("fieldStr").getAsString();
contract.functionTypeIndices.add(currentFunctionIndex, importElem.getAsJsonObject().get("type").getAsInt());
contract.eeiFunctions.put(Opcode.getOpcode("EEI_" + name), currentFunctionIndex);
currentFunctionIndex++;
}
}
}
// in WASM imported functions occupy indices before the functions defined in the contract
// because of that empty function bodies are added to the function list so that accessing a specific index matches the real fucntion
for (int i = 0; i < contract.eeiFunctions.size(); i++) {
contract.functions.add(new ArrayList<>());
}
// function bodies
int pc = 0;
int functionIndex = 0;
JsonArray functionBodies = getSection(jsonContract, "code").get("entries").getAsJsonArray();
for (JsonElement functionBody : functionBodies) {
ArrayList<OpcodeInstance> opcodeInstances = new ArrayList<>();
JsonArray jsonInstructions = functionBody.getAsJsonObject().get("code").getAsJsonArray();
// transform function end opcodes to custom end_function opcodes
JsonObject end = jsonInstructions.get(jsonInstructions.size() - 1).getAsJsonObject();
if (end.get("name").getAsString().equals("end")) {
end.addProperty("name", "end_function");
end.addProperty("immediates", functionIndex + contract.eeiFunctions.size());
jsonInstructions.set(jsonInstructions.size() - 1, end);
}
for (JsonElement jsonInstruction : jsonInstructions) {
JsonObject currentInstruction = jsonInstruction.getAsJsonObject();
OpcodeInstance parsedOpcodeInstance = new OpcodeInstance();
LanguageType returnType = null;
if (currentInstruction.has("return_type")) {
returnType = EnumUtils.getEnumIgnoreCase(LanguageType.class, currentInstruction.get("return_type").getAsString());
}
parsedOpcodeInstance.opcode = Opcode.getOpcode(currentInstruction.get("name").getAsString(), returnType);
if (currentInstruction.has("immediates")) {
JsonElement immediate = currentInstruction.get("immediates");
if (immediate.isJsonPrimitive()) {
if (LanguageType.getLanguateTypeIgnoreCase(immediate.getAsString()) != null) {
// control structures have the result type in the immediate field
parsedOpcodeInstance.immediateResultType = LanguageType.getLanguateTypeIgnoreCase(immediate.getAsString());
} else if (immediate.getAsString().equals("block_type")) {
// do nothing for now
} else {
parsedOpcodeInstance.immediate = immediate.getAsBigInteger();
}
} else {
// store with offset, call_indirect with index, and br_table with targets
if (immediate.getAsJsonObject().get("offset") != null) {
parsedOpcodeInstance.immediate = immediate.getAsJsonObject().get("offset").getAsBigInteger();
} else if (immediate.getAsJsonObject().get("index") != null) {
parsedOpcodeInstance.immediate = immediate.getAsJsonObject().get("index").getAsBigInteger();
} else if (immediate.getAsJsonObject().get("targets") != null) {
JsonArray targetsJsonArray = immediate.getAsJsonObject().get("targets").getAsJsonArray();
parsedOpcodeInstance.targets = new int[targetsJsonArray.size() + 1];
for (int i = 0; i < targetsJsonArray.size(); i++) {
parsedOpcodeInstance.targets[i] = targetsJsonArray.get(i).getAsInt();
}
parsedOpcodeInstance.targets[parsedOpcodeInstance.targets.length - 1] = immediate.getAsJsonObject().get("defaultTarget").getAsInt();
}
}
}
parsedOpcodeInstance.position = pc;
// if instruction is a call to an EEI function, translate to custom opcode
if (parsedOpcodeInstance.opcode == Opcode.CALL && contract.eeiFunctions.containsValue(parsedOpcodeInstance.immediate.intValue())) {
OpcodeInstance eeiOpcodeInstance = new OpcodeInstance();
// values (function index) of eeiFunctions are unique so the matching key can always be found
int parsedOpcodeInstanceImmediate = parsedOpcodeInstance.immediate.intValue();
eeiOpcodeInstance.opcode = contract.eeiFunctions.entrySet().stream().filter(e -> e.getValue().equals(parsedOpcodeInstanceImmediate)).findFirst().get().getKey();
eeiOpcodeInstance.position = parsedOpcodeInstance.position;
parsedOpcodeInstance = eeiOpcodeInstance;
}
opcodeInstances.add(parsedOpcodeInstance);
pc++;
}
contract.functions.add(opcodeInstances);
functionIndex++;
}
// fill result types off CALL instances since they do not contain the result type as immediate in the json file
// this step could potentially be moved to a different stage in the contract parsing procedure
for (List<OpcodeInstance> function : contract.functions) {
for (OpcodeInstance opcodeInstance : function) {
if (opcodeInstance.opcode == Opcode.CALL) {
LanguageType return_type = contract.getCustomTypeOfFunction(opcodeInstance.immediate.intValue()).return_type;
if (return_type != null) {
opcodeInstance.immediateResultType = return_type;
}
}
}
}
// initial memory size
JsonObject memorySection = getSection(jsonContract, "memory");
contract.initialMemorySize = memorySection.get("entries").getAsJsonArray().get(0).getAsJsonObject().get("intial").getAsInt() * PAGESIZE;
// globals
JsonObject globalSection = getSection(jsonContract, "global");
if (globalSection != null) {
JsonArray globals = globalSection.get("entries").getAsJsonArray();
for (JsonElement global : globals) {
contract.globals.add(global.getAsJsonObject().get("init").getAsJsonObject().get("immediates").getAsBigInteger());
}
}
// table
JsonObject tableSection = getSection(jsonContract, "table");
if (tableSection != null) {
// only one table is currently allowed in WASM
JsonObject table = tableSection.get("entries").getAsJsonArray().get(0).getAsJsonObject();
int size = table.get("limits").getAsJsonObject().get("intial").getAsInt();
contract.table = new Integer[size];
}
// table elements
JsonObject elementSection = getSection(jsonContract, "element");
if (elementSection != null) {
JsonArray elementsEntries = elementSection.get("entries").getAsJsonArray();
for (JsonElement elementEntry : elementsEntries) {
int offset = elementEntry.getAsJsonObject().get("offset").getAsJsonObject().get("immediates").getAsInt();
JsonArray elements = elementEntry.getAsJsonObject().get("elements").getAsJsonArray();
for (int tableOffset = offset, elementOffset = 0; elementOffset < elements.size(); tableOffset++, elementOffset++) {
contract.table[tableOffset] = elements.get(elementOffset).getAsInt();
}
}
}
// memory data
JsonObject dataSection = getSection(jsonContract, "data");
if (dataSection != null) {
JsonArray segments = dataSection.get("entries").getAsJsonArray();
for (JsonElement segment : segments) {
int offset = segment.getAsJsonObject().get("offset").getAsJsonObject().get("immediates").getAsInt();
JsonArray dataElements = segment.getAsJsonObject().get("data").getAsJsonArray();
for (JsonElement dataElement : dataElements) {
int value = dataElement.getAsInt();
contract.memoryData.put(offset, value);
offset++;
}
}
}
contract.generateHelperCollections();
return contract;
}
private static JsonObject getSection(JsonArray jsonContract, String sectionName) {
JsonObject section = null;
for (JsonElement element : jsonContract) {
JsonObject currentSection = element.getAsJsonObject();
if (currentSection.get("name").getAsString().equals(sectionName)) {
section = currentSection;
break;
}
}
return section;
}
} | [
"e1427164@student.tuwien.ac.at"
] | e1427164@student.tuwien.ac.at |
84800de062c59df91428f7e18a399c86b3ef1b49 | 09c65870df07b43660058dedf826afd772068e52 | /Java Lab6/src/peer/Peer.java | a5f4cb707d06de344a048212b4984d45fb61401d | [] | no_license | RTurkiewicz/Java | e19416976a2784d1d477331685bb437805cc22d0 | fc4ddee08f2861210517f26195b40ad763dca1ed | refs/heads/master | 2020-03-18T20:32:38.447077 | 2018-05-29T00:55:57 | 2018-05-29T00:55:57 | 135,222,807 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,412 | java | package peer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Scanner;
import iremote.IPeer;
import iremote.IStorehouse;
public class Peer extends UnicastRemoteObject implements IPeer {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public boolean acceptFileChunk(String fileName, String partText, int part) throws RemoteException {
fileChunks.put(fileName, part);
File file = new File("C:\\Users\\Argon\\Desktop\\PwjJ-lab6\\Communication data\\" + id + "\\File chunks\\" + fileName);
file.getParentFile().mkdirs();
try {
FileWriter fileWriter = new FileWriter(file, false);
fileWriter.write(partText);
fileWriter.close();
} catch (IOException e) {
System.out.print("Peer couldn't write accepted filechunk on disc.\n\n");
return false;
}
return true;
}
@Override
public String getFileChunk(String fileName) throws RemoteException {
File file = new File("C:\\Users\\Argon\\Desktop\\PwjJ-lab6\\Communication data\\"
+ id +"\\File chunks\\" + fileName);
Scanner fileScanner;
try {
fileScanner = new Scanner(file);
String partText = fileScanner.useDelimiter("\\A").next();
fileScanner.close();
return partText;
} catch (FileNotFoundException e) {
System.out.println("Node was asked to send a chunk of file it should have but doesn't. The chunk must have been manualy removed from the folder, check it.\n\n");
}
return chunkOfFileNotPresentTag;
}
public Peer(String id) throws RemoteException {
super();
this.id = id;
}
public static void main(String[] args) {
System.out.print("Enter desired peer's name (id): ");
Scanner consoleReader = new Scanner(System.in);
String id = consoleReader.nextLine();
System.out.println();
Peer peer;
Registry registry;
try {
peer = new Peer(id);
registry = LocateRegistry.getRegistry(port);
} catch (RemoteException e1) {
System.out.print("A RemoteException occured during peer's creation or export.\n\n");
consoleReader.close();
return;
}
boolean continueExecution = true;
do {
try {
peer.printMenu();
int choice;
try {
choice = consoleReader.nextInt();
consoleReader.nextLine();
} catch (InputMismatchException e) {
choice = 4;
}
switch (choice) {
case 1:
peer.manageRegistered(registry, consoleReader);
break;
case 2:
if (peer.isRegistered)
peer.printInfo();
break;
case 3:
if (peer.isRegistered)
peer.uploadFile(consoleReader);
break;
case 4:
if (peer.isRegistered)
peer.downloadFile(registry, consoleReader);
break;
case 0:
System.out.print("Thank you for your contribution. Farewell.\n\n");
continueExecution = false;
break;
default:
System.out.print("Not an option.\n\n");
break;
}
} catch (RemoteException e) {
System.out.print("A RemoteException occured when trying to connect.\n\n");
}
} while (continueExecution);
consoleReader.close();
}
private void printMenu() {
if (isRegistered)
System.out.print(registeredMenu);
else
System.out.print(unregisteredMenu);
}
private void manageRegistered(Registry registry, Scanner consoleReader) throws RemoteException {
if (isRegistered) {
storehouseStub.unregisterNode(id);
try {
Naming.unbind(ipURL + id);
} catch (NotBoundException e) {
e.printStackTrace();
return;
} catch (MalformedURLException e) {
System.out.print("ipURL specified in application for peers is wrong.\n\n");
return;
}
System.out.println("Peer: " + id + " unbound\n\n");
}
else {
if (firstRun) {
try {
storehouseStub = (IStorehouse) registry.lookup("Storehouse");
} catch (NotBoundException e) {
System.out.print("Peer could not be registered because the storehouse is unbound.\n\n");
return;
}
firstRun = false;
}
try {
while (!storehouseStub.registerNode(id)) {
System.out.print("Storehouse alread have a node registered for that id.\nEnter another id: ");
id = consoleReader.nextLine();
}
Naming.rebind(ipURL + id, this);
System.out.print("\n\n");
} catch (MalformedURLException e) {
System.out.print("ipURL specified in application for peers is wrong.\n\n");
storehouseStub.unregisterNode(id);
return;
}
System.out.println("Peer: " + id + " bound\n\n");
}
isRegistered = !isRegistered;
}
private void uploadFile(Scanner consoleReader) {
System.out.println(fileNameQuestion);
String fileName = consoleReader.nextLine();
File file = new File(fileName);
try {
Scanner fileScanner = new Scanner(file);
String fileText = fileScanner.useDelimiter("\\A").next();
fileScanner.close();
if (storehouseStub.uploadFile(fileName, fileText))
System.out.println("File has been uploaded to storehouse.\n\n");
else
System.out.println("File was not uploaded to storehouse because either the number of peers is to small,\n"
+ "a file of specified name has already been uploaded\nor one of the peers was unbound.\n\n");
} catch (FileNotFoundException e) {
System.out.print("Wrong name of file.\n\n");
} catch (RemoteException e) {
System.out.print("File could not be uploaded because the storehouse has been unbound.\n\n");
}
}
private void downloadFile(Registry registry, Scanner consoleReader) throws RemoteException {
System.out.println(fileNameQuestion);
String fileName = consoleReader.nextLine();
ArrayList<String> peersForFile = storehouseStub.getPeersForFile(fileName);
if (peersForFile.isEmpty()) {
System.out.println(noSuchFileAnswer);
return;
}
IPeer firstPiecePeerStub;
IPeer secondPiecePeerStub;
IPeer thirdPiecePeerStub;
try {
firstPiecePeerStub = (IPeer) registry.lookup(peersForFile.get(0));
secondPiecePeerStub = (IPeer) registry.lookup(peersForFile.get(1));
thirdPiecePeerStub = (IPeer) registry.lookup(peersForFile.get(2));
} catch (NotBoundException e1) {
System.out.print("File could not be downloaded because one of peers containing filechunks has been unbounds.\n\n");
return;
} catch (RemoteException e) {
System.out.print("File could not be downloaded because this peer couldn't connect to one of the peers containing filechunks.\n\n");
return;
}
String fileText = firstPiecePeerStub.getFileChunk(fileName)
+ secondPiecePeerStub.getFileChunk(fileName)
+ thirdPiecePeerStub.getFileChunk(fileName);
if (fileText.contains(chunkOfFileNotPresentTag)) {
System.out.print("One of the peers does not have chunk of file it should have.\n"
+ "The chunk must have been manually removed from the folder.\n\n");
return;
}
File file = new File("C:\\Users\\Argon\\Desktop\\PwjJ-lab6\\Communication data\\"
+ id +"\\Downloaded files\\" + fileName);
file.getParentFile().mkdirs();
try {
FileWriter fileWriter = new FileWriter(file, false);
fileWriter.write(fileText);
fileWriter.close();
System.out.print("File has been downloaded.\n\n");
} catch (IOException e) {
System.out.print("Writing downloaded file on disc ended with failure.\n\n");
}
}
private void printInfo() {
System.out.println("Node's id: " + id);
if (fileChunks.isEmpty())
System.out.print("This node contains no filechunks.\n\n");
else {
System.out.println("Chunks of files this peers contains.\nfile's name, number of chunk's part");
for (String fileName : fileChunks.keySet())
System.out.println("\t" + fileName + " ," + fileChunks.get(fileName));
System.out.print("\n\n");
}
}
boolean firstRun = true;
IStorehouse storehouseStub;
private String id;
private boolean isRegistered = false;
private Map<String, Integer> fileChunks= new HashMap<String, Integer>();
private static final String unregisteredMenu = "***Choose action***\n"
+ "[1] Register node\n"
+ "[0] End session\n"
+ "*************\n\n";
private static final String registeredMenu = "***Choose action***\n"
+ "[1] Unregister node\n"
+ "[2] Print node's info\n"
+ "[3] Upload file\n"
+ "[4] Download file\n"
+ "[0] End session\n"
+ "*************\n\n";
private static final String fileNameQuestion = "Please enter file's name: ";
private static final String noSuchFileAnswer = "Storehouse does not have such a file registered.\n\n";
private static String chunkOfFileNotPresentTag = "<!ChunkOfFileWasNotPresentError!>";
private static int port = 1099;
private static String ipURL = "//localhost:" + port + "/";
}
| [
"rturkiewicz222389@e-science.pl"
] | rturkiewicz222389@e-science.pl |
31f7f1edcd37f5e04828bbf24afc6a01451ea996 | fa1725d0ea1b78a2405b1ba3ca5e9c09cafd0914 | /src/main/java/com/coumtri/config/MongoConfig.java | e780904ef5fa2f0ff70b881599c0e69304ffe5d5 | [] | no_license | Coumtri/test-project-web | 62ce3d8c25a4cf7a346c90894ad9848f2569e108 | fd8af70f17010a647b7bc75a3478114421a02440 | refs/heads/master | 2021-01-20T02:16:48.616646 | 2015-08-20T15:16:11 | 2015-08-20T15:16:11 | 40,540,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,603 | java | package com.coumtri.config;
import java.net.UnknownHostException;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoTypeMapper;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
@Configuration
class MongoConfig {
@Bean
public MongoDbFactory mongoDbFactory() throws UnknownHostException {
return new SimpleMongoDbFactory(new Mongo(), "projet-test-web");
}
@Bean
public MongoTemplate mongoTemplate() throws UnknownHostException {
MongoTemplate template = new MongoTemplate(mongoDbFactory(), mongoConverter());
return template;
}
@Bean
public MongoTypeMapper mongoTypeMapper() {
return new DefaultMongoTypeMapper(null);
}
@Bean
public MongoMappingContext mongoMappingContext() {
return new MongoMappingContext();
}
@Bean
public MappingMongoConverter mongoConverter() throws UnknownHostException {
MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), mongoMappingContext());
converter.setTypeMapper(mongoTypeMapper());
return converter;
}
}
| [
"julienlac@gmail.com"
] | julienlac@gmail.com |
fd060f2f50ce25d7ac2afa59eb6e970d60f8a6f0 | dd304876be35e3acaa485bad2dc014ce8a186653 | /src/collections/examples/list/MyOwnTestSystem.java | 4f9dd8b301373ef13f1683226b4aaf8c90374abe | [] | no_license | OvidijusKutkaitis/1Paskaita1Projektas | ec9f9ab73723965b5de72636d55d5a9577b96cc8 | 56fd27998128724bb07f35335761e9882708fb54 | refs/heads/master | 2021-09-06T16:14:00.859779 | 2018-02-08T12:57:37 | 2018-02-08T12:57:37 | 120,007,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,982 | java | package collections.examples.list;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Array;
import java.util.*;
public class MyOwnTestSystem {
public static void main(String[]args){
MyOwnTestSystem myOwnTestSystem = new MyOwnTestSystem();
Map<Integer,Question> questionMap = myOwnTestSystem.readQuestions();
List<Integer> questions = new ArrayList<>();
/*for(Integer key : questionMap.keySet()){
Question q = questionMap.get(key);
System.out.println(q.getQuestionText());
for(String v : q.getVariantas()){
System.out.println(v);
}
}*/
Scanner sc = new Scanner(System.in);
int correctAnswerCount = 0;
for(int i = 0; i < 10; i++){
int numb;
while(true){
Random random = new Random();
numb = random.nextInt(questionMap.size())+1;
if(!questions.contains(numb)){
break;
}
}
questions.add(numb);
/*Random random = new Random();//naudojama generuoti random skaiciu
int numb = random.nextInt(questionMap.size()) +1;//grazina skaicius random nuo 1 iki map ilgio
if(questions.contains(numb)){
}*/
Question question = questionMap.get(numb);
System.out.println(question.getQuestionText());
for(String variant : question.getVariantas()){
System.out.println(variant);
}
System.out.println("Iveskite savo pasirinkta atsakymo varianta >>");
int userAnswer = sc.nextInt();
if(userAnswer == question.getAnswer()){
correctAnswerCount++;
}
}
System.out.println("Jusu balas yra ----" + correctAnswerCount + "----");
}
private Map<Integer,Question> readQuestions(){
Map<Integer, Question> questionMap = new HashMap<>();
try {
BufferedReader bf = new BufferedReader(new FileReader(new File("questions.txt")));
String line;
int key = 1;
while((line = bf.readLine()) != null){ //skaitome po eilute is failo
String[] items = line.split(";"); // isskaidom per ;
String[] examples = items[1].split(" "); // isskaidom variantus per tarpa
List<String> myItems = Arrays.asList(examples);// sudedame visus variantus i listas untils pagalba
int answer = Integer.valueOf(items[2].trim()); // convertuojame ats is String into Integer remove all empty space
Question question = new Question(items[0],myItems,answer);// sudedame itemus i objekta
questionMap.put(key++, question);
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return questionMap;
}
}
| [
"o.kutkaitis@gmail.com"
] | o.kutkaitis@gmail.com |
ba60e0858acf383834dff791446db178fe36ce1c | 302b1d8a6d2b848d54ca82dfb1393a496b5dd3f6 | /Sample_Test/src/com/maintestprograms/SumOfElementts.java | 30b8e15a8e0c14c05edcdb3678a3f52134d2d78c | [] | no_license | PoorvaGaddale/Backup2 | 924c5bd493eb9816b458c7593022beadb3716f88 | c118708458cafcee0199bee273ee5761074f7eb4 | refs/heads/master | 2023-05-14T07:01:58.134160 | 2021-03-29T10:48:49 | 2021-03-29T10:48:49 | 203,967,089 | 0 | 0 | null | 2023-05-09T18:52:34 | 2019-08-23T09:25:04 | HTML | UTF-8 | Java | false | false | 344 | java | package com.maintestprograms;
public class SumOfElementts {
public static void main(String[] args) {
int[] a = {1,5,8,4,5};
int sum=sumArray(a);
System.out.println(sum);
}
private static int sumArray(int[] a) {
int sum=0;
for (int i = 0; i < a.length; i++) {
sum=sum+a[i];
}
return sum;
}
}
| [
"noreply@github.com"
] | PoorvaGaddale.noreply@github.com |
7ce7d75837b9a4146aea86cbd9199ef3a3a4360f | ae5eb1a38b4d22c82dfd67c86db73592094edc4b | /project236/src/test/java/org/gradle/test/performance/largejavamultiproject/project236/p1181/Test23635.java | 1f38c161c011bc1191ebda500b3740f579f8e05f | [] | no_license | big-guy/largeJavaMultiProject | 405cc7f55301e1fd87cee5878a165ec5d4a071aa | 1cd6a3f9c59e9b13dffa35ad27d911114f253c33 | refs/heads/main | 2023-03-17T10:59:53.226128 | 2021-03-04T01:01:39 | 2021-03-04T01:01:39 | 344,307,977 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,113 | java | package org.gradle.test.performance.largejavamultiproject.project236.p1181;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test23635 {
Production23635 objectUnderTest = new Production23635();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | [
"sterling.greene@gmail.com"
] | sterling.greene@gmail.com |
62695f503ce91afa5c5c212e6290d2e4b9431aee | 40d844c1c780cf3618979626282cf59be833907f | /src/testcases/CWE598_Information_Exposure_QueryString/CWE598_Information_Exposure_QueryString__Servlet_02.java | d7586ea0950f05c810a2e95e59bb8858bfcb83fd | [] | no_license | rubengomez97/juliet | f9566de7be198921113658f904b521b6bca4d262 | 13debb7a1cc801977b9371b8cc1a313cd1de3a0e | refs/heads/master | 2023-06-02T00:37:24.532638 | 2021-06-23T17:22:22 | 2021-06-23T17:22:22 | 379,676,259 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,590 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE598_Information_Exposure_QueryString__Servlet_02.java
Label Definition File: CWE598_Information_Exposure_QueryString__Servlet.label.xml
Template File: point-flaw-02.tmpl.java
*/
/*
* @description
* CWE: 598 Information Exposure Through Query Strings in GET Request
* Sinks:
* GoodSink: post password field
* BadSink : get password field
* Flow Variant: 02 Control flow: if(true) and if(false)
*
* */
package testcases.CWE598_Information_Exposure_QueryString;
import testcasesupport.*;
import javax.servlet.http.*;
public class CWE598_Information_Exposure_QueryString__Servlet_02 extends AbstractTestCaseServlet
{
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
if (true)
{
response.getWriter().println("<form id=\"form\" name=\"form\" method=\"get\" action=\"password-test-servlet\">"); /* FLAW: method should be post instead of get */
response.getWriter().println("Username: <input name=\"username\" type=\"text\" tabindex=\"10\" /><br><br>");
response.getWriter().println("Password: <input name=\"password\" type=\"password\" tabindex=\"10\" />");
response.getWriter().println("<input type=\"submit\" name=\"submit\" value=\"Login-bad\" /></form>");
}
}
/* good1() changes true to false */
private void good1(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
if (false)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
IO.writeLine("Benign, fixed string");
}
else
{
response.getWriter().println("<form id=\"form\" name=\"form\" method=\"post\" action=\"password-test-servlet\">"); /* FIX: method set to post */
response.getWriter().println("Username: <input name=\"username\" type=\"text\" tabindex=\"10\" /><br><br>");
response.getWriter().println("Password: <input name=\"password\" type=\"password\" tabindex=\"10\" />");
response.getWriter().println("<input type=\"submit\" name=\"submit\" value=\"Login-good\" /></form>");
}
}
/* good2() reverses the bodies in the if statement */
private void good2(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
if (true)
{
response.getWriter().println("<form id=\"form\" name=\"form\" method=\"post\" action=\"password-test-servlet\">"); /* FIX: method set to post */
response.getWriter().println("Username: <input name=\"username\" type=\"text\" tabindex=\"10\" /><br><br>");
response.getWriter().println("Password: <input name=\"password\" type=\"password\" tabindex=\"10\" />");
response.getWriter().println("<input type=\"submit\" name=\"submit\" value=\"Login-good\" /></form>");
}
}
public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
good1(request, response);
good2(request, response);
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
| [
"you@example.com"
] | you@example.com |
b7ea6f8dbe503c8fd1b91f81d4c8eb9aa6c0933e | d07e9bc560669e72f48c739f13511cf8916a07b4 | /wing/src/qa/pom/contact/ContacDetails.java | be96367e269a475deb3145ad81b7ad2872c1720d | [] | no_license | keshavhg4742/bingo | 95635aa4a7485ff4abf5aa7475dae67d54f8cb3c | 83fe5d5204934c404fc6cfe87a0e2c8c94f3965d | refs/heads/master | 2021-06-25T15:01:30.935524 | 2019-11-08T15:44:25 | 2019-11-08T15:44:25 | 220,497,480 | 0 | 0 | null | 2021-04-26T19:40:38 | 2019-11-08T15:42:23 | Java | UTF-8 | Java | false | false | 2,568 | java | package qa.pom.contact;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class ContacDetails {
@FindBy(name="property(First Name)")
private WebElement firstName;
@FindBy(name="property(Last Name)")
private WebElement lastName;
@FindBy(xpath="//img[@title='Vendor Name Lookup']")
private WebElement vendor;
@FindBy(xpath="//a[text()='girish']")
private WebElement vendTxt;
@FindBy(xpath="//img[@title='Account Name Lookup']")
private WebElement accName;
@FindBy(xpath="//a[contains(text(),'QSpiders Bull Temple')]")
private WebElement text;
@FindBy(name="property(Email)")
private WebElement email;
@FindBy(xpath="//input[@name='property(Department)']")
private WebElement dept;
@FindBy(name="property(Mobile)")
private WebElement mob;
@FindBy(name="property(Mailing Street)")
private WebElement street;
@FindBy(name="property(Mailing City)")
private WebElement city;
@FindBy(name="property(Mailing State)")
private WebElement state;
@FindBy(name="property(Mailing Zip)")
private WebElement zip;
@FindBy(name="property(Mailing Country)")
private WebElement country;
@FindBy(id="copyAddress")
private WebElement copyAddr;
@FindBy(xpath="(//input[@name='Button'])[3]")
private WebElement clickSave;
public ContacDetails(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void setFirstName(String fname ) {
firstName.sendKeys(fname);
}
public void setLastName(String lname) {
lastName.sendKeys(lname);
}
public void setAccName( ) {
accName.click();
}
public void clcikText() {
text.click();
}
public void setVendor(String acName) {
this.accName.sendKeys(acName);
}
public void clcikVend() {
vendTxt.click();
}
public void setEmail(String emails) {
email.sendKeys(emails);
}
public void setDept(String depts) {
dept.sendKeys(depts);
}
public void setMob(String mobil) {
mob.sendKeys(mobil);
}
public void setStreet(String street) {
this.street.sendKeys(street);
}
public void setCity(String city) {
this.city.sendKeys(city);
}
public void setState(String st) {
state.sendKeys(st);
}
public void setZip(String zipc) {
zip.sendKeys(zipc);
}
public void setCountry(String contr) {
country.sendKeys(contr);
}
public void copyAddr() {
copyAddr.click();
}
public void clickSave() {
clickSave.click();
}
}
| [
"keshavhg4742@gmail.com"
] | keshavhg4742@gmail.com |
59d5fa7c839dc2b9cd459f2d5e6dc2d3c378fa3f | 8854802cdbc37fe8b3637f2f493f0bade14f3170 | /server/src/main/java/cn/wyslkl/server/domain/MemberCourse.java | 6b465b0e701477f4058c9e8c980ba85d3c6a70a8 | [] | no_license | yinoob/course | 369b372fe2f90a8e7ff14ab822fc16eb455514e3 | d5ac52b269baf8ce66edfecac513c55dfd100503 | refs/heads/master | 2023-02-16T23:18:30.174859 | 2021-01-15T03:47:33 | 2021-01-15T03:47:33 | 323,412,982 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,187 | java | package cn.wyslkl.server.domain;
import java.util.Date;
public class MemberCourse {
private String id;
private String memberId;
private String courseId;
private Date at;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public Date getAt() {
return at;
}
public void setAt(Date at) {
this.at = at;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", courseId=").append(courseId);
sb.append(", at=").append(at);
sb.append("]");
return sb.toString();
}
} | [
"1243876958@qq.com"
] | 1243876958@qq.com |
c8dbdbe90d837f4e7adb2462757b898be9b4824f | b5b974c657549f2c0831f70bb40fb19c1b54058d | /src/main/java/guru/springframework/spring5webapp/bootstrap/DevBootstrap.java | 5ae823cb1cb1999fb9827b80a020cc4e5a58785e | [
"Apache-2.0"
] | permissive | paulwoods/spring5webapp | 94b3b3ad64f90d7a496dd01e4902a44c44af693f | 4e48dcd308d1a78ae96d372fb8bc047bdf59df99 | refs/heads/master | 2020-03-09T09:38:55.822050 | 2018-04-09T06:06:42 | 2018-04-09T06:06:42 | 128,717,573 | 0 | 0 | null | 2018-04-09T05:13:08 | 2018-04-09T05:11:00 | Java | UTF-8 | Java | false | false | 2,142 | java | package guru.springframework.spring5webapp.bootstrap;
import guru.springframework.spring5webapp.model.Author;
import guru.springframework.spring5webapp.model.Book;
import guru.springframework.spring5webapp.model.Publisher;
import guru.springframework.spring5webapp.repositories.AuthorRepository;
import guru.springframework.spring5webapp.repositories.BookRepository;
import guru.springframework.spring5webapp.repositories.PublisherRepository;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class DevBootstrap implements ApplicationListener<ContextRefreshedEvent> {
private AuthorRepository authorRepository;
private BookRepository bookRepository;
private PublisherRepository publisherRepository;
public DevBootstrap(
AuthorRepository authorRepository,
BookRepository bookRepository,
PublisherRepository publisherRepository
) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
this.publisherRepository = publisherRepository;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
initData();
}
private void initData() {
// Eric
Publisher harperColins = new Publisher("Harper Collins", "1234 Main Street", "Dallas", "TX", "75020");
Author eric = new Author("Eric", "Evans");
Book ddd = new Book("Domain Driven Design", "1234", harperColins);
eric.getBooks().add(ddd);
publisherRepository.save(harperColins);
authorRepository.save(eric);
bookRepository.save(ddd);
// Rod
Publisher worx = new Publisher("Worx", "1234 Main Street", "Dallas", "TX", "75020");
Author rod = new Author("Rod", "Johnson");
Book noEJB = new Book("J2EE Develoipment without EJB", "23444", worx);
rod.getBooks().add(noEJB);
publisherRepository.save(worx);
authorRepository.save(rod);
bookRepository.save(noEJB);
}
}
| [
"mr.paul.woods@gmail.com"
] | mr.paul.woods@gmail.com |
168d8b23578713336acd2bd3a34d7794640763b2 | 8e9615c26d2949cfbfb8b5e030dd67ec12a33acf | /library/common/src/main/java/com/jaydenxiao/common/commonutils/JsonUtils.java | ffeb413456aadc347d20acc56a10888aac0f6b6b | [] | no_license | 1097919195/FaceCheck | 1f0a8001dcbf2068a5e0d11e72996aff2737a6eb | 841ffb82b74dd86c7a53cd6dde09c44eab208255 | refs/heads/master | 2020-03-17T20:50:07.110563 | 2018-05-18T09:10:43 | 2018-05-18T09:10:43 | 133,930,822 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,089 | java | package com.jaydenxiao.common.commonutils;
/**
* JSON解析二次封装
*
*/
public class JsonUtils {
/*
// 采取单例模式
private static Gson gson = new Gson();
private JsonUtils() {
}
*/
/**
* @param src :将要被转化的对象
* @return :转化后的JSON串
* @MethodName : toJson
* @Description : 将对象转为JSON串,此方法能够满足大部分需求
*//*
public static String toJson(Object src) {
if (null == src) {
return gson.toJson(JsonNull.INSTANCE);
}
try {
return gson.toJson(src);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return null;
}
*/
/**
* @param json
* @param classOfT
* @return
* @MethodName : fromJson
* @Description : 用来将JSON串转为对象,但此方法不可用来转带泛型的集合
*//*
public static <T> Object fromJson(String json, Class<T> classOfT) {
try {
return gson.fromJson(json, (Type) classOfT);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return null;
}
*/
/**
* @param json
* @param typeOfT
* @return
* @MethodName : fromJson
* @Description : 用来将JSON串转为对象,此方法可用来转带泛型的集合,如:Type为 new
* TypeToken<List<T>>(){}.getType()
* ,其它类也可以用此方法调用,就是将List<T>替换为你想要转成的类
*//*
public static Object fromJson(String json, Type typeOfT) {
try {
return gson.fromJson(json, typeOfT);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return null;
}
*/
/**
* 获取json中的某个值
*
* @param json
* @param key
* @return
*//*
public static String getValue(String json, String key) {
try {
JSONObject object = new JSONObject(json);
return object.getString(key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
*/
/**
* 获取json中的list值
*
* @param json
* @return
*//*
public static String getListValue(String json) {
try {
JSONObject object = new JSONObject(json);
return object.getString("list");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Double getDoubleValue(String json, String key) {
try {
JSONObject object = new JSONObject(json);
return object.getDouble(key);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static int getIntValue(String json, String key) {
try {
JSONObject object = new JSONObject(json);
return object.getInt(key);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
*/
}
| [
"1097919195@qq.com"
] | 1097919195@qq.com |
f710953b785b2637efdcb4ec910a75f84b915c48 | a9fcc2c2cf6e4433832015e33720a61fe53506d5 | /src/test/java/com/pricingPortal/ObjectRepositary/PricingPortalOR.java | a70677661b2897cef0dd17147c7ff8def443a42c | [] | no_license | mit-patel13/Pricing_Portal_Test_UI | 4da2e25799d21e20ea4cd0063295fb7e605b79fb | cdc94ed4241e9660d95caea1badb9bd08f78419f | refs/heads/master | 2020-04-11T13:50:28.010961 | 2018-12-14T20:12:31 | 2018-12-14T20:12:31 | 161,831,787 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 741 | java | package com.pricingPortal.ObjectRepositary;
public class PricingPortalOR {
public static String priceGroupChangeSets ="//h6[text()='Price Group Change Sets']";
public static String newChangeSetbuttn ="//button/span[contains(text(),'New Change Set')]";
public static String chooseFileButtn ="//input[@id='file']";
public static String firststepbox ="//p[text()='Step 1 » Select Price Increase File']/..";
public static String excelSheetDisplayedbyClassname ="k-filter-range";
public static String datevaluebyxpath ="//kendo-dateinput//input[@class='k-input']";
public static String saveChangeSet = "//button[contains(text(),'Save')]";
public static String newProductsbuttn ="//button/span[contains(text(),' New Product')]";
}
| [
"mit.patel@accesscfa.com"
] | mit.patel@accesscfa.com |
db678e02dd1f5fa221fe78cf3132a2664fd87b5d | 6ba48d5f0e55daa7e83d52710cbcd9cbd9c98cec | /investment/src/main/java/org/naruto/framework/investment/install/InstallRequest.java | b45f6140f7e0e2a4fbf05d9dabce985db2ff0a05 | [] | no_license | naruto-kyubi/ant-community | 782390f83178c5bfbbef525b2cb4c03f446e7802 | d265cc2bae8cca861340dc82996cd1c9b6def17d | refs/heads/master | 2021-10-31T10:52:07.028414 | 2021-10-21T02:43:54 | 2021-10-21T02:43:54 | 203,084,726 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 272 | java | package org.naruto.framework.investment.install;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class InstallRequest {
private String mobileId;
private String appName;
}
| [
"64435716@qq.com"
] | 64435716@qq.com |
32179f9210c749bda9c07fde19bf28648844bf05 | f3dcd34ccf03730e7d68e96784d1557972277782 | /web/src/main/java/com/sishuok/es/sys/user/entity/UserStatusHistory.java | c41b80b6c9c641ddadd42d67d5577dd435bfcb9f | [
"Apache-2.0"
] | permissive | zhuruiboqq/romantic-factor_baseOnES | 7e2aace3e284403998f404947194e28c92893658 | 1c05bda53a36475f60989a790eca31e4ba1665bb | refs/heads/master | 2021-01-21T12:58:00.788593 | 2016-05-05T14:07:22 | 2016-05-05T14:07:22 | 49,350,203 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,853 | java | /**
* Copyright (c) 2005-2012 https://github.com/zhuruiboqq
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.sys.user.entity;
import com.sishuok.es.common.entity.BaseEntity;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.*;
import java.util.Date;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-3-11 下午3:23
* <p>Version: 1.0
*/
@Entity
@Table(name = "sys_user_status_history")
public class UserStatusHistory extends BaseEntity<Long> {
/**
* 锁定的用户
*/
@ManyToOne(fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
private User user;
/**
* 备注信息
*/
private String reason;
/**
* 操作的状态
*/
@Enumerated(EnumType.STRING)
private UserStatus status;
/**
* 操作的管理员
*/
@ManyToOne(fetch = FetchType.EAGER)
@Fetch(FetchMode.SELECT)
@JoinColumn(name = "op_user_id")
private User opUser;
/**
* 操作时间
*/
@Column(name = "op_date")
@Temporal(TemporalType.TIMESTAMP)
private Date opDate;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public User getOpUser() {
return opUser;
}
public void setOpUser(User opUser) {
this.opUser = opUser;
}
public Date getOpDate() {
return opDate;
}
public void setOpDate(Date opDate) {
this.opDate = opDate;
}
}
| [
"bzhuorui@163.com"
] | bzhuorui@163.com |
bf1785b9b092f09a9bb52d3bffdbdcd6eabe9e07 | 211883472c6874e7f66a8e815fc29ad1e8cee185 | /src/main/java/ilusr/textadventurecreator/views/action/AppendTextViewProvider.java | bbdb84e31e4bc608ddd097521189f0e0669a5317 | [
"MIT"
] | permissive | JeffreyRiggle/textadventurecreator | fb95093b1c5e2dfcb88dfe0ad133ab4351e85b5b | 72e5bb2d3530a222d756b21800d300e711752b73 | refs/heads/master | 2021-12-28T04:56:11.383213 | 2021-08-12T22:34:37 | 2021-08-12T22:34:37 | 99,678,021 | 0 | 0 | MIT | 2021-08-12T22:34:39 | 2017-08-08T09:56:44 | Java | UTF-8 | Java | false | false | 577 | java | package ilusr.textadventurecreator.views.action;
import ilusr.iroshell.core.IViewProvider;
/**
*
* @author Jeff Riggle
*
*/
public class AppendTextViewProvider implements IViewProvider<BaseActionView> {
private final AppendTextModel model;
private AppendTextView view;
/**
*
* @param model A @see AppendTextModel to use to create the view.
*/
public AppendTextViewProvider(AppendTextModel model) {
this.model = model;
}
@Override
public BaseActionView getView() {
if (view == null) {
view = new AppendTextView(model);
}
return view;
}
}
| [
"JeffreyRiggle@gmail.com"
] | JeffreyRiggle@gmail.com |
0917bb108b177a9d828632b96224af058741e89e | a26d5a62b419a648d43b4a0cd48fe0709027340a | /TP/TP2/srctp2/rtl/Call.java | ebb5f6dc9326696d859df8e3854777b1b616b86e | [] | no_license | Valoute-GS/AST_Master1_S2 | 5ffe9b9d4b71c2774a31796f7c6d246e7aea60b3 | 1b32de231504dfd92229d1f64660a0c17d4e8e5f | refs/heads/master | 2020-04-18T09:16:01.965285 | 2018-05-31T10:02:18 | 2018-05-31T10:02:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 948 | java | package rtl;
import java.util.List;
public class Call implements Instr {
public final Ident target;
private Function callee;
public final List<Operand> args;
public Call(Ident target, Function callee, List<Operand> args) {
this.target = target;
this.callee = callee;
this.args = args;
}
public Function getCallee() {
return callee;
}
public void setCallee(Function callee) {
this.callee = callee;
}
public String toString() {
String res = "";
if (target!=null) res = target.toString()+" = ";
res = res+"call "+callee.name.toString()+"("+stringOfList(args)+")";
return res;
}
public static String stringOfList(List<Operand> l) {
String res = "";
if (l.size()==0) return res;
if (l.size()==1) return l.get(0).toString();
res = l.get(0).toString();
for (int i=1;i<l.size();i++)
res = res + " " + l.get(i).toString();
return res;
}
public void accept(InstrVisitor v) {
v.visit(this);
}
}
| [
"antoine.posnic@capgemini.com"
] | antoine.posnic@capgemini.com |
7ec6c9d7fff3bf10a152d775106b13f0013e61fb | f30f8520b3c77461c4bf39d61a6796dfed51087a | /src/main/java/com/isb/dto/UserDTO.java | c9454eaa61bc7639ea188128209c62e0a07a5d1e | [] | no_license | Tsvetomil/InvestingApp-Diploma | 6d2f9fadbda5bc0818eed8ab298549ec95909609 | 1b2a70fc16433b5c699acd58c907e594c88e0a82 | refs/heads/master | 2023-08-22T13:03:30.026133 | 2021-08-29T17:10:00 | 2021-08-29T17:10:00 | 361,153,658 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,319 | java | package com.isb.dto;
import com.isb.model.User;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
@Getter
@Setter
public class UserDTO {
private long id;
private String firstName;
private String lastName;
private String email;
private String lastLogin;
private String dateOfBirth;
private boolean isAdmin;
UserDTO(){
}
public static UserDTO toDTO(User user){
UserDTO userCopy = new UserDTO();
userCopy.setId(user.getId());
userCopy.setFirstName(user.getFirstName());
userCopy.setLastName(user.getLastName());
userCopy.setEmail(user.getEmail());
userCopy.setAdmin(user.isAdmin());
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
userCopy.setDateOfBirth(user.getDateOfBirth().format(format));
} catch (NullPointerException e){
//ignore
}
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
userCopy.setLastLogin(user.getLastLogin().format(format));
} catch (NullPointerException e){
//ignore
}
return userCopy;
}
}
| [
"cvetikostov@gmail.com"
] | cvetikostov@gmail.com |
5b09ec0c95508d91d8c75b8941a727d2c08df5fc | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/21/21_d6a21d8d92e97f67dcf4c53a66804ebc11a9b2f7/XliffPushStrategyTest/21_d6a21d8d92e97f67dcf4c53a66804ebc11a9b2f7_XliffPushStrategyTest_t.java | e7bc63089be7ee3f0209ce247640e9c40f7e03c3 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 9,759 | java | package org.zanata.client.commands.push;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.zanata.client.commands.push.PushCommand.TranslationResourcesVisitor;
import org.zanata.client.config.LocaleList;
import org.zanata.client.config.LocaleMapping;
import org.zanata.rest.dto.resource.Resource;
import org.zanata.rest.dto.resource.TranslationsResource;
public class XliffPushStrategyTest
{
@Mock
private PushOptions mockPushOption;
private LocaleList locales = new LocaleList();
private XliffStrategy xliffStrategy;
private List<String> include;
private List<String> exclude;
private final File sourceDir = new File("src/test/resources/xliffDir");
private final File sourceDir2 = new File("src/test/resources/xliffDir2");
private final String sourceLocale = "en-US";
@Before
public void prepare()
{
locales.add(new LocaleMapping("de"));
locales.add(new LocaleMapping("fr"));
}
@Before
public void beforeMethod()
{
MockitoAnnotations.initMocks(this);
xliffStrategy = new XliffStrategy();
include = new ArrayList<String>();
exclude = new ArrayList<String>();
}
@Test
public void findDocNamesTest() throws IOException
{
include.add("**/**StringResource_en_US*");
when(mockPushOption.getLocaleMapList()).thenReturn(locales);
when(mockPushOption.getSourceLang()).thenReturn(sourceLocale);
when(mockPushOption.getDefaultExcludes()).thenReturn(true);
when(mockPushOption.getCaseSensitive()).thenReturn(true);
when(mockPushOption.getExcludeLocaleFilenames()).thenReturn(true);
when(mockPushOption.getValidate()).thenReturn("xsd");
xliffStrategy.setPushOptions(mockPushOption);
Set<String> localDocNames = xliffStrategy.findDocNames(sourceDir, include, exclude, mockPushOption.getDefaultExcludes(), mockPushOption.getCaseSensitive(), mockPushOption.getExcludeLocaleFilenames());
Assert.assertEquals(3, localDocNames.size());
}
@Test
public void loadSrcDocTest() throws IOException
{
include.add("**/**StringResource_en_US*");
when(mockPushOption.getTransDir()).thenReturn(sourceDir);
when(mockPushOption.getLocaleMapList()).thenReturn(locales);
when(mockPushOption.getSourceLang()).thenReturn(sourceLocale);
when(mockPushOption.getDefaultExcludes()).thenReturn(true);
when(mockPushOption.getCaseSensitive()).thenReturn(true);
when(mockPushOption.getExcludeLocaleFilenames()).thenReturn(true);
when(mockPushOption.getValidate()).thenReturn("xsd");
xliffStrategy.setPushOptions(mockPushOption);
Set<String> localDocNames = xliffStrategy.findDocNames(sourceDir, include, exclude, mockPushOption.getDefaultExcludes(), mockPushOption.getCaseSensitive(), mockPushOption.getExcludeLocaleFilenames());
List<Resource> resourceList = new ArrayList<Resource>();
for (String docName : localDocNames)
{
Resource srcDoc = xliffStrategy.loadSrcDoc(sourceDir, docName);
resourceList.add(srcDoc);
TranslationResourcesVisitor visitor = mock(TranslationResourcesVisitor.class);
LocaleMapping loc;
// each src file in test has one trans file ('de' or 'fr'):
if (srcDoc.getName().equals("dir1/StringResource"))
{
loc = new LocaleMapping("de");
}
else
{
loc = new LocaleMapping("fr");
}
xliffStrategy.visitTranslationResources(docName, srcDoc, visitor);
verify(visitor).visit(eq(loc), isA(TranslationsResource.class));
}
Assert.assertEquals(3, resourceList.size());
}
@Test
public void loadSrcDocTestWithCaseSensitiveMatch() throws IOException
{
include.add("StringResource_en*");
checkForCaseSensitiveMatches(5);
}
@Test
public void loadSrcDocTestWithCaseSensitiveMismatch() throws IOException
{
include.add("stringresource_en*");
checkForCaseSensitiveMatches(0);
}
private void checkForCaseSensitiveMatches(int matches) throws IOException
{
when(mockPushOption.getSourceLang()).thenReturn(sourceLocale);
when(mockPushOption.getLocaleMapList()).thenReturn(locales);
when(mockPushOption.getCaseSensitive()).thenReturn(true);
when(mockPushOption.getExcludeLocaleFilenames()).thenReturn(true);
when(mockPushOption.getDefaultExcludes()).thenReturn(false);
when(mockPushOption.getValidate()).thenReturn("xsd");
xliffStrategy.setPushOptions(mockPushOption);
Set<String> localDocNames = xliffStrategy.findDocNames(sourceDir2, include, exclude, mockPushOption.getDefaultExcludes(), mockPushOption.getCaseSensitive(), mockPushOption.getExcludeLocaleFilenames());
Assert.assertEquals(matches, localDocNames.size());
}
@Test
public void loadSrcDocTestWithoutCaseSensitive() throws IOException
{
include.add("STRINGRESOURCE_en*");
when(mockPushOption.getSourceLang()).thenReturn(sourceLocale);
when(mockPushOption.getLocaleMapList()).thenReturn(locales);
when(mockPushOption.getCaseSensitive()).thenReturn(false);
when(mockPushOption.getExcludeLocaleFilenames()).thenReturn(true);
when(mockPushOption.getDefaultExcludes()).thenReturn(false);
when(mockPushOption.getValidate()).thenReturn("xsd");
xliffStrategy.setPushOptions(mockPushOption);
Set<String> localDocNames = xliffStrategy.findDocNames(sourceDir2, include, exclude, mockPushOption.getDefaultExcludes(), mockPushOption.getCaseSensitive(), mockPushOption.getExcludeLocaleFilenames());
Assert.assertEquals(5, localDocNames.size());
}
@Test
public void loadSrcDocTestWithExcludeFileOption() throws IOException
{
include.add("**/**StringResource_en_US*");
exclude.add("**/*StringResource*");
when(mockPushOption.getTransDir()).thenReturn(sourceDir);
when(mockPushOption.getLocaleMapList()).thenReturn(locales);
when(mockPushOption.getSourceLang()).thenReturn(sourceLocale);
when(mockPushOption.getDefaultExcludes()).thenReturn(true);
when(mockPushOption.getCaseSensitive()).thenReturn(true);
when(mockPushOption.getExcludeLocaleFilenames()).thenReturn(true);
when(mockPushOption.getValidate()).thenReturn("xsd");
xliffStrategy.setPushOptions(mockPushOption);
Set<String> localDocNames = xliffStrategy.findDocNames(sourceDir, include, exclude, mockPushOption.getDefaultExcludes(), mockPushOption.getCaseSensitive(), mockPushOption.getExcludeLocaleFilenames());
List<Resource> resourceList = new ArrayList<Resource>();
for (String docName : localDocNames)
{
Resource srcDoc = xliffStrategy.loadSrcDoc(sourceDir, docName);
resourceList.add(srcDoc);
TranslationResourcesVisitor visitor = mock(TranslationResourcesVisitor.class);
LocaleMapping loc;
// each src file in test has one trans file ('de' or 'fr'):
if (srcDoc.getName().equals("dir1/StringResource"))
{
loc = new LocaleMapping("de");
}
else
{
loc = new LocaleMapping("fr");
}
xliffStrategy.visitTranslationResources(docName, srcDoc, visitor);
verify(visitor).visit(eq(loc), isA(TranslationsResource.class));
}
Assert.assertEquals(0, resourceList.size());
}
@Test
public void loadSrcDocTestWithExcludeOption() throws IOException
{
include.add("**/**StringResource_en_US*");
exclude.add("**/dir2/*");
when(mockPushOption.getTransDir()).thenReturn(sourceDir);
when(mockPushOption.getLocaleMapList()).thenReturn(locales);
when(mockPushOption.getSourceLang()).thenReturn(sourceLocale);
when(mockPushOption.getDefaultExcludes()).thenReturn(true);
when(mockPushOption.getCaseSensitive()).thenReturn(true);
when(mockPushOption.getExcludeLocaleFilenames()).thenReturn(true);
when(mockPushOption.getValidate()).thenReturn("xsd");
xliffStrategy.setPushOptions(mockPushOption);
Set<String> localDocNames = xliffStrategy.findDocNames(sourceDir, include, exclude, mockPushOption.getDefaultExcludes(), mockPushOption.getCaseSensitive(), mockPushOption.getExcludeLocaleFilenames());
List<Resource> resourceList = new ArrayList<Resource>();
for (String docName : localDocNames)
{
Resource srcDoc = xliffStrategy.loadSrcDoc(sourceDir, docName);
resourceList.add(srcDoc);
TranslationResourcesVisitor visitor = mock(TranslationResourcesVisitor.class);
LocaleMapping loc;
// each src file in test has one trans file ('de' or 'fr'):
if (srcDoc.getName().equals("dir1/StringResource"))
{
loc = new LocaleMapping("de");
}
else
{
loc = new LocaleMapping("fr");
}
xliffStrategy.visitTranslationResources(docName, srcDoc, visitor);
verify(visitor).visit(eq(loc), isA(TranslationsResource.class));
}
Assert.assertEquals(1, resourceList.size());
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
7d12ea8a6fe9ccb8c02eefcff1214792dcd9576b | 641b3cb83d82b909b01970dece762a4ea8524d1d | /src/Class42.java | 1713584dbcf81ba90e20007c44e01fb1549850c3 | [] | no_license | Rune-Status/nshusa-battlerune-client-149 | a48e7c39aa00ebfcbf85747174c84368e5c8cbe0 | 3fcfa1820f474efcc290d1fb665db5308cbaaac4 | refs/heads/master | 2021-07-09T22:49:28.082173 | 2017-10-08T00:13:54 | 2017-10-08T00:13:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,091 | java | import java.util.HashMap;
import java.util.Map;
public class Class42 {
static int anInt97;
static final Map chatLineMap;
static final Class70 aClass70_1;
static final Class79 aClass79_1;
static Class30 aClass30_1;
static int[] blendedSaturation;
static {
chatLineMap = new HashMap();
aClass70_1 = new Class70(1024);
aClass79_1 = new Class79();
anInt97 = 0;
}
static final int getSmoothNoise(final int int_0, final int int_1, final int int_2) {
final int int_3 = int_0 / int_2;
final int int_4 = int_0 & (int_2 - 1);
final int int_5 = int_1 / int_2;
final int int_6 = int_1 & (int_2 - 1);
final int int_7 = CombatInfo2.getSmoothNoise2D(int_3, int_5);
final int int_8 = CombatInfo2.getSmoothNoise2D(int_3 + 1, int_5);
final int int_9 = CombatInfo2.getSmoothNoise2D(int_3, int_5 + 1);
final int int_10 = CombatInfo2.getSmoothNoise2D(int_3 + 1, int_5 + 1);
final int int_11 = Class14.method192(int_7, int_8, int_4, int_2);
final int int_12 = Class14.method192(int_9, int_10, int_4, int_2);
return Class14.method192(int_11, int_12, int_6, int_2);
}
}
| [
"freesunfury@gmail.com"
] | freesunfury@gmail.com |
a8945608bcf3f3e5002873acc482e8add6856ce2 | 3ff3713a96c58ea4d6cea5d3b776e137ae437aaa | /src/main/java/io/softawarriors/springboot/topic/Topic.java | 898d3b348924f3b298d852572b0e677592586d36 | [] | no_license | softawarriors/demo1SpringBoot | 16109c704b206b0ce6ffd4a50d97634fe3611be0 | 0a1504608e58d764ed11a65e370c800afa083a7b | refs/heads/master | 2020-03-06T21:54:54.821599 | 2018-03-28T08:01:53 | 2018-03-28T08:01:53 | 127,089,660 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 786 | java | package io.softawarriors.springboot.topic;
public class Topic {
private String id;
private String name;
private String description;
public Topic(){
//default constructor
}
public Topic(String id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| [
"c-pranav.aggarwal@round.glass"
] | c-pranav.aggarwal@round.glass |
91c1b36931445c7a4c7baf66d99c06aec1948fdf | 20ad5a3da3466fc8fde2154965d531d3bbd373d9 | /src/WiggleSort/Solution.java | a4ee8d00b4ab44a4e9712c8d13fc0074fe27b588 | [] | no_license | zhenyiluo/leetcode | 64965f2127c0217364f508aac2683874112f088d | 946ae2714b2bf754312971abcb7af5ef0e0633b4 | refs/heads/master | 2021-01-18T15:17:05.605735 | 2018-10-15T03:07:56 | 2018-10-15T03:07:56 | 41,125,875 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 658 | java | public class Solution {
public void wiggleSort(int[] nums) {
if(nums == null || nums.length <= 1){
return;
}
Arrays.sort(nums);
int len = nums.length;
int ps = 0;
int pl = (len +1) / 2;
int index = 0;
while(ps < len && pl < len && index < len){
if(index == ps){
ps += 2;
}else{
swap(nums, index, pl);
pl ++;
}
index++;
}
}
private void swap(int[] nums, int i, int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
} | [
"zhenyiluo@gmail.com"
] | zhenyiluo@gmail.com |
9019e5e9c47d62ff06fb334d6861a45dbeb51644 | 8e2b0356fbf46795ea76242570616393764afbec | /TIJ4Example/src/thinking/_12_exceptions/OnOffSwitch/OnOffException2.java | 87c3a4edac8be7357729b49cfaaa1875bb224827 | [] | no_license | royalwang/TIJ4Example | 491134983499b1ba1186975ed45ad5373b9e4a6d | 3bbc3a819ba3792c9d51857dad9ff5d1e316d2f0 | refs/heads/master | 2021-12-03T06:29:49.351584 | 2014-04-23T08:18:06 | 2014-04-23T08:18:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 142 | java | package thinking._12_exceptions.OnOffSwitch;
//: exceptions/OnOffException2.java
public class OnOffException2 extends Exception {} ///:~
| [
"776488705@qq.com"
] | 776488705@qq.com |
ba895cf5ff07226319c1a9f927b679fe6d9c2095 | e50b5bd585cdd2efaa16b180f60a4eea13db9180 | /nsjp-web/src/main/java/mx/gob/segob/nsjp/web/hecho/action/IngresarHechosAction.java | 16c840d3c43463a5c4154866e02b2a302ad5c76c | [] | no_license | RichichiDomotics/defensoria | bc885d73ec7f99d685f7e56cde1f63a52a3e8240 | 2a87a841ae5cf47fbe18abf7651c2eaa8b481786 | refs/heads/master | 2016-09-03T01:00:51.529702 | 2015-03-31T01:44:15 | 2015-03-31T01:44:15 | 32,884,521 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 23,494 | java | /**
* Nombre del Programa : IngresarHechosAction.java
* Autor : ArmandoCT
* Compania : Ultrasist
* Proyecto : NSJP Fecha: 14/junio/2011
* Marca de cambio : N/A
* Descripcion General : Clase Action para ingresar objetos
* Programa Dependiente : N/A
* Programa Subsecuente : N/A
* Cond. de ejecucion : N/A
* Dias de ejecucion : N/A Horario: N/A
* MODIFICACIONES
*------------------------------------------------------------------------------
* Autor : N/A
* Compania : N/A
* Proyecto : N/A Fecha: N/A
* Modificacion : N/A
*------------------------------------------------------------------------------
*/
package mx.gob.segob.nsjp.web.hecho.action;
import mx.gob.segob.nsjp.comun.enums.calidad.Calidades;
import mx.gob.segob.nsjp.comun.enums.catalogo.Catalogos;
import mx.gob.segob.nsjp.comun.enums.expediente.OrigenExpediente;
import mx.gob.segob.nsjp.comun.excepcion.NSJPNegocioException;
import mx.gob.segob.nsjp.comun.util.DateUtils;
import mx.gob.segob.nsjp.delegate.expediente.ExpedienteDelegate;
import mx.gob.segob.nsjp.delegate.hecho.HechoDelegate;
import mx.gob.segob.nsjp.dto.catalogo.CatalogoDTO;
import mx.gob.segob.nsjp.dto.catalogo.ValorDTO;
import mx.gob.segob.nsjp.dto.domicilio.*;
import mx.gob.segob.nsjp.dto.elemento.CalidadDTO;
import mx.gob.segob.nsjp.dto.expediente.ExpedienteDTO;
import mx.gob.segob.nsjp.dto.hecho.HechoDTO;
import mx.gob.segob.nsjp.dto.hecho.TiempoDTO;
import mx.gob.segob.nsjp.dto.usuario.UsuarioDTO;
import mx.gob.segob.nsjp.web.base.action.GenericAction;
import mx.gob.segob.nsjp.web.hecho.form.HechoForm;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* Clase Action para ingresar hechos.
*
* @version 1.0
* @author ArmandoCT
*
*/
public class IngresarHechosAction extends GenericAction {
/* Log de clase */
private static final Logger log = Logger
.getLogger(IngresarHechosAction.class);
@Autowired
private HechoDelegate hechoDelegate;
@Autowired
private ExpedienteDelegate expedienteDelegate;
/**
* Metodo utilizado para guardar un hecho
*
* @param mapping
* @param form
* @param request
* @param response
* @return null, debido a la comunicacion Ajax
* @throws IOException
* En caso de obtener una exception
*/
public ActionForward ingresarHecho(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException {
try {
log.info("ejecutando Action guardar hecho");
HechoForm forma = (HechoForm) form;
log.info("FORMA HECHO:::::::::::::::::::::::");
//Revisamos que el id del hecho no sea nulo
if(StringUtils.isBlank(forma.getIdHecho()))
{
forma.setGcDescripcionHecho("0");
log.info("Id Hecho ---> ES:null");
}
log.info("Descripcion="+ forma.getGcDescripcionHecho());
//Revisamos que la descripcion del hecho no sea nula
if(forma.getGcDescripcionHecho().equalsIgnoreCase("") ){
forma.setGcDescripcionHecho("");
log.info("Descripcion, ES:null");
}
//revisamos que los datos de domicilio no sea nula
if(StringUtils.isBlank(forma.getPais())){
forma.setPais("");
}
if(StringUtils.isBlank(forma.getCodigoPostal())){
forma.setCodigoPostal("");
}
if(StringUtils.isBlank(forma.getEntidadFederativa()) || forma.getEntidadFederativa().equalsIgnoreCase("-1")){
forma.setEntidadFederativa(null);
}
if(StringUtils.isBlank(forma.getCiudad()) || forma.getCiudad().equalsIgnoreCase("-1")){
forma.setCiudad(null);
}
if(StringUtils.isBlank(forma.getDelegacionMunicipio()) || forma.getDelegacionMunicipio().equalsIgnoreCase("-1")){
forma.setDelegacionMunicipio(null);
}
if(StringUtils.isBlank(forma.getAsentamientoColonia()) || forma.getAsentamientoColonia().equalsIgnoreCase("-1")){
forma.setAsentamientoColonia(null);
}
if(StringUtils.isBlank(forma.getTipoAsentamiento()) || forma.getTipoAsentamiento().equalsIgnoreCase("-1")){
forma.setTipoAsentamiento(null);
}
if(StringUtils.isBlank(forma.getTipoCalle()) || forma.getTipoCalle().equalsIgnoreCase("-1")){
forma.setTipoCalle(null);
}
if(StringUtils.isBlank(forma.getCalle())){
forma.setCalle("");
}
if(StringUtils.isBlank(forma.getNumExterior())){
forma.setNumExterior("");
}
if(StringUtils.isBlank(forma.getNumInterior())){
forma.setNumInterior("");
}
if(StringUtils.isBlank(forma.getReferencias())){
forma.setReferencias("");
}
if(StringUtils.isBlank(forma.getEntreCalle())){
forma.setEntreCalle("");
}
if(StringUtils.isBlank(forma.getYcalle())){
forma.setYcalle("");
}
if(StringUtils.isBlank(forma.getAliasDomicilio())){
forma.setAliasDomicilio("");
}
if(StringUtils.isBlank(forma.getEdificio())){
forma.setEdificio("");
}
if(StringUtils.isBlank(forma.getLongitud())){
forma.setLongitud("");
}
if(StringUtils.isBlank(forma.getLatitud())){
forma.setLatitud("");
}
//FIN revisamos que los datos de domicilio no sea nula
//encapsulamos la informacion del tiempo
TiempoDTO tiempoDTO=new TiempoDTO();
ValorDTO valorDTO=new ValorDTO();
boolean conTiempo = false;
//revisamos que los datos de tiempo no sea nula
if(Integer.parseInt(forma.getTipoTiempoHecho())>0)
{
List<CatalogoDTO> listaCatalogo= catDelegate.recuperarCatalogo(Catalogos.TIPO_TIEMPO);
//encapsulamos la informacion del tiempo
if(Integer.parseInt(forma.getTipoTiempoHecho())==1 && !forma.getFecha().isEmpty())//especifico
{
/*************************************************/
forma.setHora(IngresarHechosAction.FormateaHora(forma.getHora()));
/**************************************************/
valorDTO.setIdCampo(listaCatalogo.get(0).getClave());
tiempoDTO.setFechaInicio(DateUtils.obtener(forma.getFecha(),forma.getHora()));
tiempoDTO.setTipoRegistro(valorDTO);
conTiempo=true;
}
else if(Integer.parseInt(forma.getTipoTiempoHecho())==2 && !forma.getFechaInicioLapso().isEmpty()
&& !forma.getFechaFinLapso().isEmpty())//lapso
{
/*************************************************/
//7:00PM ---checar que pasa con el 7:00AM && 12:00AM
if( forma.getHoraFinLapso().substring(4, 5).equals("P") ||
forma.getHoraFinLapso().substring(4, 5).equals("A") ||
forma.getHoraFinLapso().substring(5, 6).equals("P") ||
forma.getHoraFinLapso().substring(5, 6).equals("A") )
{
String aux= forma.getHoraFinLapso().substring(forma.getHoraFinLapso().length()-2,forma.getHoraFinLapso().length());
String inicioCad=forma.getHoraFinLapso().substring(0,forma.getHoraFinLapso().length()-2);
forma.setHoraFinLapso(inicioCad+" "+aux);
}
if( forma.getHoraInicioLapso().substring(4, 5).equals("P") ||
forma.getHoraInicioLapso().substring(4, 5).equals("A") ||
forma.getHoraInicioLapso().substring(5, 6).equals("P") ||
forma.getHoraInicioLapso().substring(5, 6).equals("A") )
{
String aux= forma.getHoraInicioLapso().substring(forma.getHoraInicioLapso().length()-2,forma.getHoraInicioLapso().length());
String inicioCad=forma.getHoraInicioLapso().substring(0,forma.getHoraInicioLapso().length()-2);
forma.setHoraInicioLapso(inicioCad+" "+aux);
}
forma.setHoraInicioLapso(IngresarHechosAction.FormateaHora(forma.getHoraInicioLapso()));
forma.setHoraFinLapso(IngresarHechosAction.FormateaHora(forma.getHoraFinLapso()));
/**************************************************/
valorDTO.setIdCampo(listaCatalogo.get(1).getClave());
tiempoDTO.setFechaInicio(DateUtils.obtener(forma.getFechaInicioLapso(),forma.getHoraInicioLapso()));
tiempoDTO.setFechaFin((DateUtils.obtener(forma.getFechaFinLapso(),forma.getHoraFinLapso())));
tiempoDTO.setTipoRegistro(valorDTO);
conTiempo=true;
}
else if(Integer.parseInt(forma.getTipoTiempoHecho())==3)//descripcion hecho
{
valorDTO.setIdCampo(listaCatalogo.get(2).getClave());
tiempoDTO.setDescripcion(forma.getGsNarrativa());
tiempoDTO.setTipoRegistro(valorDTO);
conTiempo=true;
}
}
//encapsulamos la informacion del expediente
//ExpedienteDTO expedienteDTO=(ExpedienteDTO)request.getSession().getAttribute(forma.getNumExpediente());//new ExpedienteDTO(Long.parseLong(forma.getNumExpediente()));
log.info("num_exp_hecho:: "+forma.getNumExpediente());
ExpedienteDTO expedienteDTO=super.getExpedienteTrabajo(request, forma.getNumExpediente());
log.info("id_num_exp_hecho:: "+forma.getNumeroExpedienteId());
log.info("num_exp_DTO:: "+ expedienteDTO);
if(forma.getNumeroExpedienteId()!=null && !forma.getNumeroExpedienteId().equals("null") && !forma.getNumeroExpedienteId().equals(""))
{
expedienteDTO.setNumeroExpedienteId(Long.parseLong(forma.getNumeroExpedienteId()));
}
log.info("num_exp_id_hecho:: "+ expedienteDTO.getNumeroExpedienteId());
//creamos el hecho a insertar
HechoDTO hechoDTO=new HechoDTO();
if(conTiempo){
hechoDTO.setTiempo(tiempoDTO);
}
hechoDTO.setExpediente(expedienteDTO);
hechoDTO.setDescNarrativa(forma.getGcDescripcionHecho());
UsuarioDTO usuarioDTO=new UsuarioDTO();
usuarioDTO.setIdUsuario(Long.parseLong(forma.getIdUsuario()));
hechoDTO.setUsuario(usuarioDTO);
//Revisamos que la fecha de arribo no sea nula
if(!forma.getFechaArribo().equalsIgnoreCase("") && !forma.getHoraArribo().equalsIgnoreCase("")){
forma.setHoraArribo(IngresarHechosAction.FormateaHora(forma.getHoraArribo()));
hechoDTO.setFechaDeArribo(DateUtils.obtener(forma.getFechaArribo(),forma.getHoraArribo()));
}
CalidadDTO calidadDTO=new CalidadDTO();
calidadDTO.setCalidades(Calidades.LUGAR_HECHOS);
//Encapsulamos la informacion del domicilio
if(Long.parseLong(forma.getPais())==10)//Mexico
{
DomicilioDTO domicilioDTO=new DomicilioDTO();
//domicilioDTO.setLatitud(forma.getLatitud());
//domicilioDTO.setLongitud(forma.getLongitud());
if (!(forma.getLatitudN()== null) && !forma.getLatitudN().equals("")) {
/*se cambia la forma del las coordenadas de Grados a Decimales/*Enable IT ByYolo*/
// String lat= forma.getLatitudN()+forma.getLatitudGrados()+"°"+forma.getLatitudMinutos()+"'"+forma.getLatitudSegundos()+"\"";
String lat= forma.getLatitudN();
log.info("lat_hechoDTO:: "+lat);
domicilioDTO.setLatitud(lat);
}
if (!(forma.getLongitudE()== null) && !forma.getLongitudE().equals("")) {
/*se cambia la forma del las coordenadas de Grados a Decimales/*Enable IT ByYolo*/
// String longitud= forma.getLongitudE()+forma.getLongitudGrados()+"°"+forma.getLongitudMinutos()+"'"+forma.getLongitudSegundos()+"\"";
String longitud= forma.getLongitudE();
log.info("lon_hechoDTO:: "+longitud);
domicilioDTO.setLongitud(longitud);
}
domicilioDTO.setEdificio(forma.getEdificio());
domicilioDTO.setAlias(forma.getAliasDomicilio());
domicilioDTO.setEntreCalle2(forma.getYcalle());
domicilioDTO.setEntreCalle1(forma.getEntreCalle());
domicilioDTO.setReferencias(forma.getReferencias());
domicilioDTO.setNumeroInterior(forma.getNumInterior());
domicilioDTO.setNumeroExterior(forma.getNumExterior());
domicilioDTO.setCalle(forma.getCalle());
if(forma.getTipoCalle()!=null)
{
domicilioDTO.setValorCalleId(new ValorDTO(Long.parseLong(forma.getTipoCalle())));
}
domicilioDTO.setCalidadDTO(calidadDTO);
domicilioDTO.setExpedienteDTO(expedienteDTO);
domicilioDTO.setFechaCreacionElemento(new Date());
//delcaramos el nuevo asentamiento
AsentamientoDTO asentamientoDTO=new AsentamientoDTO();
if(forma.getAsentamientoColonia()!=null)
{
log.info("ID_COLONIA::: "+forma.getAsentamientoColonia());
asentamientoDTO.setAsentamientoId(Long.parseLong(forma.getAsentamientoColonia()));
}
asentamientoDTO.setCodigoPostal(forma.getCodigoPostal());
//Declaramos el tipo de asentamiento
if(forma.getTipoAsentamiento()!=null)
{
log.info("ID_TIPO_ASENTAMIENTO::: "+forma.getTipoAsentamiento());
TipoAsentamientoDTO tipoAsentamientoDTO = new TipoAsentamientoDTO(Long.parseLong(forma.getTipoAsentamiento()),"");
asentamientoDTO.setTipoAsentamientoDTO(tipoAsentamientoDTO);
}
//Declaramos el municipio
MunicipioDTO municipioDTO=new MunicipioDTO();
if(forma.getDelegacionMunicipio()!=null)
{
municipioDTO.setMunicipioId(Long.parseLong(forma.getDelegacionMunicipio()));
}
asentamientoDTO.setMunicipioDTO(municipioDTO);
//declaramos la Ciudad
CiudadDTO ciudadDTO = new CiudadDTO();
if(forma.getCiudad()!=null)
{
ciudadDTO.setCiudadId(Long.parseLong(forma.getCiudad()));
}
//declaramos la entidad federativa
EntidadFederativaDTO entidadFederativaDTO=new EntidadFederativaDTO();
if(forma.getEntidadFederativa()!=null)
{
entidadFederativaDTO.setEntidadFederativaId(Long.parseLong(forma.getEntidadFederativa()));
}
if(forma.getPais()!=null)
{
entidadFederativaDTO.setValorIdPais(new ValorDTO(Long.parseLong(forma.getPais())));
}
ciudadDTO.setEntidadFederativaDTO(entidadFederativaDTO);
asentamientoDTO.setCiudadDTO(ciudadDTO);
domicilioDTO.setCiudadDTO(ciudadDTO);
domicilioDTO.setEntidadDTO(entidadFederativaDTO);
domicilioDTO.setAsentamientoDTO(asentamientoDTO);
domicilioDTO.setMunicipioDTO(municipioDTO);
//seteamos el domicilio al Hecho
hechoDTO.setLugar(domicilioDTO);
}
else//Otro pais
{
DomicilioExtranjeroDTO domExtranjreoDTO= new DomicilioExtranjeroDTO();
domExtranjreoDTO.setLatitud(forma.getLatitud());
domExtranjreoDTO.setLongitud(forma.getLongitud());
domExtranjreoDTO.setEdificio(forma.getEdificio());
domExtranjreoDTO.setAlias(forma.getAliasDomicilio());
domExtranjreoDTO.setEntreCalle2(forma.getYcalle());
domExtranjreoDTO.setEntreCalle1(forma.getEntreCalle());
domExtranjreoDTO.setReferencias(forma.getReferencias());
domExtranjreoDTO.setNumeroInterior(forma.getNumInterior());
domExtranjreoDTO.setNumeroExterior(forma.getNumExterior());
domExtranjreoDTO.setCalle(forma.getCalle());
domExtranjreoDTO.setPais(forma.getPais());
domExtranjreoDTO.setCodigoPostal(forma.getCodigoPostal());
domExtranjreoDTO.setCiudad(forma.getCiudad());
domExtranjreoDTO.setMunicipio(forma.getDelegacionMunicipio());
domExtranjreoDTO.setAsentamientoExt(forma.getAsentamientoColonia());
domExtranjreoDTO.setEstado(forma.getEntidadFederativa());
domExtranjreoDTO.setCalidadDTO(calidadDTO);
domExtranjreoDTO.setExpedienteDTO(expedienteDTO);
domExtranjreoDTO.setFechaCreacionElemento(new Date());
//private String tipoAsentamiento; SE VA EN DOMICILIO EXTRANJERO
//private String tipoCalle; SE VA EN DOMICILIO EXTRANJERO
//seteamos el domicilio extranjero al Hecho
hechoDTO.setLugar(domExtranjreoDTO);
}
//cambiamos el estatus del Expediente
if(Long.parseLong(forma.getOrigenExpediente())==0)
{
//Denuncia
expedienteDelegate.actualizarTipoExpediente(expedienteDTO, OrigenExpediente.DENUNCIA);
}
else
{
if(Long.parseLong(forma.getOrigenExpediente())==1){
//Querella
expedienteDelegate.actualizarTipoExpediente(expedienteDTO, OrigenExpediente.QUERELLA);
}else
expedienteDelegate.actualizarTipoExpediente(expedienteDTO, OrigenExpediente.REPORTE);
}
log.info("$$$$$ Ingreso_Hecho - MODIFIQUE EL ORIGEN DEL EXPEDIENTE :::::: "+expedienteDTO.getNumeroExpedienteId());
log.info("idLugar_hechoDTO:: "+request.getParameter("idLugar"));
log.info("idTiempo_hechoDTO:: "+request.getParameter("idTiempo"));
//hacemos la insercion del hecho
if(Long.parseLong(forma.getIdHecho())==0)
{
//esta es una inserción de Hecho
hechoDTO= hechoDelegate.ingresarHecho(hechoDTO);
}
else
{
//esta es una modificacion de un hecho
hechoDTO.setHechoId(Long.parseLong(forma.getIdHecho()));
if (request.getParameter("idLugar")!=null && !request.getParameter("idLugar").isEmpty()) {
hechoDTO.getLugar().setElementoId(Long.parseLong(request.getParameter("idLugar")));
} else {
hechoDTO.getLugar().setElementoId(null);
}
if (request.getParameter("idTiempo")!=null && !request.getParameter("idTiempo").isEmpty()) {
hechoDTO.getTiempo().setTiempoId(Long.parseLong(request.getParameter("idTiempo")));
} else if (conTiempo){
hechoDTO.getTiempo().setTiempoId(null);
}
//FIXME aqui abajo iria el llamado al servicio de actualizacion del Hecho
hechoDTO=hechoDelegate.modificarHecho(hechoDTO);
}
if(hechoDTO!=null && hechoDTO.getHechoId()!=null)
{
converter.alias("hechoDTO", HechoDTO.class);
String xml = converter.toXML(hechoDTO);
log.info("hechoDTO:: "+xml);
escribirRespuesta(response, xml);
}
else
{
hechoDTO.setHechoId(0L);
converter.alias("hechoDTO", HechoDTO.class);
String xml = converter.toXML(hechoDTO);
escribirRespuesta(response, xml);
}
log.info("Termina ejecucion Action guardar hecho - FIN ");
} catch (NSJPNegocioException e) {
log.error(e.getMessage(), e);
escribir(response, "", e);
}
return null;
}
/*************************************************/
/*************************************************/
public static String FormateaHora(String strhora){
String horaFormateada = null;
String complemento=null;
int hora = 0;
if(strhora.contains("PM")){
if(strhora.length()==7 || strhora.length() == 6 ){
complemento=strhora.substring(1,strhora.length());
hora=Integer.parseInt(strhora.substring(0, 1));
}
if(strhora.length()==8){
complemento=strhora.substring(2,strhora.length());
hora=Integer.parseInt(strhora.substring(0, 2));
}
hora+=12;
if(hora==24){
hora=12;
}
horaFormateada=hora+""+complemento;
}else if(strhora.contains("AM")){
if(strhora.length()==7 || strhora.length()==6 ){
complemento=strhora.substring(1,strhora.length());
hora=Integer.parseInt(strhora.substring(0, 1));
}
if(strhora.length()==8){
complemento=strhora.substring(2,strhora.length());
hora=Integer.parseInt(strhora.substring(0, 2));
}
if (hora==12){
hora=00;
}
horaFormateada=hora+""+complemento;
}
else{//sino trae ni am ni pm
strhora=strhora.trim();//quito espacios en blanco
if(strhora.length()== 4){
hora=Integer.parseInt(strhora.substring(0,1));
complemento= strhora.substring(1,strhora.length());
complemento +=" AM";
horaFormateada=hora+""+complemento;
}
if(strhora.length()== 5 ){
hora=Integer.parseInt(strhora.substring(0,2));
complemento=strhora.substring(2,strhora.length());
if(hora>0 && hora <=11 ){//es AM
complemento+=" AM";
}
if(hora==0 || hora >=12 ){
complemento+=" PM";
}
horaFormateada=hora+""+complemento;
}
}
return horaFormateada;
}
/**
* Metodo para actualizar un hecho con base a su Id
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws IOException
*/
public ActionForward modificarHecho(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
/**
* Por el momento solo se va a modificar la narrativa o descripcion
*/
log.info("EJECUTANDO ACTION MODIFICAR HECHO");
HechoForm forma = (HechoForm) form;
log.info("************VERIFICANDO PARAMETROS****************");
log.info("HECHO ID:::::::::::::::::::::::" + forma.getIdHecho());
log.info("HECHO DESCRIPCION::::::::::::::" + forma.getGcDescripcionHecho());
log.info("HECHO EXPEDIENTE_ID::::::::::::" + forma.getExpedienteId());
// Revisamos que el id del hecho no sea nulo
Long hechoId = NumberUtils.toLong(forma.getIdHecho(), 0L);
Long expedienteId = NumberUtils.toLong(forma.getExpedienteId(), 0L);
HechoDTO hechoDTO = new HechoDTO();
if (hechoId != null && hechoId > 0L && expedienteId != null && expedienteId > 0L) {
ExpedienteDTO expedienteDto = new ExpedienteDTO();
expedienteDto.setExpedienteId(expedienteId);
hechoDTO.setHechoId(hechoId);
hechoDTO.setExpediente(expedienteDto);
if(forma.getGcDescripcionHecho() != null && !forma.getGcDescripcionHecho().trim().isEmpty()){
hechoDTO.setDescNarrativa(forma.getGcDescripcionHecho());
}
hechoDTO = hechoDelegate.modificarHecho(hechoDTO);
}
if (hechoDTO != null && hechoDTO.getHechoId() != null) {
converter.alias("hechoDTO", HechoDTO.class);
String xml = converter.toXML(hechoDTO);
log.info("hechoDTO:: " + xml);
escribirRespuesta(response, xml);
}
} catch (NSJPNegocioException e) {
log.error(e.getMessage(), e);
escribir(response, "", e);
}
return null;
}
/**
* Metodo para consultar un hecho con base a su Id
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws IOException
*/
public ActionForward consultarHecho(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
log.info("EJECUTANDO ACTION CONSULTAR HECHO");
log.info("EJECUTANDO ACTION MODIFICAR HECHO");
HechoForm forma = (HechoForm) form;
UsuarioDTO usuario = super.getUsuarioFirmado(request);
log.info("************VERIFICANDO PARAMETROS****************");
log.info("HECHO EXPEDIENTE_ID::::::::::::" + forma.getExpedienteId());
Long expedienteId = NumberUtils.toLong(forma.getExpedienteId(), 0L);
HechoDTO hechoDTO = new HechoDTO();
List<HechoDTO> listaHechos = null;
if (expedienteId != null && expedienteId > 0L) {
ExpedienteDTO expedienteDto = new ExpedienteDTO();
expedienteDto.setExpedienteId(expedienteId);
hechoDTO.setExpediente(expedienteDto);
listaHechos = hechoDelegate.consultarHechos(hechoDTO);
}
if (listaHechos != null && listaHechos.size() > 0 && listaHechos.get(0) != null) {
listaHechos.get(0).setUsuario(usuario);
converter.alias("usuarioDTO", UsuarioDTO.class);
converter.alias("hechoDTO", HechoDTO.class);
String xml = converter.toXML(listaHechos.get(0));
log.info("hechoDTO:: " + xml);
escribirRespuesta(response, xml);
}
} catch (NSJPNegocioException e) {
log.error(e.getMessage(), e);
escribir(response, "", e);
}
return null;
}
}
| [
"larryconther@gmail.com"
] | larryconther@gmail.com |
d1e2d20171f5735cec96375c08e25854a31210ad | 7d329203a8a337fd261ba92b03d9ce4f5b4ea005 | /app/src/main/java/com/transcomfy/data/model/History.java | efef8d04b789acdcb548008d8fb38369e50e26c5 | [] | no_license | sharonmalio/Transcomfy_commuter | e358fafd295f55ab8ba1b0eb9f283780a2e79e5c | 273236d0dd790d4f3111db3b1abb04b58b4f3dfd | refs/heads/master | 2021-05-06T00:24:16.031814 | 2018-01-14T13:04:42 | 2018-01-14T13:04:42 | 117,249,036 | 0 | 1 | null | 2018-01-14T13:04:43 | 2018-01-12T14:16:06 | Java | UTF-8 | Java | false | false | 1,532 | java | package com.transcomfy.data.model;
import android.os.Parcel;
import android.os.Parcelable;
public class History implements Parcelable {
private String from;
private String to;
private double amount;
private long createdAt;
public History(){
}
public void setFrom(String from) {
this.from = from;
}
public void setTo(String to) {
this.to = to;
}
public void setAmount(double amount) {
this.amount = amount;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
public String getFrom() {
return from;
}
public String getTo() {
return to;
}
public double getAmount() {
return amount;
}
public long getCreatedAt() {
return createdAt;
}
public History(Parcel in){
from = in.readString();
to = in.readString();
amount = in.readDouble();
createdAt = in.readLong();
}
public static final Creator CREATOR = new Creator() {
public History createFromParcel(Parcel in) {
return new History(in);
}
public History[] newArray(int size) {
return new History[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(from);
dest.writeString(to);
dest.writeDouble(amount);
dest.writeLong(createdAt);
}
}
| [
"kaninimalio@gmail.com"
] | kaninimalio@gmail.com |
bd4733c635f8ebd73c43e8beb31eb55fc08c67e9 | aa66bb5ce78d8696d4c5343f4782b468ebe0764e | /app/src/main/java/com/app/legend/waraumusic/utils/ScrollerFragmentLayout.java | eaf23a41d10ce4cfb0a0bc000354f90db326cd5b | [
"MIT"
] | permissive | liuzhushaonian/WarauMusic | 5c8eaaffff0c9b5655a62f26ef435ecfc6a16704 | 2795bfa644475d1140843004f606ddc4a9823d0a | refs/heads/master | 2020-03-29T17:57:19.491834 | 2018-09-25T00:58:35 | 2018-09-25T00:58:35 | 150,187,222 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,532 | java | package com.app.legend.waraumusic.utils;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.FrameLayout;
public class ScrollerFragmentLayout extends FrameLayout{
private float mPosY=0,mCurPosY=0;
private boolean con=false;
private GestureDetector gestureDetector;
public ScrollerFragmentLayout(@NonNull Context context) {
super(context);
}
public ScrollerFragmentLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ScrollerFragmentLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public ScrollerFragmentLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setGestureDetector(GestureDetector gestureDetector) {
this.gestureDetector = gestureDetector;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (gestureDetector!=null){
return gestureDetector.onTouchEvent(ev);
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean performClick() {
return super.performClick();
}
}
| [
"liuzhushaonian@sina.cn"
] | liuzhushaonian@sina.cn |
b22f24d0bceed726e0cd357487ae33df259e29e2 | 96a031caf94c7aaced33a34ad0eb9d7c51691d40 | /src/main/java/com/aces/aws/security/UserSecurityService.java | 2d3f5de6706d15a582ad6e7f67024f0523b2e489 | [] | no_license | ajayinva/aces-mongo | d227e554a2d6022124d29333d7bffa85794fb6fd | 740ba1a8ada7571f68c1fb06e2a233590626257d | refs/heads/master | 2020-12-02T16:41:36.747596 | 2017-07-07T19:13:55 | 2017-07-07T19:13:55 | 96,569,452 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 918 | java | /**
*
*/
package com.aces.aws.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.aces.aws.entity.User;
import com.aces.aws.repositories.UserRepository;
/**
* @author aagarwal
*
*/
@Service
public class UserSecurityService implements UserDetailsService{
/**
*
*/
@Autowired
private UserRepository userRepository;
/**
*
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUserName(username);
if(user==null){
throw new UsernameNotFoundException("Username "+username+" not found");
}
return user;
}
}
| [
"ajayinva@gmail.com"
] | ajayinva@gmail.com |
5e4618e84be3c3ae245592fa6c3e72543a7f0375 | 3d6719045a4cfa9cb030b356d302309c535e0451 | /src/main/java/net/sourceforge/jwbf/mediawiki/bots/MediaWikiBot.java | b08e811ef059c68a699fc43b660298b68e6c68cb | [
"Apache-2.0"
] | permissive | enginer/jwbf | 91fa3ee16f0080bc0862e791ba86dc0b57cdf86d | f2ef4f3fbe0d75a5daa47d8cbb0dbc03bb4cc944 | refs/heads/master | 2021-01-14T09:54:09.301716 | 2014-03-23T15:02:56 | 2014-03-23T16:15:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,813 | java | package net.sourceforge.jwbf.mediawiki.bots;
import java.net.URL;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.jwbf.core.actions.ContentProcessable;
import net.sourceforge.jwbf.core.actions.HttpActionClient;
import net.sourceforge.jwbf.core.actions.util.ActionException;
import net.sourceforge.jwbf.core.actions.util.ProcessException;
import net.sourceforge.jwbf.core.bots.HttpBot;
import net.sourceforge.jwbf.core.bots.WikiBot;
import net.sourceforge.jwbf.core.bots.util.JwbfException;
import net.sourceforge.jwbf.core.contentRep.Article;
import net.sourceforge.jwbf.core.contentRep.ContentAccessable;
import net.sourceforge.jwbf.core.contentRep.SimpleArticle;
import net.sourceforge.jwbf.core.contentRep.Userinfo;
import net.sourceforge.jwbf.mediawiki.actions.MediaWiki;
import net.sourceforge.jwbf.mediawiki.actions.MediaWiki.Version;
import net.sourceforge.jwbf.mediawiki.actions.editing.GetRevision;
import net.sourceforge.jwbf.mediawiki.actions.editing.PostDelete;
import net.sourceforge.jwbf.mediawiki.actions.editing.PostModifyContent;
import net.sourceforge.jwbf.mediawiki.actions.login.PostLogin;
import net.sourceforge.jwbf.mediawiki.actions.meta.GetUserinfo;
import net.sourceforge.jwbf.mediawiki.actions.meta.GetVersion;
import net.sourceforge.jwbf.mediawiki.actions.meta.Siteinfo;
import net.sourceforge.jwbf.mediawiki.actions.util.VersionException;
import net.sourceforge.jwbf.mediawiki.contentRep.LoginData;
import com.google.common.collect.ImmutableSet;
/**
* This class helps you to interact with each <a href="http://www.mediawiki.org" target="_blank">MediaWiki</a>. This
* class offers a <b>basic set</b> of methods which are defined in the package net.sourceforge.jwbf.actions.mw.* How to
* use:
*
* <pre>
* MediaWikiBot b = new MediaWikiBot("http://yourwiki.org");
* b.login("Username", "Password");
* System.out.println(b.readContent("Main Page").getText());
* </pre>
*
* <b>How to find the correct wikiurl</b>
* <p>
* The correct wikiurl is sometimes not easy to find, because some wikiadmis uses url rewriting rules. In this cases the
* correct url is the one, which gives you access to <code>api.php</code>. E.g. Compare
*
* <pre>
* http://www.mediawiki.org/wiki/api.php
* http://www.mediawiki.org/w/api.php
* </pre>
*
* Thus the correct wikiurl is: <code>http://www.mediawiki.org/w/</code>
* </p>
*
* @author Thomas Stock
* @author Tobias Knerr
* @author Justus Bisser
*/
@Slf4j
public class MediaWikiBot implements WikiBot {
private LoginData login = null;
private Version version = null;
private Userinfo ui = null;
private boolean loginChangeUserInfo = false;
private boolean loginChangeVersion = false;
private boolean useEditApi = true;
@Inject
private HttpBot bot;
private HttpActionClient client;
/**
* These chars are not allowed in article names.
*/
public static final char[] INVALID_LABEL_CHARS = "[]{}<>|".toCharArray();
private static final int DEFAULT_READ_PROPERTIES = GetRevision.CONTENT | GetRevision.COMMENT
| GetRevision.USER | GetRevision.TIMESTAMP | GetRevision.IDS | GetRevision.FLAGS;
private static final Set<String> emptySet = ImmutableSet.of();
/**
* use this constructor, if you want to work with IoC.
*/
public MediaWikiBot() {
}
/**
* @param u
* wikihosturl like "http://www.mediawiki.org/w/"
*/
public MediaWikiBot(final URL u) {
this(HttpActionClient.of(u));
}
public MediaWikiBot(final HttpActionClient client) {
this.client = client;
bot = new HttpBot(client);
}
/**
* @param url
* wikihosturl like "http://www.mediawiki.org/w/"
* @throws IllegalArgumentException
* if param url does not represent a well-formed url
*/
public MediaWikiBot(final String url) {
if (!(url.endsWith(".php") || url.endsWith("/"))) {
throw new IllegalArgumentException("(" + url + ") url must end with slash or .php");
}
this.client = HttpActionClient.of(url);
bot = new HttpBot(client);
}
/**
* @param url
* wikihosturl like "http://www.mediawiki.org/w/"
* @param testHostReachable
* if true, test if host reachable
*/
public MediaWikiBot(URL url, boolean testHostReachable) {
bot = new HttpBot(client);
if (testHostReachable) {
HttpBot.getPage(client);
}
}
/**
* Performs a Login.
*
* @param username
* the username
* @param passwd
* the password
* @param domain
* login domain (Special for LDAPAuth extention to authenticate against LDAP users)
* @see PostLogin
*/
public void login(final String username, final String passwd, final String domain) {
LoginData login = new LoginData();
performAction(new PostLogin(username, passwd, domain, login));
this.login = login;
loginChangeUserInfo = true;
if (getVersion() == Version.UNKNOWN) {
loginChangeVersion = true;
}
}
/**
* Performs a Login. Actual old cookie login works right, because is pending on
* {@link #writeContent(ContentAccessable)}
*
* @param username
* the username
* @param passwd
* the password
* @see PostLogin
*/
@Override
public void login(final String username, final String passwd) {
login(username, passwd, null);
}
/**
* @param name
* of article in a mediawiki like "Main Page"
* @param properties
* {@link GetRevision}
* @return a content representation of requested article, never null
* @see GetRevision
*/
public synchronized Article getArticle(final String name, final int properties) {
return new Article(this, readData(name, properties));
}
/**
* {@inheritDoc}
*/
@Override
public synchronized SimpleArticle readData(final String name, final int properties) {
GetRevision ac = new GetRevision(getVersion(), name, properties);
performAction(ac);
return ac.getArticle();
}
/**
* {@inheritDoc}
*/
@Override
public SimpleArticle readData(String name) {
return readData(name, DEFAULT_READ_PROPERTIES);
}
/**
* @param name
* of article in a mediawiki like "Main Page"
* @return a content representation of requested article, never null
* @see GetRevision
*/
public synchronized Article getArticle(final String name) {
return getArticle(name, DEFAULT_READ_PROPERTIES);
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void writeContent(final SimpleArticle simpleArticle) {
if (!isLoggedIn()) {
throw new ActionException("Please login first");
}
for (char invChar : INVALID_LABEL_CHARS) { // FIXME Replace with a REGEX
if (simpleArticle.getTitle().contains(invChar + "")) {
throw new ActionException("Invalid character in label\"" + simpleArticle.getTitle()
+ "\" : \"" + invChar + "\"");
}
}
performAction(new PostModifyContent(this, simpleArticle));
if (simpleArticle.getText().trim().length() < 1)
throw new RuntimeException("Content is empty, still written");
}
/**
* @return true if
*/
public final boolean isLoggedIn() {
if (login != null) {
return login.isLoggedIn();
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public Userinfo getUserinfo() {
log.debug("get userinfo");
if (ui == null || loginChangeUserInfo) {
GetUserinfo a;
try {
a = new GetUserinfo();
performAction(a);
ui = a;
loginChangeUserInfo = false;
} catch (VersionException e) {
if (login != null && login.getUserName().length() > 0) {
ui = new Userinfo() {
@Override
public String getUsername() {
return login.getUserName();
}
@Override
public Set<String> getRights() {
return emptySet;
}
@Override
public Set<String> getGroups() {
return emptySet;
}
};
} else {
ui = new Userinfo() {
@Override
public String getUsername() {
return "unknown";
}
@Override
public Set<String> getRights() {
return emptySet;
}
@Override
public Set<String> getGroups() {
return emptySet;
}
};
}
}
}
return ui;
}
/**
* {@inheritDoc}
*/
@Override
public void delete(String title) {
performAction(new PostDelete(this, title));
}
/**
* deletes an article with a reason
*/
public void delete(String title, String reason) {
performAction(new PostDelete(this, title, reason));
}
public synchronized String performAction(ContentProcessable a) {
if (a.isSelfExecuter()) {
throw new ActionException("this is a selfexcecuting action, "
+ "please do not perform this action manually");
}
return bot().performAction(a);
}
private HttpBot bot() {
if (bot == null) {
throw new IllegalStateException("please use another constructor or inject "
+ HttpBot.class.getCanonicalName());
}
return bot;
}
/**
* @return the
* @throws IllegalStateException
* if no version was found.
* @see #getSiteinfo()
*/
@Nonnull
public Version getVersion() throws IllegalStateException {
if (version == null || loginChangeVersion) {
try {
GetVersion gs = new GetVersion();
performAction(gs);
version = gs.getVersion();
loginChangeVersion = false;
} catch (JwbfException e) {
log.error(e.getClass().getName() + e.getLocalizedMessage());
throw new IllegalStateException(e.getLocalizedMessage());
}
log.debug("Version is: " + version.name());
}
return version;
}
/**
* @return a on problems with http, cookies and io
* @see Siteinfo
*/
@Nonnull
public Siteinfo getSiteinfo() {
Siteinfo gs = null;
try {
gs = new Siteinfo();
performAction(gs);
} catch (ProcessException e) {
log.error("{}", e);
}
return gs;
}
/**
* @return the
*/
public boolean isEditApi() {
return useEditApi;
}
/**
* @param useEditApi
* Set to false, to force editing without the API.
*/
public final void useEditApi(boolean useEditApi) {
this.useEditApi = useEditApi;
}
/**
* {@inheritDoc}
*/
@Override
public final String getWikiType() {
return MediaWiki.class.getName() + " " + getVersion();
}
}
| [
"eldurloki@users.sourceforge.net"
] | eldurloki@users.sourceforge.net |
05388c96a75aafddd370531fff05b6e463679c64 | 2071205760a653b2ba530ebe66cd0bea4b1f9390 | /Village/src/village/GroundSand.java | c4dd098d6d7f0837a8aa755bcce042534352e177 | [] | no_license | KosteCZ/koste-playground | 7b38453afa2ba15a758a239b5bb19a25a567717e | cfacbc24765cf0966d5e157a5044cfcf503b4bd6 | refs/heads/master | 2021-01-20T10:30:53.824024 | 2016-07-20T21:15:30 | 2016-07-20T21:15:30 | 33,817,408 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 297 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package village;
/**
*
* @author Honza
*/
public class GroundSand extends Ground {
public GroundSand(int x, int y, int size) {
super(x, y, size);
// name = "Grass";
}
}
| [
"xkoscak@gmail.com@e8249325-254e-5a8f-03e7-5eb5bf0d756e"
] | xkoscak@gmail.com@e8249325-254e-5a8f-03e7-5eb5bf0d756e |
8036e1d32c8e2341d5b23be0f28263ee7e021964 | 6cead6da6e39a136dc1305d50ce58766d7143179 | /GITTest2_Idea/src/main/java/com/zhangfan/test/DiGuiDemo.java | e58176e2c389ae63666b29e8968a1168314ca538 | [] | no_license | hahaha4963/studyDemo | 3dbf54231d2eed06a03c5de2ef4879fc56de8acb | 6c42a98a5fc978afa5606a18c5b1dc9de84df876 | refs/heads/master | 2020-04-28T21:58:32.799223 | 2019-03-14T10:51:53 | 2019-03-14T10:51:53 | 175,601,048 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 310 | java | package com.zhangfan.test;
public class DiGuiDemo {
public static void main(String[] args) {
Long i = 10L;
System.out.println("i! = "+fac(i));
}
static Long fac(Long n){
if(n <= 1L){
return 1L;
}else {
return n*fac(n-1);
}
}
}
| [
"hahaha@qq.com"
] | hahaha@qq.com |
38355d90dc963f5efed9914a2aff41dc33de1022 | b7e02b9a752c2e82d8ac5f349c7cd9d6c10d357f | /src/com/my/java/guanxi/Test.java | e1d5c15b22bc5ebaeb954bd3c3b3d1d5fb2430d9 | [] | no_license | zhangmin1992/java-base | fdd80c65383b32a6a4419ea34a04e73cb686e90e | 508736ffe55b43a4b9cdd61c3eec9fb90876b881 | refs/heads/master | 2022-11-06T09:31:39.239927 | 2022-10-20T09:00:02 | 2022-10-20T09:00:02 | 143,278,263 | 0 | 0 | null | 2019-09-23T09:18:13 | 2018-08-02T10:15:43 | Java | UTF-8 | Java | false | false | 98 | java | package com.my.java.guanxi;
public class Test {
public static void main(String[] args) {
}
}
| [
"zhangmin46@maoyan.com"
] | zhangmin46@maoyan.com |
19137951303c48f92911f25d36465d618b6766f0 | 1524cf9ff1cbceb5ba7259e7b1fc67d3011e55f8 | /src/main/java/org/w3/mathml3/Grad.java | cc0c29d5106eba3160fbeb4fbf970f237d49fefe | [] | no_license | bojanantonovic/mathml-3-jaxb | 927662f6314c36576dbe5b884a664aa384444b81 | 7981ad7daa3b55711accd4888de0277556a1afd8 | refs/heads/master | 2021-01-17T06:28:57.987250 | 2016-06-23T13:51:47 | 2016-06-23T13:51:47 | 61,806,818 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,927 | java | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.06.23 um 03:11:44 PM CEST
//
package org.w3.mathml3;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "grad")
public class Grad {
@XmlAttribute(name = "xmlns")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xmlns;
@XmlAttribute(name = "xmlns:xlink")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xmlnsXlink;
@XmlAttribute(name = "xmlns:xsi")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xmlnsXsi;
@XmlAttribute(name = "xlink:href")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xlinkHref;
@XmlAttribute(name = "xlink:type")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xlinkType;
@XmlAttribute(name = "xml:lang")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xmlLang;
@XmlAttribute(name = "xml:space")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String xmlSpace;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String id;
@XmlAttribute(name = "xref")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String xref;
@XmlAttribute(name = "class")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String clazz;
@XmlAttribute(name = "style")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String style;
@XmlAttribute(name = "href")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String href;
@XmlAttribute(name = "other")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String other;
@XmlAttribute(name = "encoding")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String encoding;
@XmlAttribute(name = "definitionURL")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String definitionURL;
/**
* Ruft den Wert der xmlns-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlns() {
if (xmlns == null) {
return "http://www.w3.org/1998/Math/MathML";
} else {
return xmlns;
}
}
/**
* Legt den Wert der xmlns-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlns(String value) {
this.xmlns = value;
}
/**
* Ruft den Wert der xmlnsXlink-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlnsXlink() {
if (xmlnsXlink == null) {
return "http://www.w3.org/1999/xlink";
} else {
return xmlnsXlink;
}
}
/**
* Legt den Wert der xmlnsXlink-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlnsXlink(String value) {
this.xmlnsXlink = value;
}
/**
* Ruft den Wert der xmlnsXsi-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlnsXsi() {
return xmlnsXsi;
}
/**
* Legt den Wert der xmlnsXsi-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlnsXsi(String value) {
this.xmlnsXsi = value;
}
/**
* Ruft den Wert der xlinkHref-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXlinkHref() {
return xlinkHref;
}
/**
* Legt den Wert der xlinkHref-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXlinkHref(String value) {
this.xlinkHref = value;
}
/**
* Ruft den Wert der xlinkType-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXlinkType() {
return xlinkType;
}
/**
* Legt den Wert der xlinkType-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXlinkType(String value) {
this.xlinkType = value;
}
/**
* Ruft den Wert der xmlLang-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlLang() {
return xmlLang;
}
/**
* Legt den Wert der xmlLang-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlLang(String value) {
this.xmlLang = value;
}
/**
* Ruft den Wert der xmlSpace-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlSpace() {
return xmlSpace;
}
/**
* Legt den Wert der xmlSpace-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlSpace(String value) {
this.xmlSpace = value;
}
/**
* Ruft den Wert der id-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Legt den Wert der id-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Ruft den Wert der xref-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXref() {
return xref;
}
/**
* Legt den Wert der xref-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXref(String value) {
this.xref = value;
}
/**
* Ruft den Wert der clazz-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
return clazz;
}
/**
* Legt den Wert der clazz-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
/**
* Ruft den Wert der style-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Legt den Wert der style-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Ruft den Wert der href-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Legt den Wert der href-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Ruft den Wert der other-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOther() {
return other;
}
/**
* Legt den Wert der other-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOther(String value) {
this.other = value;
}
/**
* Ruft den Wert der encoding-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Legt den Wert der encoding-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
/**
* Ruft den Wert der definitionURL-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefinitionURL() {
return definitionURL;
}
/**
* Legt den Wert der definitionURL-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefinitionURL(String value) {
this.definitionURL = value;
}
}
| [
"bojan@antonovic.ch"
] | bojan@antonovic.ch |
5888900c203c85acfd2dbd3f2e739b1cd7a35902 | 666731669ccf0ba1a5243876d44286ce5d0c0262 | /order/src/main/java/com/hzyice/order/dto/CartDTO.java | eb8887688ae18b286ff9ffd8e453750649f993ad | [] | no_license | hzyice/hzy-springcloud-sell | 9afaa6f3936a838cb2291d33a3896ae43fa0dd56 | f36c473737bf7e2af6a93045088d4bcbeb46535a | refs/heads/master | 2020-03-24T16:07:38.176853 | 2018-07-30T03:10:55 | 2018-07-30T03:10:55 | 142,813,545 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 456 | java | package com.hzyice.order.dto;
import lombok.Data;
/**
* Created by 廖师兄
* 2017-12-10 22:36
*/
@Data
public class CartDTO {
/**
* 商品id
*/
private String productId;
/**
* 商品数量
*/
private Integer productQuantity;
public CartDTO() {
}
public CartDTO(String productId, Integer productQuantity) {
this.productId = productId;
this.productQuantity = productQuantity;
}
}
| [
"285633420@qq.com"
] | 285633420@qq.com |
5e1969cfcd0611f63c85235a7c4c3e4b191c6105 | a8830d1b5106306faec8b432241346fd0db563ca | /src/factoryDesignPattern/UFOShip.java | 93b538349b77ad3297f938f0978b4414a7a10d3e | [] | no_license | turian-ovidiu/Java-Design-Patterns | e7f5f0bec65b9b6d155d5d61b812a682f0a4e569 | 340f94e48f9484da281e2d987d3095c77f2690b7 | refs/heads/master | 2021-01-23T22:12:03.864010 | 2017-02-25T11:18:05 | 2017-02-25T11:18:05 | 83,120,357 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 196 | java | package factoryDesignPattern;
public class UFOShip extends EnemyShip {
public UFOShip() {
super();
setName("Alien");
setDamage(356);
setSpeed(267);
}
}
| [
"trovvi@gmail.com"
] | trovvi@gmail.com |
37661a1820ce381eead647d40812c06ed042ce8d | 6232ea567256e453ef45d024c350c173d7df2026 | /Login/src/org/gvp/database/MySqlConnection.java | 48d972d9c0d7cdd94c89d03e69fda33d0d3b9851 | [] | no_license | kevalking/LoginFramework | 7499f5b0ac2d5a3aa0b11b25159eab0c4bd565f4 | cbe6c61a6441e5bcdb00b0ab1575e2d50fcdb9f3 | refs/heads/master | 2021-01-10T08:51:02.848070 | 2016-02-29T10:03:18 | 2016-02-29T10:03:18 | 51,500,434 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 769 | java | package org.gvp.database;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* MySqlConnection class have getConnection method.
* @return It returns Connection object.
* @author Ravirajsinh Vaghela
*
*/
public class MySqlConnection implements org.gvp.database.IConnection
{
public Connection getConnection(String Server_ip,String db_name, String user_name, String password)//this method is for made connection
{
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://"+Server_ip+"/"+db_name,user_name,password);
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
}
| [
"kevalking.pithva@gmail.com"
] | kevalking.pithva@gmail.com |
1c943366b52c7b51dbb7879e23fb1b9ea4086fc1 | e51de484e96efdf743a742de1e91bce67f555f99 | /Android/triviacrack_src/src/com/inmobi/androidsdk/bootstrapper/AppGalleryConfigParams.java | 56d4aa8e2b802ad8f6b56b1db3f6c6586ea39d21 | [] | no_license | adumbgreen/TriviaCrap | b21e220e875f417c9939f192f763b1dcbb716c69 | beed6340ec5a1611caeff86918f107ed6807d751 | refs/heads/master | 2021-03-27T19:24:22.401241 | 2015-07-12T01:28:39 | 2015-07-12T01:28:39 | 28,071,899 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 621 | java | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.inmobi.androidsdk.bootstrapper;
import com.inmobi.commons.internal.InternalSDKUtil;
import java.util.Map;
public class AppGalleryConfigParams
{
String a;
public AppGalleryConfigParams()
{
a = "http://appgalleries.inmobi.com/inmobi_sdk";
}
public String getUrl()
{
return a;
}
public void setFromMap(Map map)
{
a = InternalSDKUtil.getStringFromMap(map, "url");
}
}
| [
"klayderpus@chimble.net"
] | klayderpus@chimble.net |
ed5bf1b3f983b1c20f5523275a21fba9e043f28f | c3f90fe74a47867c019ed08466827caca2e2a1e4 | /src/packrun/Greifer.java | d535e0caf09b99dd0fc619ffbf0e5c2b7a7979bf | [] | no_license | Hakermann420/javamichi | 2126fbee77b49bdc47165858825cd98026cff0f7 | da3b84786f2c97745712017731443e842c62364b | refs/heads/main | 2023-05-25T18:20:12.148318 | 2021-06-03T12:30:03 | 2021-06-03T12:30:03 | 356,687,096 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 657 | java | package packrun;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.port.MotorPort;
/**
* @author Hakermann
* Klasse, um den Greifer am Roboter zu kontrollieren,
* kann den Greifer hoch und runter fahren
*
*/
public class Greifer {
public static EV3LargeRegulatedMotor motor;
/**
* Initializes the motor
*/
public static void Init() {
if(motor == null) motor = new EV3LargeRegulatedMotor(MotorPort.A);
}
/**
* Bewegt den Gabelstapler nach oben
*/
public static void Up() {
motor.rotate(-45);
}
/**
* Bewegt den Gabelstapler nach unten
*/
public static void Down() {
motor.rotate(45);
}
}
| [
"marcel.loebert@gmail.com"
] | marcel.loebert@gmail.com |
59d8035b1491a8771d6d615958de1f37ece9970f | 1a1e5c984f8fd44b9652333f21aff8f100cc277b | /app/src/main/java/PackageManager.java | a1166012122cdab9f81b8942ecbfb1015c6369bc | [] | no_license | SagarBChauhan/Brodcast-Demo | fb7e74ca52c61c40fd9374bba9a9e1d591821631 | 4701e36fdf3cf6fbc07f216447b01e8262e6315e | refs/heads/main | 2022-12-22T20:00:49.836633 | 2020-10-05T04:50:13 | 2020-10-05T04:50:13 | 301,296,332 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 628 | java | import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class PackageManager extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED))
{
Toast.makeText(context, "Application added", Toast.LENGTH_SHORT).show();
}
else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED))
{
Toast.makeText(context, "Application Removed", Toast.LENGTH_SHORT).show();
}
}
}
| [
"chauhansagar373@gmail.com"
] | chauhansagar373@gmail.com |
3e9f9d905f7705a74a3101930318180cde65646a | 72eeddbdaa48e883f99d900fc0f3b11b94f873d3 | /src/main/java/com/pierre/serialnumbersgenerator/Application.java | baadc731a6dfa61cb14ef6aac425fb9926825926 | [
"Unlicense"
] | permissive | PierreMoawad/SerialNumbersGenerator | 62fd182896f5b77b6a9855b85929a9a8c180b81c | e70966c0457c43304d223bc5e749def5824905a0 | refs/heads/main | 2023-06-07T08:26:35.627045 | 2021-06-27T14:47:19 | 2021-06-27T14:47:19 | 363,291,057 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 743 | java | package com.pierre.serialnumbersgenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.vaadin.artur.helpers.LaunchUtil;
/**
* The entry point of the Spring Boot application.
*/
@SpringBootApplication
@ConfigurationPropertiesScan("com.pierre.serialnumbersgenerator.config")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
LaunchUtil.launchBrowserInDevelopmentMode(SpringApplication.run(Application.class, args));
}
}
| [
"piere.moawad@gmail.com"
] | piere.moawad@gmail.com |
39972cf996bbb5335483ae3679059cf72a0303df | 0501395067d20df394b520b449901997f1c287fd | /src/main/java/org/szx/common/exception/GlobalRuntimeException.java | 5a009d1838a88158db128d7e63e23149aaa95e32 | [] | no_license | vstartup/vstartup-apartment | 8fe334ecb7dddfed84502af4e87dd1c6bf1c7ec2 | b2b060e50754df256b0fefe749af361bc8afa88f | refs/heads/master | 2021-01-15T22:29:38.758335 | 2015-04-14T05:47:21 | 2015-04-14T05:47:21 | 33,845,190 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 521 | java | package org.szx.common.exception;
/**
全局的运行异常定义
对于没有明确含义的运行异常可以统一使用该异常,必须在构造函数提供异常描述的代码和参数
*/
public class GlobalRuntimeException extends BaseRuntimeException{
private static final long serialVersionUID = -4243351801813509605L;
public GlobalRuntimeException(String message,Exception e){
super(message,e);
}
public GlobalRuntimeException(String code,String[] params){
super(code,params);
}
}
| [
"hongchun_zhang@yeah.net"
] | hongchun_zhang@yeah.net |
d5e267fc60a6fca79122fd7fe210f16570b4246f | a28a8ef8027dcbe7f7eaa168347c6c2d0c1b2d79 | /war/datasets/jEdit-1SC/t_230882/astchanges.java | 74c6cd2c884aa5643a6bc2cdd5fff086863f27da | [] | no_license | martinezmatias/commitsurvey | f36f9e6a32c2dd43cc976eb2224ffae06067c609 | a1791d57b879c722d30ee174e1af81737ef04f34 | refs/heads/master | 2021-01-23T05:29:56.498364 | 2017-03-27T08:58:08 | 2017-03-27T08:58:08 | 86,312,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 35 | java | STATEMENT_PARENT_CHANGE-ASSIGNMENT
| [
"matias.sebastian.martinez@gmail.com"
] | matias.sebastian.martinez@gmail.com |
6ad325bf62e826db1769e98f87d3f54c259f6f82 | b6b0c2c78b6bf55c2818d5758e96a9d246d2c215 | /C01/src/xyz/heptadecane/SRTF.java | 6a516a3d21ef0be4818f7e74eba8298987e57020 | [
"MIT"
] | permissive | HeptaDecane/SPOSL_SEM6 | d2580339662f4317fba48bdbce7077a94865f6ff | bee47943e4d9f3fe5e35b8e4c4d3f2fc634f58c7 | refs/heads/main | 2023-05-07T03:54:08.299744 | 2021-05-27T16:37:41 | 2021-05-27T16:37:41 | 333,099,050 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,184 | java | package xyz.heptadecane;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class SRTF extends Scheduler {
private Map<Integer, Integer> timeMap;
public SRTF(ArrayList<Process> processes) {
super(processes);
timeMap = new HashMap<>();
for(Process process : processes)
timeMap.put(process.getId(), process.getCpuTime());
}
@Override
protected Process selectProcess() {
Process selected = null;
for(Process process : processes){
if(!process.isCompleted() && currentTime>=process.getArrivalTime()){
if(selected == null)
selected = process;
else {
if(timeMap.get(process.getId()) < timeMap.get(selected.getId()))
selected = process;
else if(timeMap.get(process.getId()) == timeMap.get(selected.getId()))
if (process.getArrivalTime() < selected.getArrivalTime())
selected = process;
else if (process.getArrivalTime() == selected.getArrivalTime())
if (process.getId() < selected.getId())
selected = process;
}
}
}
return selected;
}
@Override
public String execute() {
String chart = "";
while (!isQueueEmpty()){
chart += currentTime+" ";
Process process = selectProcess();
if(process == null) {
chart += "[ ] ";
moveTimer(1);
}
else {
chart += "[P"+process.getId()+"] ";
if(!process.isResponded())
process.setResponseTime(currentTime);
int remainingTime = timeMap.get(process.getId()) - 1;
timeMap.put(process.getId(), remainingTime);
moveTimer(1);
if(timeMap.get(process.getId()) == 0)
process.setCompletionTime(currentTime);
}
}
chart += currentTime+"\n";
return chart;
}
}
| [
"sooraj1999vs@gmail.com"
] | sooraj1999vs@gmail.com |
ab310e59fcce2bda70edd1d68b39e4e8dc3968ba | 88f10466d29ea421e7d22606664507d83abd89e4 | /src/com/thoughtworks/Operations/Operation.java | c273453f0ace88e9ad35a052f7c3a4fbf3135f0b | [] | no_license | Amiedeep/biblioteca2 | a1dd754944dfe6ac321154114a56270528ac4f7e | d243e1da53590e3efff0f86dcfd39ce05196933e | refs/heads/master | 2021-01-23T05:36:19.173648 | 2019-12-27T12:51:12 | 2019-12-27T12:51:12 | 41,812,737 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 183 | java | //A interface with only executeOperation method which all classes have to implement.
package com.thoughtworks.Operations;
public interface Operation {
void executeOperation();
}
| [
"amandees@thoughtworks.com"
] | amandees@thoughtworks.com |
c0d10f2427f9b28f30f49543e160da0b96140fcd | 37af04a484f1bab238400ae877ad24ba24990cae | /src/Assignments/NestedWhileEx.java | 950f89212164a180a0116ed902cd69036181f404 | [] | no_license | hacialidemirbas/GitHub | e1b7626ce20e6080173108d035131440a41be8e6 | 00e97743fdf6836f19b0aa7117622a4b15827aab | refs/heads/master | 2021-05-27T10:44:54.192489 | 2020-05-19T22:59:33 | 2020-05-19T22:59:33 | 254,257,875 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 337 | java | package Assignments;
public class NestedWhileEx {
public static void main(String[] args) {
int oLoop = 1;
while (oLoop<20) {
while(oLoop < 11) {
System.out.println(oLoop);
oLoop++;
}
System.out.println(oLoop);
oLoop++;
}
}
}
| [
"hacialidemirbas@gmail.com"
] | hacialidemirbas@gmail.com |
6c11067908bee28da14e0beff7abc7066d52a1ab | 141be6a0ffea92aa0196f8928340a16638b210ed | /毕业设计/20170501/13计算机1班-张松周-20170501/源码/geju/YYFramework/src/app/logic/activity/user/AboutMeActivity.java | 1a31840ea2e14e90f01931f85a39ec47c76d2e9d | [
"Apache-2.0"
] | permissive | pexcn-todo/GraduationPro | 16dc5978d502c0fd5e599def7b61439005d4a8ec | 0f5565a4a522c4524d1e296d8e6fd9f637ee8660 | refs/heads/master | 2021-06-17T17:07:38.132229 | 2017-05-09T15:51:23 | 2017-05-09T15:51:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,940 | java | package app.logic.activity.user;
import java.io.File;
import java.util.List;
import org.ql.app.alert.AlertDialog;
import org.ql.utils.QLToastUtils;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import app.logic.activity.ActTitleHandler;
import app.logic.activity.InitActActivity;
import app.logic.controller.UpdataController;
import app.logic.pojo.UpdataAppInfo;
import app.logic.singleton.ZSZSingleton;
import app.logic.singleton.ZSZSingleton.StatusDownloadFileCompleteListener;
import app.logic.singleton.ZSZSingleton.UpdataDownloadProgressListener;
import app.utils.common.Listener;
import app.utils.download.thread.AppVersionDownloadThread;
import app.utils.helpers.SystemBuilderUtils;
import app.yy.geju.R;
/*
* GZYY 2016-10-20 下午4:52:47
*/
public class AboutMeActivity extends InitActActivity implements OnClickListener {
public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/YYData/download";
private ActTitleHandler titleHandler;
private TextView app_PackbackName;
private ImageView app_UpdataStatus;
private UpdataAppInfo updataAppInfo;
@Override
protected void initActTitleView() {
titleHandler = new ActTitleHandler();
setAbsHandler(titleHandler);
}
@Override
protected void initView(Bundle savedInstanceState) {
setContentView(R.layout.activity_about_me);
setTitle("关于");
titleHandler.replaseLeftLayout(this, true);
titleHandler.getLeftLayout().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
app_PackbackName = (TextView) findViewById(R.id.app_packbackNameTV);
app_UpdataStatus = (ImageView) findViewById(R.id.app_updataStatusIv);
findViewById(R.id.app_Updata_layout).setOnClickListener(this);
}
@Override
protected void initData() {
app_PackbackName.setText("Android for V:" + String.valueOf(SystemBuilderUtils.getInstance().getAppVersionName(AboutMeActivity.this)));
checkUpdataApp();
updataApp();
}
/*
* 检查版本更新
*/
private void checkUpdataApp() {
// 开始检查网络版本
UpdataController.getAppVersion(this, new Listener<Void, List<UpdataAppInfo>>() {
@Override
public void onCallBack(Void status, List<UpdataAppInfo> reply) {
if (reply == null || reply.size() < 1) {
return;
}
UpdataAppInfo info = reply.get(0);
int versionCode = SystemBuilderUtils.getInstance().getAppVersionCode(AboutMeActivity.this);
if (versionCode == -1) {
return;
}
//
if (versionCode < info.getApp_version()) {
// showUpdataApp(versionCode, info);
updataAppInfo = info;
app_UpdataStatus.setVisibility(View.VISIBLE);
}
}
});
}
private void showUpdataApp(int oldVersionCode, final UpdataAppInfo info) {
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(0);
alertDialog.setTitle(info.getApp_update_msg());
View view = LayoutInflater.from(this).inflate(R.layout.dialog_updata_app_layout, null);
alertDialog.setView(view);
TextView message_tv = (TextView) view.findViewById(R.id.message_tv);
message_tv.setText("当前版本为" + String.valueOf(oldVersionCode) + ",检测到的最新版本为" + String.valueOf(info.getApp_version()) + ",是否要更新??");
Button yes_btn = (Button) view.findViewById(R.id.yes_btn);
final Button no_btn = (Button) view.findViewById(R.id.no_btn);
yes_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
checkLocationFile(info);
alertDialog.dismiss();
}
});
no_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (info.getApp_udpate_type() == 1) {
no_btn.setTextColor(getResources().getColor(R.color.line_bg));
return;
}
alertDialog.dismiss();
}
});
alertDialog.show();
}
// 检查本地文件
private void checkLocationFile(final UpdataAppInfo info) {
// 创建目录下载目录
File dir = new File(DOWNLOAD_PATH);
if (!dir.exists()) {
dir.mkdir();
}
// 检查本地文件是否存在
final File appFile = new File(DOWNLOAD_PATH + "/" + info.getApp_name() + ".apk");
if (appFile.exists()) {
appFile.delete();
}
updataDownloadProgress();
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
AppVersionDownloadThread downloadThread = new AppVersionDownloadThread(AboutMeActivity.this, info);
downloadThread.start();
}
});
}
// 回调最新app下载完成后,打开apk
private void updataApp() {
ZSZSingleton.getZSZSingleton().setStatusDownloadFileCompleteListener(new StatusDownloadFileCompleteListener() {
@Override
public void onCallBack(String url) {
if (url == null || TextUtils.isEmpty(url)) {
return;
}
if (ZSZSingleton.getZSZSingleton().getHaveComplete() > 0) {
return;
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(url)), "application/vnd.android.package-archive");
startActivity(intent);
ZSZSingleton.getZSZSingleton().setHaveComplete(1);
}
});
}
// 通知消息下载进度
private void updataDownloadProgress() {
final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("格局新版本下载").setContentText("下载进度").setSmallIcon(R.drawable.ic_launcher);
ZSZSingleton.getZSZSingleton().setUpdataDownloadProgressListener(new UpdataDownloadProgressListener() {
@Override
public void onCallBack(int plan) {
if (plan < 100) {
builder.setProgress(100, plan, false);
builder.setAutoCancel(true);
manager.notify(100, builder.build());
} else {
builder.setContentText("下载完成").setProgress(0, 0, true);
manager.notify(100, builder.build());
manager.cancel(100);
}
}
});
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.app_Updata_layout:
if (updataAppInfo != null) {
showUpdataApp(SystemBuilderUtils.getInstance().getAppVersionCode(AboutMeActivity.this), updataAppInfo);
} else {
QLToastUtils.showToast(AboutMeActivity.this, "当前已经是最新版本了");
}
break;
default:
break;
}
}
}
| [
"2964287498@qq.com"
] | 2964287498@qq.com |
721518ff178bd2aac910687b03eb2ab3cbd130e6 | c05f87647a9f224d03d9387ed5d0f2d1553999cb | /app/src/main/java/com/application/chatroomsv2/AES/AES_Main.java | 0ab62e97779698db66df37f82726880c85208c16 | [] | no_license | harshita707/secure-voice-encryption | d54e9eacb3a6bfa721c7ac441264a0ace239fd9b | fbfb6f6d5af161fdcaf0288d1db7b151b581adc5 | refs/heads/master | 2023-04-28T13:09:07.577619 | 2021-05-27T07:16:21 | 2021-05-27T07:16:21 | 357,084,104 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,923 | java | package com.application.chatroomsv2.AES;
import java.util.Base64;
import java.util.Scanner;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class AES_Main {
public static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < ba.length; i++)
str.append(String.format("%x", ba[i]));
return str.toString();
}
public static String fromHexString(String hex) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < hex.length(); i += 2) {
str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
}
return str.toString();
}
public static String encryptMessage(String message, String keyBase) {
//fixing message length
int k = message.length();
if (k < 16) {
for (int i = 0; i < (16 - k); i++) {
message = message.concat("-");
}
}
String key = getHashKey.get128bitKey(keyBase);
String st = toHexString(message.getBytes());
AES aes = new AES(st, key);
String et = aes.encrypt();
return et;
}
public static String decryptMessage(String message, String keyBase){
String key = getHashKey.get128bitKey(keyBase);
AES aes1 = new AES(message, key);
String pt = aes1.decrypt();
pt = fromHexString(pt);
return pt.replaceAll("-*$", "");
}
// public static void main(String[] args) {
//
// String key = "";//"7a52514c722b7349723872584b6a612f";// "01234567890123450123456789012444"7a52514c722b7349723872584b6a612f
// String s;
//
// Scanner sc = new Scanner(System.in);
// System.out.println("Enter String:");
// s = sc.nextLine();
// // System.out.println(s.length());
// int k = s.length();
// if (k < 16) {
// for (int i = 0; i < (16 - k); i++) {
// s = s.concat("-");
// }
// }
// KeyGenerator Gen;
// SecretKey secretKey;
// String encodedKey;
// try {
// Gen = KeyGenerator.getInstance("AES");
// Gen.init(128);
// secretKey = Gen.generateKey();
// encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
// key = toHexString(encodedKey.getBytes());
// key = key.substring(0, 32);
// System.out.println(key + " " + key.length());
// } catch (Exception e) {
// }
//
// String st = toHexString(s.getBytes());
// AES aes = new AES(st, key);
// String et = aes.encrypt();
// System.out.println("encrypted text:" + et);
//
// AES aes1 = new AES(et, key);
// String pt = aes1.decrypt();
// pt = fromHexString(pt);
// System.out.println("decrypted text:" + pt.replaceAll("-*$", ""));
// }
}
| [
"harshitapundir707@gmail.com"
] | harshitapundir707@gmail.com |
0a089d5175b7d614c06871a7eacd4b2564205067 | c738c635c8337f31f53ca1350e751dd76d9e3401 | /src/main/java/com/mailslurp/models/WebhookDeliveryStatusPayload.java | 9350f4972f9ff9302f47a2da06cee7f8dfb8a959 | [
"MIT"
] | permissive | mailslurp/mailslurp-client-java | e1f8fa9e3d91092825dfc6566a577d1be3dd5c8b | 5fff8afabd783c94c7e99c4ce8fcb8cb8058982c | refs/heads/master | 2023-06-24T02:46:29.757016 | 2023-06-12T23:35:46 | 2023-06-12T23:35:46 | 204,670,215 | 3 | 2 | MIT | 2022-05-29T01:44:33 | 2019-08-27T09:38:50 | Java | UTF-8 | Java | false | false | 26,614 | java | /*
* MailSlurp API
* MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://docs.mailslurp.com/) - [Examples](https://github.com/mailslurp/examples) repository
*
* The version of the OpenAPI document: 6.5.2
* Contact: contact@mailslurp.dev
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.mailslurp.models;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.openapitools.jackson.nullable.JsonNullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.mailslurp.clients.JSON;
/**
* DELIVERY_STATUS webhook payload. Sent to your webhook url endpoint via HTTP POST when an email delivery status is created. This could be a successful delivery or a delivery failure.
*/
@ApiModel(description = "DELIVERY_STATUS webhook payload. Sent to your webhook url endpoint via HTTP POST when an email delivery status is created. This could be a successful delivery or a delivery failure.")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2023-06-12T23:33:57.654989Z[Etc/UTC]")
public class WebhookDeliveryStatusPayload {
public static final String SERIALIZED_NAME_MESSAGE_ID = "messageId";
@SerializedName(SERIALIZED_NAME_MESSAGE_ID)
private String messageId;
public static final String SERIALIZED_NAME_WEBHOOK_ID = "webhookId";
@SerializedName(SERIALIZED_NAME_WEBHOOK_ID)
private UUID webhookId;
/**
* Name of the event type webhook is being triggered for.
*/
@JsonAdapter(EventNameEnum.Adapter.class)
public enum EventNameEnum {
EMAIL_RECEIVED("EMAIL_RECEIVED"),
NEW_EMAIL("NEW_EMAIL"),
NEW_CONTACT("NEW_CONTACT"),
NEW_ATTACHMENT("NEW_ATTACHMENT"),
EMAIL_OPENED("EMAIL_OPENED"),
EMAIL_READ("EMAIL_READ"),
DELIVERY_STATUS("DELIVERY_STATUS"),
BOUNCE("BOUNCE"),
BOUNCE_RECIPIENT("BOUNCE_RECIPIENT"),
NEW_SMS("NEW_SMS");
private String value;
EventNameEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static EventNameEnum fromValue(String value) {
for (EventNameEnum b : EventNameEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<EventNameEnum> {
@Override
public void write(final JsonWriter jsonWriter, final EventNameEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public EventNameEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return EventNameEnum.fromValue(value);
}
}
}
public static final String SERIALIZED_NAME_EVENT_NAME = "eventName";
@SerializedName(SERIALIZED_NAME_EVENT_NAME)
private EventNameEnum eventName;
public static final String SERIALIZED_NAME_WEBHOOK_NAME = "webhookName";
@SerializedName(SERIALIZED_NAME_WEBHOOK_NAME)
private String webhookName;
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private UUID id;
public static final String SERIALIZED_NAME_USER_ID = "userId";
@SerializedName(SERIALIZED_NAME_USER_ID)
private UUID userId;
public static final String SERIALIZED_NAME_SENT_ID = "sentId";
@SerializedName(SERIALIZED_NAME_SENT_ID)
private UUID sentId;
public static final String SERIALIZED_NAME_REMOTE_MTA_IP = "remoteMtaIp";
@SerializedName(SERIALIZED_NAME_REMOTE_MTA_IP)
private String remoteMtaIp;
public static final String SERIALIZED_NAME_INBOX_ID = "inboxId";
@SerializedName(SERIALIZED_NAME_INBOX_ID)
private UUID inboxId;
public static final String SERIALIZED_NAME_REPORTING_MTA = "reportingMta";
@SerializedName(SERIALIZED_NAME_REPORTING_MTA)
private String reportingMta;
public static final String SERIALIZED_NAME_RECIPIENTS = "recipients";
@SerializedName(SERIALIZED_NAME_RECIPIENTS)
private List<String> recipients = null;
public static final String SERIALIZED_NAME_SMTP_RESPONSE = "smtpResponse";
@SerializedName(SERIALIZED_NAME_SMTP_RESPONSE)
private String smtpResponse;
public static final String SERIALIZED_NAME_SMTP_STATUS_CODE = "smtpStatusCode";
@SerializedName(SERIALIZED_NAME_SMTP_STATUS_CODE)
private Integer smtpStatusCode;
public static final String SERIALIZED_NAME_PROCESSING_TIME_MILLIS = "processingTimeMillis";
@SerializedName(SERIALIZED_NAME_PROCESSING_TIME_MILLIS)
private Long processingTimeMillis;
public static final String SERIALIZED_NAME_RECEIVED = "received";
@SerializedName(SERIALIZED_NAME_RECEIVED)
private OffsetDateTime received;
public static final String SERIALIZED_NAME_SUBJECT = "subject";
@SerializedName(SERIALIZED_NAME_SUBJECT)
private String subject;
public WebhookDeliveryStatusPayload() {
}
public WebhookDeliveryStatusPayload messageId(String messageId) {
this.messageId = messageId;
return this;
}
/**
* Idempotent message ID. Store this ID locally or in a database to prevent message duplication.
* @return messageId
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "Idempotent message ID. Store this ID locally or in a database to prevent message duplication.")
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public WebhookDeliveryStatusPayload webhookId(UUID webhookId) {
this.webhookId = webhookId;
return this;
}
/**
* ID of webhook entity being triggered
* @return webhookId
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "ID of webhook entity being triggered")
public UUID getWebhookId() {
return webhookId;
}
public void setWebhookId(UUID webhookId) {
this.webhookId = webhookId;
}
public WebhookDeliveryStatusPayload eventName(EventNameEnum eventName) {
this.eventName = eventName;
return this;
}
/**
* Name of the event type webhook is being triggered for.
* @return eventName
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "Name of the event type webhook is being triggered for.")
public EventNameEnum getEventName() {
return eventName;
}
public void setEventName(EventNameEnum eventName) {
this.eventName = eventName;
}
public WebhookDeliveryStatusPayload webhookName(String webhookName) {
this.webhookName = webhookName;
return this;
}
/**
* Name of the webhook being triggered
* @return webhookName
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Name of the webhook being triggered")
public String getWebhookName() {
return webhookName;
}
public void setWebhookName(String webhookName) {
this.webhookName = webhookName;
}
public WebhookDeliveryStatusPayload id(UUID id) {
this.id = id;
return this;
}
/**
* ID of delivery status
* @return id
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "ID of delivery status")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public WebhookDeliveryStatusPayload userId(UUID userId) {
this.userId = userId;
return this;
}
/**
* User ID of event
* @return userId
**/
@javax.annotation.Nonnull
@ApiModelProperty(required = true, value = "User ID of event")
public UUID getUserId() {
return userId;
}
public void setUserId(UUID userId) {
this.userId = userId;
}
public WebhookDeliveryStatusPayload sentId(UUID sentId) {
this.sentId = sentId;
return this;
}
/**
* ID of sent email
* @return sentId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "ID of sent email")
public UUID getSentId() {
return sentId;
}
public void setSentId(UUID sentId) {
this.sentId = sentId;
}
public WebhookDeliveryStatusPayload remoteMtaIp(String remoteMtaIp) {
this.remoteMtaIp = remoteMtaIp;
return this;
}
/**
* IP address of the remote Mail Transfer Agent
* @return remoteMtaIp
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "IP address of the remote Mail Transfer Agent")
public String getRemoteMtaIp() {
return remoteMtaIp;
}
public void setRemoteMtaIp(String remoteMtaIp) {
this.remoteMtaIp = remoteMtaIp;
}
public WebhookDeliveryStatusPayload inboxId(UUID inboxId) {
this.inboxId = inboxId;
return this;
}
/**
* Id of the inbox
* @return inboxId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Id of the inbox")
public UUID getInboxId() {
return inboxId;
}
public void setInboxId(UUID inboxId) {
this.inboxId = inboxId;
}
public WebhookDeliveryStatusPayload reportingMta(String reportingMta) {
this.reportingMta = reportingMta;
return this;
}
/**
* Mail Transfer Agent reporting delivery status
* @return reportingMta
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Mail Transfer Agent reporting delivery status")
public String getReportingMta() {
return reportingMta;
}
public void setReportingMta(String reportingMta) {
this.reportingMta = reportingMta;
}
public WebhookDeliveryStatusPayload recipients(List<String> recipients) {
this.recipients = recipients;
return this;
}
public WebhookDeliveryStatusPayload addRecipientsItem(String recipientsItem) {
if (this.recipients == null) {
this.recipients = new ArrayList<>();
}
this.recipients.add(recipientsItem);
return this;
}
/**
* Recipients for delivery
* @return recipients
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Recipients for delivery")
public List<String> getRecipients() {
return recipients;
}
public void setRecipients(List<String> recipients) {
this.recipients = recipients;
}
public WebhookDeliveryStatusPayload smtpResponse(String smtpResponse) {
this.smtpResponse = smtpResponse;
return this;
}
/**
* SMTP server response message
* @return smtpResponse
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "SMTP server response message")
public String getSmtpResponse() {
return smtpResponse;
}
public void setSmtpResponse(String smtpResponse) {
this.smtpResponse = smtpResponse;
}
public WebhookDeliveryStatusPayload smtpStatusCode(Integer smtpStatusCode) {
this.smtpStatusCode = smtpStatusCode;
return this;
}
/**
* SMTP server status
* @return smtpStatusCode
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "SMTP server status")
public Integer getSmtpStatusCode() {
return smtpStatusCode;
}
public void setSmtpStatusCode(Integer smtpStatusCode) {
this.smtpStatusCode = smtpStatusCode;
}
public WebhookDeliveryStatusPayload processingTimeMillis(Long processingTimeMillis) {
this.processingTimeMillis = processingTimeMillis;
return this;
}
/**
* Time in milliseconds for delivery processing
* @return processingTimeMillis
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Time in milliseconds for delivery processing")
public Long getProcessingTimeMillis() {
return processingTimeMillis;
}
public void setProcessingTimeMillis(Long processingTimeMillis) {
this.processingTimeMillis = processingTimeMillis;
}
public WebhookDeliveryStatusPayload received(OffsetDateTime received) {
this.received = received;
return this;
}
/**
* Time event was received
* @return received
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Time event was received")
public OffsetDateTime getReceived() {
return received;
}
public void setReceived(OffsetDateTime received) {
this.received = received;
}
public WebhookDeliveryStatusPayload subject(String subject) {
this.subject = subject;
return this;
}
/**
* Email subject
* @return subject
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Email subject")
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WebhookDeliveryStatusPayload webhookDeliveryStatusPayload = (WebhookDeliveryStatusPayload) o;
return Objects.equals(this.messageId, webhookDeliveryStatusPayload.messageId) &&
Objects.equals(this.webhookId, webhookDeliveryStatusPayload.webhookId) &&
Objects.equals(this.eventName, webhookDeliveryStatusPayload.eventName) &&
Objects.equals(this.webhookName, webhookDeliveryStatusPayload.webhookName) &&
Objects.equals(this.id, webhookDeliveryStatusPayload.id) &&
Objects.equals(this.userId, webhookDeliveryStatusPayload.userId) &&
Objects.equals(this.sentId, webhookDeliveryStatusPayload.sentId) &&
Objects.equals(this.remoteMtaIp, webhookDeliveryStatusPayload.remoteMtaIp) &&
Objects.equals(this.inboxId, webhookDeliveryStatusPayload.inboxId) &&
Objects.equals(this.reportingMta, webhookDeliveryStatusPayload.reportingMta) &&
Objects.equals(this.recipients, webhookDeliveryStatusPayload.recipients) &&
Objects.equals(this.smtpResponse, webhookDeliveryStatusPayload.smtpResponse) &&
Objects.equals(this.smtpStatusCode, webhookDeliveryStatusPayload.smtpStatusCode) &&
Objects.equals(this.processingTimeMillis, webhookDeliveryStatusPayload.processingTimeMillis) &&
Objects.equals(this.received, webhookDeliveryStatusPayload.received) &&
Objects.equals(this.subject, webhookDeliveryStatusPayload.subject);
}
private static <T> boolean equalsNullable(JsonNullable<T> a, JsonNullable<T> b) {
return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get()));
}
@Override
public int hashCode() {
return Objects.hash(messageId, webhookId, eventName, webhookName, id, userId, sentId, remoteMtaIp, inboxId, reportingMta, recipients, smtpResponse, smtpStatusCode, processingTimeMillis, received, subject);
}
private static <T> int hashCodeNullable(JsonNullable<T> a) {
if (a == null) {
return 1;
}
return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class WebhookDeliveryStatusPayload {\n");
sb.append(" messageId: ").append(toIndentedString(messageId)).append("\n");
sb.append(" webhookId: ").append(toIndentedString(webhookId)).append("\n");
sb.append(" eventName: ").append(toIndentedString(eventName)).append("\n");
sb.append(" webhookName: ").append(toIndentedString(webhookName)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" userId: ").append(toIndentedString(userId)).append("\n");
sb.append(" sentId: ").append(toIndentedString(sentId)).append("\n");
sb.append(" remoteMtaIp: ").append(toIndentedString(remoteMtaIp)).append("\n");
sb.append(" inboxId: ").append(toIndentedString(inboxId)).append("\n");
sb.append(" reportingMta: ").append(toIndentedString(reportingMta)).append("\n");
sb.append(" recipients: ").append(toIndentedString(recipients)).append("\n");
sb.append(" smtpResponse: ").append(toIndentedString(smtpResponse)).append("\n");
sb.append(" smtpStatusCode: ").append(toIndentedString(smtpStatusCode)).append("\n");
sb.append(" processingTimeMillis: ").append(toIndentedString(processingTimeMillis)).append("\n");
sb.append(" received: ").append(toIndentedString(received)).append("\n");
sb.append(" subject: ").append(toIndentedString(subject)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("messageId");
openapiFields.add("webhookId");
openapiFields.add("eventName");
openapiFields.add("webhookName");
openapiFields.add("id");
openapiFields.add("userId");
openapiFields.add("sentId");
openapiFields.add("remoteMtaIp");
openapiFields.add("inboxId");
openapiFields.add("reportingMta");
openapiFields.add("recipients");
openapiFields.add("smtpResponse");
openapiFields.add("smtpStatusCode");
openapiFields.add("processingTimeMillis");
openapiFields.add("received");
openapiFields.add("subject");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("messageId");
openapiRequiredFields.add("webhookId");
openapiRequiredFields.add("eventName");
openapiRequiredFields.add("id");
openapiRequiredFields.add("userId");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to WebhookDeliveryStatusPayload
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!WebhookDeliveryStatusPayload.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
throw new IllegalArgumentException(String.format("The required field(s) %s in WebhookDeliveryStatusPayload is not found in the empty JSON string", WebhookDeliveryStatusPayload.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!WebhookDeliveryStatusPayload.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `WebhookDeliveryStatusPayload` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : WebhookDeliveryStatusPayload.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
if (!jsonObj.get("messageId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `messageId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("messageId").toString()));
}
if (!jsonObj.get("webhookId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `webhookId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("webhookId").toString()));
}
if (!jsonObj.get("eventName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `eventName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("eventName").toString()));
}
if ((jsonObj.get("webhookName") != null && !jsonObj.get("webhookName").isJsonNull()) && !jsonObj.get("webhookName").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `webhookName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("webhookName").toString()));
}
if (!jsonObj.get("id").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `id` to be a primitive type in the JSON string but got `%s`", jsonObj.get("id").toString()));
}
if (!jsonObj.get("userId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `userId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("userId").toString()));
}
if ((jsonObj.get("sentId") != null && !jsonObj.get("sentId").isJsonNull()) && !jsonObj.get("sentId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `sentId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sentId").toString()));
}
if ((jsonObj.get("remoteMtaIp") != null && !jsonObj.get("remoteMtaIp").isJsonNull()) && !jsonObj.get("remoteMtaIp").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `remoteMtaIp` to be a primitive type in the JSON string but got `%s`", jsonObj.get("remoteMtaIp").toString()));
}
if ((jsonObj.get("inboxId") != null && !jsonObj.get("inboxId").isJsonNull()) && !jsonObj.get("inboxId").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `inboxId` to be a primitive type in the JSON string but got `%s`", jsonObj.get("inboxId").toString()));
}
if ((jsonObj.get("reportingMta") != null && !jsonObj.get("reportingMta").isJsonNull()) && !jsonObj.get("reportingMta").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `reportingMta` to be a primitive type in the JSON string but got `%s`", jsonObj.get("reportingMta").toString()));
}
// ensure the optional json data is an array if present
if (jsonObj.get("recipients") != null && !jsonObj.get("recipients").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `recipients` to be an array in the JSON string but got `%s`", jsonObj.get("recipients").toString()));
}
if ((jsonObj.get("smtpResponse") != null && !jsonObj.get("smtpResponse").isJsonNull()) && !jsonObj.get("smtpResponse").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `smtpResponse` to be a primitive type in the JSON string but got `%s`", jsonObj.get("smtpResponse").toString()));
}
if ((jsonObj.get("subject") != null && !jsonObj.get("subject").isJsonNull()) && !jsonObj.get("subject").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `subject` to be a primitive type in the JSON string but got `%s`", jsonObj.get("subject").toString()));
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!WebhookDeliveryStatusPayload.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'WebhookDeliveryStatusPayload' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<WebhookDeliveryStatusPayload> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(WebhookDeliveryStatusPayload.class));
return (TypeAdapter<T>) new TypeAdapter<WebhookDeliveryStatusPayload>() {
@Override
public void write(JsonWriter out, WebhookDeliveryStatusPayload value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public WebhookDeliveryStatusPayload read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of WebhookDeliveryStatusPayload given an JSON string
*
* @param jsonString JSON string
* @return An instance of WebhookDeliveryStatusPayload
* @throws IOException if the JSON string is invalid with respect to WebhookDeliveryStatusPayload
*/
public static WebhookDeliveryStatusPayload fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, WebhookDeliveryStatusPayload.class);
}
/**
* Convert an instance of WebhookDeliveryStatusPayload to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}
| [
"contact@mailslurp.dev"
] | contact@mailslurp.dev |
03febaae6ac867fce90ae4e1013b3b478cc1e91c | aab3f486974c3c5701ebfdaa31da7f2f02d050da | /spring-security-demo-1/src/main/java/com/verizon/ssd/controller/CommonController.java | fbc1f8bb883e407b58a23acd73271126471c8a75 | [] | no_license | KrishnaSai07/SpringFiles | c02ff5110eb86f33119e1122eca93f01bbb7a4e1 | 31ed8a0327b53211154264a9eebb002fc5172735 | refs/heads/master | 2020-04-04T18:44:25.016058 | 2018-11-05T07:29:28 | 2018-11-05T07:29:28 | 156,176,705 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 351 | java | package com.verizon.ssd.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class CommonController {
@GetMapping({"","/","/home"})
public ModelAndView showHome()
{
return new ModelAndView("home");
}
}
| [
"saindiana07@gmail.com"
] | saindiana07@gmail.com |
f3ac246fe56bcb3a1c55b06ceb2a54c3e1b45ed3 | a04cb802bb99cd3bd8162d271d438e66771dba35 | /src/Class30/SetsDemo2.java | 27c5c5cda5e2692566430eafe5734ced726a34ce | [] | no_license | alexm3726/Batch9IntelliJ | ff2f1f077997dcf4040e51133f287575707a4519 | fc4afbc798a9d17c7e547f2474073fa9a167c43b | refs/heads/main | 2023-04-20T18:47:40.766233 | 2021-05-14T07:48:17 | 2021-05-14T07:48:17 | 353,596,059 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 559 | java | package Class30;
import java.util.*;
public class SetsDemo2 {
public static void main(String[] args) {
ArrayList<Integer> arrayList=new ArrayList<>();
arrayList.add(10);
arrayList.add(102);
arrayList.add(10);
arrayList.add(120);
arrayList.add(120);
arrayList.add(100);
arrayList.add(100);
arrayList.add(null);
Set<Integer> set=new HashSet<>(arrayList);
ArrayList<Integer> removedElements=new ArrayList<>(set);
System.out.println(removedElements);
}
}
| [
"alexm3726@gmail.com"
] | alexm3726@gmail.com |
aae30ec4b76a3eb0317c617c91b15a12ffc6f503 | 2d53d6f8d3e0e389bba361813e963514fdef3950 | /Sql_injection/s03/CWE89_SQL_Injection__getQueryString_Servlet_execute_67b.java | fa226b9f5296e10a9630f2a13ae80ab790198772 | [] | no_license | apobletts/ml-testing | 6a1b95b995fdfbdd68f87da5f98bd969b0457234 | ee6bb9fe49d9ec074543b7ff715e910110bea939 | refs/heads/master | 2021-05-10T22:55:57.250937 | 2018-01-26T20:50:15 | 2018-01-26T20:50:15 | 118,268,553 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 6,608 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE89_SQL_Injection__getQueryString_Servlet_execute_67b.java
Label Definition File: CWE89_SQL_Injection.label.xml
Template File: sources-sinks-67b.tmpl.java
*/
/*
* @description
* CWE: 89 SQL Injection
* BadSource: getQueryString_Servlet Parse id param out of the URL query string (without using getParameter())
* GoodSource: A hardcoded string
* Sinks: execute
* GoodSink: Use prepared statement and execute (properly)
* BadSink : data concatenated into SQL statement used in execute(), which could result in SQL Injection
* Flow Variant: 67 Data flow: data passed in a class from one method to another in different source files in the same package
*
* */
package testcases.CWE89_SQL_Injection.s03;
import testcasesupport.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.logging.Level;
public class CWE89_SQL_Injection__getQueryString_Servlet_execute_67b
{
public void badSink(CWE89_SQL_Injection__getQueryString_Servlet_execute_67a.Container dataContainer , HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data = dataContainer.containerOne;
Connection dbConnection = null;
Statement sqlStatement = null;
try
{
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.createStatement();
/* PRAETORIAN: data concatenated into SQL statement used in execute(), which could result in SQL Injection */
Boolean result = sqlStatement.execute("insert into users (status) values ('updated') where name='"+data+"'");
if(result)
{
IO.writeLine("Name, " + data + ", updated successfully");
}
else
{
IO.writeLine("Unable to update records for user: " + data);
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink(CWE89_SQL_Injection__getQueryString_Servlet_execute_67a.Container dataContainer , HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data = dataContainer.containerOne;
Connection dbConnection = null;
Statement sqlStatement = null;
try
{
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.createStatement();
/* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */
Boolean result = sqlStatement.execute("insert into users (status) values ('updated') where name='"+data+"'");
if(result)
{
IO.writeLine("Name, " + data + ", updated successfully");
}
else
{
IO.writeLine("Unable to update records for user: " + data);
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
/* goodB2G() - use badsource and goodsink */
public void goodB2GSink(CWE89_SQL_Injection__getQueryString_Servlet_execute_67a.Container dataContainer , HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data = dataContainer.containerOne;
Connection dbConnection = null;
PreparedStatement sqlStatement = null;
try
{
/* FIX: Use prepared statement and execute (properly) */
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlStatement.setString(1, data);
Boolean result = sqlStatement.execute();
if (result)
{
IO.writeLine("Name, " + data + ", updated successfully");
}
else
{
IO.writeLine("Unable to update records for user: " + data);
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
}
| [
"anna.pobletts@praetorian.com"
] | anna.pobletts@praetorian.com |
01cbac62a593c6cee634e246f30cec33df2db981 | ed068591f3111c344bb39438f4d51ed5476da01b | /3.1-DAM_-_Dispozitive-si-aplicatii-mobile/ToDoApp/app/src/androidTest/java/ro/liis/todoapp/ExampleInstrumentedTest.java | be9b77c0cdaa8c38191327d46da0dc492415b6de | [] | no_license | maximcovali/Anul_3-Sem_1 | efe029b3c11cf011403dc67e7e26496ea9669335 | 2080efd182d0f3717dc21e86ebcbff2a7598d579 | refs/heads/master | 2020-12-29T16:42:27.005011 | 2019-07-09T08:27:47 | 2019-07-09T08:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 714 | java | package ro.liis.todoapp;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("ro.liis.todoapp", appContext.getPackageName());
}
}
| [
"richtercristina@gmail.com"
] | richtercristina@gmail.com |
ecd35673730fd46f966597319b5b3ae23c05546e | c0ed54a1bc9fb3ff6ddeca5693b290c6f624e988 | /src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin/src/org/robotframework/ide/eclipse/main/plugin/assist/RedSettingProposal.java | 102fae24e13778f4c4a2a791ac8a027a401680ee | [
"Apache-2.0"
] | permissive | szkatu/RED | 7e81e2cba09fd2b83b33bfc87cc7886c773fd603 | f4499ffdc753e67ec75abbfaaafad99c4e236b3e | refs/heads/master | 2020-03-12T15:53:40.544405 | 2018-03-19T09:07:47 | 2018-03-19T09:07:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,044 | java | /*
* Copyright 2016 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.assist;
import org.eclipse.jface.resource.ImageDescriptor;
import org.robotframework.ide.eclipse.main.plugin.RedImages;
import org.robotframework.ide.eclipse.main.plugin.assist.RedSettingProposals.SettingTarget;
class RedSettingProposal extends BaseAssistProposal {
private final SettingTarget target;
RedSettingProposal(final String settingName, final SettingTarget target, final ProposalMatch match) {
super(settingName, match);
this.target = target;
}
@Override
public ImageDescriptor getImage() {
return RedImages.getRobotSettingImage();
}
@Override
public boolean hasDescription() {
return true;
}
@Override
public String getDescription() {
return RedSettingProposals.getSettingDescription(target, content, "");
}
}
| [
"CI-nokia@users.noreply.github.com"
] | CI-nokia@users.noreply.github.com |
e3b860f571aa7900c1f755d71ab86a4b0eec3776 | 297636f772f723a7cb6b72d1023654194877e9de | /src/main/java/week2/MergeLead.java | aa7da0125d3650c90187b3ed97a2c482896ba1ce | [] | no_license | deepthiravilla/testing | 6e9384a7fe216e7bef7b5a8ded818375ead300a8 | fab36c3df9ef582acf9c9679e5fba43ca5f86885 | refs/heads/master | 2020-03-28T10:17:23.009457 | 2018-09-10T07:06:12 | 2018-09-10T07:06:12 | 148,097,691 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,428 | java |
package week2;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;
public class MergeLead {
public static void main(String[] args) throws InterruptedException, IOException {
// setting chrome driver path
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
// launching chrome browser
ChromeDriver driver = new ChromeDriver();
// load URL
driver.navigate().to("http://leaftaps.com/opentaps");
// driver.get("http://leaftaps.com/opentaps");
// maximize browser
driver.manage().window().maximize();
// adding implicit wait to identify webelements within the specified time
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
// enter user name
driver.findElementByXPath("//input[@id='username']").sendKeys("DemoSalesManager");
// enter password
driver.findElementByXPath("//input[@id='password']").sendKeys("crmsfa");
// click login button
driver.findElementByXPath("//input[@class='decorativeSubmit']").click();
// click crm/sfa link
driver.findElementByXPath("//a[contains(text(),'CRM/SFA')]").click();
// click leads tap
driver.findElementByXPath("//a[text()='Leads']").click();
// click Merge button
driver.findElementByXPath("//a[text()='Merge Leads']").click();
// click From lookup
driver.findElementByXPath("//img[@src='/images/fieldlookup.gif'][1]").click();
// get all the opened window references
Set<String> allSetWindowRef = driver.getWindowHandles();
// copy set value to list
List<String> allListWindowRef = new ArrayList<String>();
allListWindowRef.addAll(allSetWindowRef);
// switch to the newly opened window
driver.switchTo().window(allListWindowRef.get(1));
// enter first name
driver.findElementByXPath("//input[@name='firstName']").sendKeys("kos");
// click find lead button
driver.findElementByXPath("//button[text()='Find Leads']").click();
// to avoid stale element exception using Thread.sleep method
Thread.sleep(3000);
// fetch first displayed id
String firstLeadID = driver.findElementByXPath("(//div[@class='x-grid3-cell-inner x-grid3-col-partyId'])[1]").getText();
System.out.println("First lead id: "+firstLeadID);
// click first displayed lead id
driver.findElementByXPath("(//div[@class='x-grid3-cell-inner x-grid3-col-partyId'])[1]/a").click();
// get all the window reference to switch back to original window
allSetWindowRef = driver.getWindowHandles();
// copy set to list
allListWindowRef = new ArrayList<String>();
allListWindowRef.addAll(allSetWindowRef);
// switch to original window
driver.switchTo().window(allListWindowRef.get(0));
// verify the first displayed id entered in the text box after fetching
String verifyFirstName = driver.findElementByXPath("//input[@id='ComboBox_partyIdFrom']").getAttribute("value");
if(verifyFirstName.equals(firstLeadID))
{
System.out.println("First lead id is entered correctly in the From lead text box: "+verifyFirstName);
}
else
{
System.out.println("First lead id is not entered correctly in the From lead text box: "+verifyFirstName);
}
// click To lead button
driver.findElementByXPath("//span[text()='To Lead']//following::a/img[@src='/images/fieldlookup.gif']").click();
// Thread.sleep(3000);
// get all the opened window references
allSetWindowRef = driver.getWindowHandles();
// copy set value to list
allListWindowRef = new ArrayList<String>();
allListWindowRef.addAll(allSetWindowRef);
// System.out.println(allListWindowRef.size());
driver.switchTo().window(allListWindowRef.get(1));
// enter first name
driver.findElementByXPath("//input[@name='firstName']").sendKeys("Kums");
// click find lead button
driver.findElementByXPath("//button[text()='Find Leads']").click();
// to avoid stale element exception using Thread.sleep method
Thread.sleep(3000);
// fetch first displayed id
String secondLeadID = driver.findElementByXPath("(//div[@class='x-grid3-cell-inner x-grid3-col-partyId'])[2]").getText();
// System.out.println("Second lead id: "+secondLeadID);
// click Second displayed lead id
driver.findElementByXPath("(//div[@class='x-grid3-cell-inner x-grid3-col-partyId'])[2]/a").click();
// get all the opened window references
allSetWindowRef = driver.getWindowHandles();
// copy set value to list
allListWindowRef = new ArrayList<String>();
allListWindowRef.addAll(allSetWindowRef);
// System.out.println(allListWindowRef.size());
driver.switchTo().window(allListWindowRef.get(0));
// verify the first displayed id entered in the text box after fetching
String verifySecondName = driver.findElementByXPath("//input[@id='ComboBox_partyIdTo']").getAttribute("value");
if(verifySecondName.equals(secondLeadID))
{
System.out.println("Second lead id is entered correctly in the To lead text box: "+verifySecondName);
}
else
{
System.out.println("Second lead id is not entered correctly in the To lead text box: "+verifySecondName);
}
// click Merge button
driver.findElementByXPath("//a[text()='Merge']").click();
// switch to pop up
driver.switchTo().alert().accept();
// click Find Lead button
driver.findElementByXPath("//a[text()='Find Leads']").click();
// Enter Lead id
driver.findElementByXPath("//input[@name='id']").sendKeys(firstLeadID);
// click Find Lead button
driver.findElementByXPath("//button[text()='Find Leads']").click();
// Verifying the text "No records to display"
String noRecordsMessage = driver.findElementByXPath("//div[text()='No records to display']").getText();
// System.out.println("Final message after merging: "+noRecordsMessage);
if(noRecordsMessage.equals("No records to display"))
{
System.out.println("Merge is happened correctly: "+noRecordsMessage);
}
else
{
System.out.println("Merge is not happened correctly: "+noRecordsMessage);
}
// take screenshot
File srcLoc = driver.getScreenshotAs(OutputType.FILE);
File destinationLoc = new File("./snaps/NoRecordsToDisplayMessage.png");
FileUtils.copyFile(srcLoc, destinationLoc);
// close browser
driver.close();
}
} | [
"user@dell"
] | user@dell |
f3a13bf01234482e84a6278216d69a7f67ae0ac4 | 4aa90348abcb2119011728dc067afd501f275374 | /app/src/main/java/com/tencent/mm/ui/chatting/AppAttachDownloadUI$5.java | 4adf4754497897a6610590fe6a452618cd7dcb13 | [] | no_license | jambestwick/HackWechat | 0d4ceb2d79ccddb45004ca667e9a6a984a80f0f6 | 6a34899c8bfd50d19e5a5ec36a58218598172a6b | refs/heads/master | 2022-01-27T12:48:43.446804 | 2021-12-29T10:36:30 | 2021-12-29T10:36:30 | 249,366,791 | 0 | 0 | null | 2020-03-23T07:48:32 | 2020-03-23T07:48:32 | null | UTF-8 | Java | false | false | 2,201 | java | package com.tencent.mm.ui.chatting;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.modelcdntran.g;
import com.tencent.mm.pluginsdk.model.app.ab;
import com.tencent.mm.pluginsdk.model.app.ab.a;
import com.tencent.mm.pluginsdk.model.app.an;
import com.tencent.mm.sdk.e.c;
import com.tencent.mm.sdk.platformtools.bh;
import com.tencent.mm.sdk.platformtools.x;
class AppAttachDownloadUI$5 implements OnClickListener {
final /* synthetic */ AppAttachDownloadUI ypv;
AppAttachDownloadUI$5(AppAttachDownloadUI appAttachDownloadUI) {
this.ypv = appAttachDownloadUI;
}
public final void onClick(View view) {
AppAttachDownloadUI.k(this.ypv).setVisibility(8);
AppAttachDownloadUI.l(this.ypv).setVisibility(0);
AppAttachDownloadUI.m(this.ypv).setVisibility(8);
x.i("MicroMsg.AppAttachDownloadUI", "summerapp stopBtn downloadAppAttachScene[%s]", new Object[]{AppAttachDownloadUI.a(this.ypv)});
if (AppAttachDownloadUI.a(this.ypv) != null) {
ab a = AppAttachDownloadUI.a(this.ypv);
a aVar = this.ypv;
if (!a.veL) {
g.MJ().kI(a.hBn);
a.veF = an.aqd().Rz(a.mediaId);
}
x.i("MicroMsg.NetSceneDownloadAppAttach", "summerbig pause listener[%s], info[%s], justSaveFile[%b], stack[%s]", new Object[]{aVar, a.veF, Boolean.valueOf(a.veL), bh.cgy()});
if (a.veF != null) {
if (a.veF.field_status == 101 && aVar != null) {
aVar.bYO();
}
a.veF.field_status = 102;
if (!a.veL) {
an.aqd().c(a.veF, new String[0]);
}
}
com.tencent.mm.kernel.g.CG().c(AppAttachDownloadUI.a(this.ypv));
return;
}
c o = AppAttachDownloadUI.o(this.ypv);
if (o != null && o.field_status != 199) {
x.i("MicroMsg.AppAttachDownloadUI", "summerapp stopBtn onClick but scene is null and set status[%d] paused", new Object[]{Long.valueOf(o.field_status)});
o.field_status = 102;
an.aqd().c(o, new String[0]);
}
}
}
| [
"malin.myemail@163.com"
] | malin.myemail@163.com |
8bc32e0a0bff981079557b2ff246c8cad9517aa2 | fbb9c1e8a8c76dc7bd78b218748bd250df54c63e | /src/com/ssf/edog/receiver/LaunchKeyguardReceiver.java | d0e916690f57a39c162939b96efc8064ddb5163a | [] | no_license | chenyi2013/Ed | 394bad33a5eecfa68345cdf81243a4008c06fcf3 | 0d45088af173cb9f7159b34844986e26aef4b8ed | refs/heads/master | 2021-01-19T17:42:27.456881 | 2014-09-03T07:18:12 | 2014-09-03T07:18:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 616 | java | package com.ssf.edog.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ssf.edog.KeyguardActivity;
import com.ssf.edog.config.Config;
public class LaunchKeyguardReceiver extends BroadcastReceiver {
public LaunchKeyguardReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.LAUNCH_KEYGUAGRD_ACTION)) {
Intent newIntent = new Intent(context, KeyguardActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
}
}
}
| [
"chenyi_de_email@163.com"
] | chenyi_de_email@163.com |
674593aaf33d2141538808bf96917f6e19759c88 | 7933ef7f49581c2c19a9682c4be593223a28342d | /src/com/goit/gojavaonline/codegym/practice3/RectangleSquare.java | 7c95f15348ba6feb570acc096b6e4a2a192f627a | [] | no_license | tamila27/Codegym | 7b1481ac426e6b580f7111dd4373a5785923fe0f | 96f692e87bf0d1d5bb3558667c3548e668bc6506 | refs/heads/master | 2020-12-24T19:12:41.648653 | 2016-06-04T10:50:03 | 2016-06-04T10:50:03 | 58,211,354 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,933 | java | package com.goit.gojavaonline.codegym.practice3;
/**
* Created by tamila on 5/20/16.
*/
public class RectangleSquare {
public int measure(int[] x, int[] h, int[] w) {
int maxX = 0;
int maxY = 0;
for (int i = 0; i < x.length; i++) {
if(maxX < x[i]+w[i]) maxX = x[i] + w[i];
}
for (int i = 0; i < h.length; i++) {
if(maxY < h[i]) maxY = h[i];
}
int resultSquare = 0;
boolean[][] coordinatesPlane = new boolean[maxX][maxY];
for (int i = 0; i < x.length; i++) {
int xEndIndex = x[i] + w[i];
int yEndIndex = h[i];
for (int j = x[i]; j < xEndIndex; j++) {
for (int k = 0; k < yEndIndex; k++) {
if(!coordinatesPlane[j][k]) resultSquare++;
coordinatesPlane[j][k] = true;
}
}
}
System.out.println(resultSquare);
return resultSquare;
/*int maxX = 0;
int maxY = 0;
for (int i = 0; i < x.length; i++) {
if(maxX < x[i]+w[i]) maxX = x[i] + w[i];
}
for (int i = 0; i < h.length; i++) {
if(maxY < h[i]) maxY = h[i];
}
boolean[][] coordinatesPlane = new boolean[maxX][maxY];
for (int i = 0; i < x.length; i++) {
int xEndIndex = x[i] + w[i];
int yEndIndex = h[i];
for (int j = x[i]; j < xEndIndex; j++) {
for (int k = 0; k < yEndIndex; k++) {
coordinatesPlane[j][k] = true;
}
}
}
int resultSquare = 0;
for (int i = 0; i < coordinatesPlane.length; i++) {
for (int j = 0; j < coordinatesPlane[0].length; j++) {
if(coordinatesPlane[i][j]) resultSquare++;
}
}
System.out.println(resultSquare);
return resultSquare;*/
}
}
| [
"tamilaasanova@gmail.com"
] | tamilaasanova@gmail.com |
dedbd32c58bb7121c50218fe43f4391119829a1d | ccf0c00e5b8ff38dcc5cb3e58cb6b68bf8a39d9b | /Proyecto_Final/src/Conexion/Auto_APP.java | c661d0719b1d4ab4a88a4608884b1f3073d26a17 | [] | no_license | ShoferxDJ/Proyecto-Final-Menu | 3cad145e72a3ccc73b21b68ae84cb99c567b13e8 | ca8c3b3408811c4bf93568a41b5b68007eb20fbf | refs/heads/master | 2022-11-11T16:40:47.870680 | 2020-06-29T15:55:32 | 2020-06-29T15:55:32 | 275,862,604 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,303 | java | package Conexion;
import java.util.Scanner;
import Controlador.AutoControlador;
import Modelo.Auto;
public class Auto_APP {
public static void main(String[] args) {
// TODO Auto-generated method stub
Auto auto = new Auto();
AutoControlador autoC = new AutoControlador ();
Scanner salida = new Scanner (System.in);
//---------CREAR AUTO----------//
/*auto.setIdproductos(1);
auto.setModelo("GT 2017");
auto.setMarca("Ford");
auto.setDescripcion("SUPER AUTO");
auto.setPrecio(3450000);
autoC.crearAuto(auto);*/
//---------ELIMINAR AUTO----------//
//autoC.eliminarAuto("2");
//---------CONSULTAR AUTO----------//
//autoC.consultarAuto("3");
//---------EDITAR AUTO----------//
/*auto.setIdproductos(2);
auto.setModelo("Versa TM 2020");
auto.setMarca("Nissan");
auto.setDescripcion("5 pasajeros\n"
+ "118 hp\n"
+ "torque 110-4000 RPM\n"
+ "Motor 1.6 Lt\n");
auto.setPrecio(285000);
autoC.editarAuto(auto);*/
//---------EDITAR AUTO OPCION NUMERO 2----------//
/*System.out.println("Ingrese el Nombre del producto: ");
String nombre = salida.next();
auto.setModelo(nombre);
System.out.println("Ingrese ID del producto: ");;
auto.setIdproductos(Integer.parseInt(salida.next()));
autoC.editarAuto(auto);*/
}
}
| [
"alexr@DESKTOP-6RLAL1L"
] | alexr@DESKTOP-6RLAL1L |
b638d6d9f987e15ac4a691ab7f1351c48babbc01 | f62627bfcf024e5b8606e523f90c0e8b16f2bf85 | /EContact/app/src/test/java/com/rajesh/helloworld/ExampleUnitTest.java | 7476e27bcf2054a8c74d29a84da84b0dcf70768e | [] | no_license | rajeshalane/Projects | 2b71f903feb438e7eb5117115fb9434d25e6d8cc | 14e662636043642f294590e66ee35b07fbf917fe | refs/heads/master | 2020-04-14T19:16:36.813174 | 2019-03-03T12:25:53 | 2019-03-03T12:25:53 | 164,052,078 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 382 | java | package com.rajesh.helloworld;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"rajesh.alane@gmail.com"
] | rajesh.alane@gmail.com |
2a2e1d187999ebdaa22963a8a64c7404a9965e08 | 0170437d02848f18e246e5babd878ff65a2de2ed | /library/src/com/marchah/uicomponent/Object/CameraOld.java | 023ba99ddedf0a6e6232822aa2a34ec8d5790785 | [] | no_license | marchah/UIComponent | 10aa38b8178469e9e8f08b3862740f6bd15f327c | cdb96a272c310a0e7518e7c02df4c16adeaeab03 | refs/heads/master | 2016-09-06T03:27:37.741029 | 2015-02-25T17:40:28 | 2015-02-25T17:40:28 | 30,187,781 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,281 | java | package com.marchah.uicomponent.Object;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Build;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.marchah.uicomponent.Listener.CameraListener;
import java.io.IOException;
import java.util.List;
/**
* Created by marcha on 04/02/15.
*/
public class CameraOld extends ACamera {
private Camera mCamera;
private Activity activity;
private SurfaceHolder holder;
private CameraOld(Activity activity, SurfaceHolder holder) throws Exception {
this.activity = activity;
this.holder = holder;
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
mCamera = null;
mCamera = Camera.open(currentCameraId);
Camera.Parameters params = mCamera.getParameters();
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.setParameters(params);
}
public void startPreview() throws IOException {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
}
public void stopPreview() {
mCamera.stopPreview();
}
public void release() {
if (mCamera != null)
mCamera.release();
}
private double PREVIEW_SIZE_FACTOR = 1.30;
public void setPreviewSize(int width, int height) {
final Camera.Parameters params = mCamera.getParameters();
Camera.Size size = getOptimalPreviewSize(params, width, height);
params.setPreviewSize(size.width, size.height);
size = getOptimalPictureSize(params);
params.setPictureSize(size.width, size.height);
mCamera.setParameters(params);
}
private Camera.Size getOptimalPictureSize(Camera.Parameters params) {
List<Camera.Size> sizes = params.getSupportedPictureSizes();
Camera.Size result = sizes.get(0);
for (int i = 0; i < sizes.size(); i++) {
if (sizes.get(i).width > result.width)
result = sizes.get(i);
}
return result;
}
private Camera.Size getOptimalPreviewSize(Camera.Parameters params, int width, int height) {
Camera.Size result = null;
for (final Camera.Size size : params.getSupportedPreviewSizes()) {
if (size.width <= width * PREVIEW_SIZE_FACTOR && size.height <= height * PREVIEW_SIZE_FACTOR) {
if (result == null) {
result = size;
} else {
final int resultArea = result.width * result.height;
final int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
if (result == null) {
result = params.getSupportedPreviewSizes().get(0);
}
return result;
}
private int getPictureRotation() {
// TODO: in landscape: one orientation ins't good
// http://stackoverflow.com/questions/4697631/android-screen-orientation
// http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation%28int%29
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(currentCameraId, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
return result;
}
public void setCameraDisplayOrientation() {
if (mCamera != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setRotation(getPictureRotation());
mCamera.setParameters(parameters);
} else {
mCamera.setDisplayOrientation(getPictureRotation());
}
}
}
public void switchCamera() throws Exception {
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
setCurrentCamera(currentCameraId);
}
public void setCurrentCamera(int cameraId) throws Exception {
if (holder != null) {
stopPreview();
release();
this.currentCameraId = cameraId;
mCamera = Camera.open(currentCameraId);
setCameraDisplayOrientation();
startPreview();
}
}
public boolean isZoomSupported() {
Camera.Parameters parameters = mCamera.getParameters();
return parameters.isZoomSupported();
}
public int getMaxZoom() {
Camera.Parameters parameters = mCamera.getParameters();
return parameters.getMaxZoom();
}
public void setZoom(int zoomLevel) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setZoom(zoomLevel);
mCamera.setParameters(parameters);
}
private CameraListener mListener = null;
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
// TODO: When camera front
// 1) device in portrait mode the picture is upside down
// 2) mirroring effect
matrix.postRotate(getPictureRotation());
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
mListener.onPictureTaken(bitmap);
mListener = null;
try {
startPreview();
}
catch (Exception e) {
e.printStackTrace();
}
}
};
public void takePicture(CameraListener listener) {
if (mListener == null) {
mListener = listener;
mCamera.takePicture(null, null, mPicture);
}
}
public static ICamera getCameraInstance(Activity activity, SurfaceHolder holder){
CameraOld c = null;
try {
c = new CameraOld(activity, holder);
}
catch (Exception e){
e.printStackTrace();
// TODO: log err
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
}
| [
"hugo.marchadier@smartplace.pro"
] | hugo.marchadier@smartplace.pro |
57764a3f056ac12e1902d1ce7ff639720f8a75bc | bf5f8a980e5b98f8a47611fbec97cedc7566922f | /src/at/jku/ssw/battleship/model/Field.java | bbc9eb1251b28ba034848802f42b146994b5246f | [] | no_license | Baumgartner-Lukas/se2-ue09-1455128-swing | 6957abba13c2b6a0eeda867a0e92befd847e482a | a4d784e7abcd74e8cec1accac7cee4057338ae4c | refs/heads/master | 2020-03-19T06:01:42.903749 | 2018-06-04T07:04:35 | 2018-06-04T07:04:35 | 135,984,408 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,185 | java | package at.jku.ssw.battleship.model;
import java.util.ArrayList;
import java.util.List;
public class Field {
private List<FieldListener> listeners = new ArrayList<>();
private State grid[][];
public Field(int size) {
if (size < 1) throw new IllegalArgumentException("Field size must be at least 1");
grid = new State[size][size];
for (int r = 0; r < size; r++) {
for (int c = 0; c < size; c++) {
grid[r][c] = State.FREE;
}
}
}
public State getState(int row, int column) {
if ((row > grid.length || row < 0) ||
(column > grid.length || column < 0)) return State.FREE;
return grid[row][column];
}
public void setState(int row, int column, State newState) {
grid[row][column] = newState;
}
public int getSize() {
return grid.length;
}
//ue-09-swing
public void addFieldListener(FieldListener listener) {
listeners.add(listener);
}
public void removeFieldListener(FieldListener listener) {
listeners.remove(listener);
}
public void fireFieldEvent() {
}
//ue-09-swing
}
| [
"baumgartner.webtree@gmail.com"
] | baumgartner.webtree@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.