file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
Maven__javax_javaee_web_api_7_0.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__javax_javaee_web_api_7_0.xml | <component name="libraryTable">
<library name="Maven: javax:javaee-web-api:7.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/javaee-web-api/7.0/javaee-web-api-7.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/javaee-web-api/7.0/javaee-web-api-7.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/javaee-web-api/7.0/javaee-web-api-7.0-sources.jar!/" />
</SOURCES>
</library>
</component> | 499 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__javax_enterprise_cdi_api_1_1.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__javax_enterprise_cdi_api_1_1.xml | <component name="libraryTable">
<library name="Maven: javax.enterprise:cdi-api:1.1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/enterprise/cdi-api/1.1/cdi-api-1.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/enterprise/cdi-api/1.1/cdi-api-1.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/enterprise/cdi-api/1.1/cdi-api-1.1-sources.jar!/" />
</SOURCES>
</library>
</component> | 494 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__javax_inject_javax_inject_1.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__javax_inject_javax_inject_1.xml | <component name="libraryTable">
<library name="Maven: javax.inject:javax.inject:1">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/inject/javax.inject/1/javax.inject-1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/inject/javax.inject/1/javax.inject-1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/inject/javax.inject/1/javax.inject-1-sources.jar!/" />
</SOURCES>
</library>
</component> | 499 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_jboss_spec_javax_annotation_jboss_annotations_api_1_2_spec_1_0_0_Final.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_jboss_spec_javax_annotation_jboss_annotations_api_1_2_spec_1_0_0_Final.xml | <component name="libraryTable">
<library name="Maven: org.jboss.spec.javax.annotation:jboss-annotations-api_1.2_spec:1.0.0.Final">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/annotation/jboss-annotations-api_1.2_spec/1.0.0.Final/jboss-annotations-api_1.2_spec-1.0.0.Final.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/annotation/jboss-annotations-api_1.2_spec/1.0.0.Final/jboss-annotations-api_1.2_spec-1.0.0.Final-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/annotation/jboss-annotations-api_1.2_spec/1.0.0.Final/jboss-annotations-api_1.2_spec-1.0.0.Final-sources.jar!/" />
</SOURCES>
</library>
</component> | 771 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_jboss_spec_javax_servlet_jboss_servlet_api_3_1_spec_1_0_0_Final.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_jboss_spec_javax_servlet_jboss_servlet_api_3_1_spec_1_0_0_Final.xml | <component name="libraryTable">
<library name="Maven: org.jboss.spec.javax.servlet:jboss-servlet-api_3.1_spec:1.0.0.Final">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/servlet/jboss-servlet-api_3.1_spec/1.0.0.Final/jboss-servlet-api_3.1_spec-1.0.0.Final.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/servlet/jboss-servlet-api_3.1_spec/1.0.0.Final/jboss-servlet-api_3.1_spec-1.0.0.Final-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/servlet/jboss-servlet-api_3.1_spec/1.0.0.Final/jboss-servlet-api_3.1_spec-1.0.0.Final-sources.jar!/" />
</SOURCES>
</library>
</component> | 731 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__javax_javaee_endorsed_api_7_0.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__javax_javaee_endorsed_api_7_0.xml | <component name="libraryTable">
<library name="Maven: javax:javaee-endorsed-api:7.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/javaee-endorsed-api/7.0/javaee-endorsed-api-7.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/javaee-endorsed-api/7.0/javaee-endorsed-api-7.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/javaee-endorsed-api/7.0/javaee-endorsed-api-7.0-sources.jar!/" />
</SOURCES>
</library>
</component> | 534 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_jboss_spec_javax_faces_jboss_jsf_api_2_2_spec_2_2_4.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_jboss_spec_javax_faces_jboss_jsf_api_2_2_spec_2_2_4.xml | <component name="libraryTable">
<library name="Maven: org.jboss.spec.javax.faces:jboss-jsf-api_2.2_spec:2.2.4">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/faces/jboss-jsf-api_2.2_spec/2.2.4/jboss-jsf-api_2.2_spec-2.2.4.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/faces/jboss-jsf-api_2.2_spec/2.2.4/jboss-jsf-api_2.2_spec-2.2.4-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/jboss/spec/javax/faces/jboss-jsf-api_2.2_spec/2.2.4/jboss-jsf-api_2.2_spec-2.2.4-sources.jar!/" />
</SOURCES>
</library>
</component> | 653 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_javassist_javassist_3_27_0_GA.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_javassist_javassist_3_27_0_GA.xml | <component name="libraryTable">
<library name="Maven: org.javassist:javassist:3.27.0-GA">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/javassist/javassist/3.27.0-GA/javassist-3.27.0-GA.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/javassist/javassist/3.27.0-GA/javassist-3.27.0-GA-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/javassist/javassist/3.27.0-GA/javassist-3.27.0-GA-sources.jar!/" />
</SOURCES>
</library>
</component> | 538 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__javax_validation_validation_api_1_1_0_Final.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml | <component name="libraryTable">
<library name="Maven: javax.validation:validation-api:1.1.0.Final">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final-sources.jar!/" />
</SOURCES>
</library>
</component> | 599 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__com_google_protobuf_protobuf_java_3_15_7.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__com_google_protobuf_protobuf_java_3_15_7.xml | <component name="libraryTable">
<library name="Maven: com.google.protobuf:protobuf-java:3.15.7">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/protobuf/protobuf-java/3.15.7/protobuf-java-3.15.7.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/com/google/protobuf/protobuf-java/3.15.7/protobuf-java-3.15.7-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/com/google/protobuf/protobuf-java/3.15.7/protobuf-java-3.15.7-sources.jar!/" />
</SOURCES>
</library>
</component> | 569 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__net_java_dev_jna_jna_4_1_0.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__net_java_dev_jna_jna_4_1_0.xml | <component name="libraryTable">
<library name="Maven: net.java.dev.jna:jna:4.1.0">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/net/java/dev/jna/jna/4.1.0/jna-4.1.0-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/net/java/dev/jna/jna/4.1.0/jna-4.1.0-sources.jar!/" />
</SOURCES>
</library>
</component> | 480 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_apache_maven_scm_maven_scm_provider_cvsjava_1_11_2.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_apache_maven_scm_maven_scm_provider_cvsjava_1_11_2.xml | <component name="libraryTable">
<library name="Maven: org.apache.maven.scm:maven-scm-provider-cvsjava:1.11.2">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/scm/maven-scm-provider-cvsjava/1.11.2/maven-scm-provider-cvsjava-1.11.2.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/scm/maven-scm-provider-cvsjava/1.11.2/maven-scm-provider-cvsjava-1.11.2-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/maven/scm/maven-scm-provider-cvsjava/1.11.2/maven-scm-provider-cvsjava-1.11.2-sources.jar!/" />
</SOURCES>
</library>
</component> | 664 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Maven__org_hibernate_javax_persistence_hibernate_jpa_2_1_api_1_0_0_Final.xml | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.idea/libraries/Maven__org_hibernate_javax_persistence_hibernate_jpa_2_1_api_1_0_0_Final.xml | <component name="libraryTable">
<library name="Maven: org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final-sources.jar!/" />
</SOURCES>
</library>
</component> | 708 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
MavenWrapperDownloader.java | /FileExtraction/Java_unseen/Jakarta-EE-Petclinic_petclinic-javaee7/.mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| 4,951 | Java | .java | Jakarta-EE-Petclinic/petclinic-javaee7 | 36 | 88 | 4 | 2014-01-09T21:21:37Z | 2022-06-30T22:52:54Z |
Gradle__javax_inject_javax_inject_1.xml | /FileExtraction/Java_unseen/austin2035_hermit/.idea/libraries/Gradle__javax_inject_javax_inject_1.xml | <component name="libraryTable">
<library name="Gradle: javax.inject:javax.inject:1">
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/javax.inject/javax.inject/1/6975da39a7040257bd51d21a231b76c915872d38/javax.inject-1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/javax.inject/javax.inject/1/70ec961c25111ed9015d1af77772d96383c2d238/javax.inject-1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/javax.inject/javax.inject/1/a00123f261762a7c5e0ec916a2c7c8298d29c400/javax.inject-1-sources.jar!/" />
</SOURCES>
</library>
</component> | 707 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
Gradle__com_squareup_javawriter_2_1_1.xml | /FileExtraction/Java_unseen/austin2035_hermit/.idea/libraries/Gradle__com_squareup_javawriter_2_1_1.xml | <component name="libraryTable">
<library name="Gradle: com.squareup:javawriter:2.1.1">
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.squareup/javawriter/2.1.1/67ff45d9ae02e583d0f9b3432a5ebbe05c30c966/javawriter-2.1.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.squareup/javawriter/2.1.1/f591a105db78771d0a1e7a277b3747556c528c22/javawriter-2.1.1-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.squareup/javawriter/2.1.1/5b31387d839a5cdaf5b6de3990da01f7f2b963c5/javawriter-2.1.1-sources.jar!/" />
</SOURCES>
</library>
</component> | 721 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
ExampleUnitTest.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/test/java/com/lookcos/hermit/ExampleUnitTest.java | package com.lookcos.hermit;
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);
}
} | 379 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
ShellUtils.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/main/java/com/lookcos/hermit/ShellUtils.java | package com.lookcos.hermit;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
/**
* 应用执行shell命令
* 看到了一个博主写的很好就直接拿过来了
* 原文链接:https://www.cnblogs.com/zhujiabin/p/10495214.html
* */
public class ShellUtils {
public static final String COMMAND_SU = "su";
public static final String COMMAND_SH = "sh";
public static final String COMMAND_EXIT = "exit\n";
public static final String COMMAND_LINE_END = "\n";
private ShellUtils() {
throw new AssertionError();
}
/**
* 查看是否有了root权限
*
* @return
*/
public static boolean checkRootPermission() {
return execCommand("echo root", true, false).result == 0;
}
/**
* 执行shell命令,默认返回结果
*
* @param command
* command
* @param 运行是否需要root权限
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String command, boolean isRoot) {
return execCommand(new String[] { command }, isRoot, true);
}
/**
* 执行shell命令,默认返回结果
*
* @param commands
* command list
* @param 运行是否需要root权限
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(List<String> commands,
boolean isRoot) {
return execCommand(
commands == null ? null : commands.toArray(new String[] {}),
isRoot, true);
}
/**
* 执行shell命令,默认返回结果
*
* @param commands
* command array
* @param 运行是否需要root权限
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String[] commands, boolean isRoot) {
return execCommand(commands, isRoot, true);
}
/**
* execute shell command
*
* @param command
* command
* @param 运行是否需要root权限
* @param isNeedResultMsg
* whether need result msg
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(String command, boolean isRoot,
boolean isNeedResultMsg) {
return execCommand(new String[] { command }, isRoot, isNeedResultMsg);
}
/**
* execute shell commands
*
* @param commands
* command list
* @param 运行是否需要root权限
* @param 是否需要返回运行结果
* @return
* @see ShellUtils#execCommand(String[], boolean, boolean)
*/
public static CommandResult execCommand(List<String> commands,
boolean isRoot, boolean isNeedResultMsg) {
return execCommand(
commands == null ? null : commands.toArray(new String[] {}),
isRoot, isNeedResultMsg);
}
/**
* execute shell commands
*
* @param commands
* command array
* @param 运行是否需要root权限
* @param 是否需要返回运行结果
* @return <ul>
* <li>if isNeedResultMsg is false, {@link CommandResult#successMsg}
* is null and {@link CommandResult#errorMsg} is null.</li>
* <li>if {@link CommandResult#result} is -1, there maybe some
* excepiton.</li>
* </ul>
*/
public static CommandResult execCommand(String[] commands, boolean isRoot,
boolean isNeedResultMsg) {
int result = -1;
if (commands == null || commands.length == 0) {
return new CommandResult(result, null, null);
}
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = null;
StringBuilder errorMsg = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec(
isRoot ? COMMAND_SU : COMMAND_SH);
os = new DataOutputStream(process.getOutputStream());
for (String command : commands) {
if (command == null) {
continue;
}
// donnot use os.writeBytes(commmand), avoid chinese charset
// error
os.write(command.getBytes());
os.writeBytes(COMMAND_LINE_END);
os.flush();
}
os.writeBytes(COMMAND_EXIT);
os.flush();
result = process.waitFor();
// get command result
if (isNeedResultMsg) {
successMsg = new StringBuilder();
errorMsg = new StringBuilder();
successResult = new BufferedReader(new InputStreamReader(
process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
return new CommandResult(result, successMsg == null ? null
: successMsg.toString(), errorMsg == null ? null
: errorMsg.toString());
}
/**
* 运行结果
* <ul>
* <li>{@link CommandResult#result} means result of command, 0 means normal,
* else means error, same to excute in linux shell</li>
* <li>{@link CommandResult#successMsg} means success message of command
* result</li>
* <li>{@link CommandResult#errorMsg} means error message of command result</li>
* </ul>
*
* @author <a href="http://www.trinea.cn" target="_blank">Trinea</a>
* 2013-5-16
*/
public static class CommandResult {
/** 运行结果 **/
public int result;
/** 运行成功结果 **/
public String successMsg;
/** 运行失败结果 **/
public String errorMsg;
public CommandResult(int result) {
this.result = result;
}
public CommandResult(int result, String successMsg, String errorMsg) {
this.result = result;
this.successMsg = successMsg;
this.errorMsg = errorMsg;
}
}
} | 7,509 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
AppConfig.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/main/java/com/lookcos/hermit/AppConfig.java | package com.lookcos.hermit;
import android.content.Context;
import com.yanzhenjie.andserver.annotation.Config;
import com.yanzhenjie.andserver.framework.config.Multipart;
import com.yanzhenjie.andserver.framework.config.WebConfig;
import com.yanzhenjie.andserver.framework.website.AssetsWebsite;
import java.io.File;
@Config
public class AppConfig implements WebConfig {
@Override
public void onConfig(Context context, Delegate delegate) {
delegate.addWebsite(new AssetsWebsite(context, "/web"));
delegate.setMultipart(Multipart.newBuilder()
.allFileMaxSize(1024 * 1024 * 20) // 20M
.fileMaxSize(1024 * 1024 * 5) // 5M
.maxInMemorySize(1024 * 10) // 1024 * 10 bytes
.uploadTempDir(new File(context.getCacheDir(), "_server_upload_cache_"))
.build());
}
} | 867 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
AccessbilityCore.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/main/java/com/lookcos/hermit/AccessbilityCore.java | package com.lookcos.hermit;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.accessibilityservice.GestureDescription;
import android.graphics.Bitmap;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.accessibilityservice.AccessibilityService;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONException;
import static android.view.Display.DEFAULT_DISPLAY;
public class AccessbilityCore extends AccessibilityService {
public static String TAG = "HermitOut";
public static AccessbilityCore aServer;
private static AccessibilityEvent mAccessibilityEvent = null;
private static AccessibilityService mAccessibilityService = null;
public static AccessibilityNodeInfo activeNodeInfo = null;
public static List<AccessibilityNodeInfo> listNodeInfo = new ArrayList<AccessibilityNodeInfo>();
String regexId = ".*boundsInParent: Rect(.*?); boundsInScreen: Rect(.*?); .*";
Pattern rID = Pattern.compile(regexId);
public static int result;
public static Intent intentData;
public static MediaProjectionManager mMediaProjectionManager;
private static Handler handler = new Handler(Looper.myLooper());
JSONArray nodes = new JSONArray();
public static JSONArray newNodes = new JSONArray();
//初始化
@Override
protected void onServiceConnected() {
super.onServiceConnected();
aServer = this;
}
@Override
public void onInterrupt() {
aServer = null;
}
@Override
public void onDestroy() {
super.onDestroy();
aServer = null;
}
@Override
public void onCreate() {
super.onCreate();
AccessbilityCore.setAccessibilityService(this);
}
/**
* 设置数据
*
* @param service
* @param
*/
public static void setAccessibilityService(AccessibilityService service) {
synchronized (AccessbilityCore.class)
{
if (service != null && mAccessibilityService == null)
{
mAccessibilityService = service;
}
}
}
public static AccessibilityService getmAccessibilityService() {
return mAccessibilityService;
}
public static void performAction(int action){
mAccessibilityService.performGlobalAction(action);
return ;
}
/**
* 屏幕截图
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void ScreenShotByAB() {
MainActivity activity = (MainActivity) MainActivity.context;
if (mMediaProjectionManager == null) {
mMediaProjectionManager =
(MediaProjectionManager) activity.getApplication().getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
activity.startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), 200);
} else {
generatorPicture(activity, result, intentData);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static void generatorPicture(Activity activity, int resultCode, Intent data) {
MediaProjection mMediaProjection =
mMediaProjectionManager.getMediaProjection(resultCode, data);
Resources resources = activity.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
int density = dm.densityDpi;
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
ImageReader mImageReader =
ImageReader.newInstance(screenWidth, screenHeight, 0x1,
2);
VirtualDisplay mVirtualDisplay =
mMediaProjection.createVirtualDisplay("screen-mirror",
screenWidth, screenHeight, density,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mImageReader.getSurface(), null, null);
String filepath = "/storage/emulated/0/Pictures/HermitScreenShot.jpg";
mImageReader.setOnImageAvailableListener((ImageReader.OnImageAvailableListener) reader -> {
try {
Image image = reader.acquireLatestImage();
int width = image.getWidth();
int height = image.getHeight();
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height,
Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
image.close();
if (mVirtualDisplay != null) {
mVirtualDisplay.release();
}
//保存图片
FileOutputStream fos = new FileOutputStream(filepath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("generatorPicture", "Exception e : " + e);
}
}, handler);
}
/**
* 模拟点击某个节点
*
* @param nodeInfo nodeInfo
*/
public static boolean performViewClick(AccessibilityNodeInfo nodeInfo) {
boolean res = false;
if (nodeInfo == null)
{
return res;
}
while (nodeInfo != null)
{
if (nodeInfo.isClickable())
{
res = nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
break;
}
nodeInfo = nodeInfo.getParent();
}
return res;
}
//通过坐标点击具体坐标
@RequiresApi(api = Build.VERSION_CODES.N)
public static boolean clickByCoordinate(int x, int y) {
AccessibilityService service = mAccessibilityService;
Path path = new Path();
path.moveTo(x, y);
GestureDescription.Builder builder = new GestureDescription.Builder();
GestureDescription gestureDescription = builder.addStroke(new GestureDescription.StrokeDescription(path, 0, 200)).build();
return service.dispatchGesture(gestureDescription, new AccessibilityService.GestureResultCallback() {
@Override
public void onCompleted(GestureDescription gestureDescription) {
super.onCompleted(gestureDescription);
}
}, null);
}
// 根据坐标来滑动
@RequiresApi(api = Build.VERSION_CODES.N)
public static boolean swipeByCoordinate(int x0, int y0, int x1, int y1, int ms) {
AccessibilityService service = mAccessibilityService;
Path path = new Path();
path.moveTo(x0, y0);
path.lineTo(x1, y1);
GestureDescription.Builder builder = new GestureDescription.Builder();
GestureDescription gestureDescription = builder.addStroke(new GestureDescription.StrokeDescription(path, 0, ms)).build();
return service.dispatchGesture(gestureDescription, new AccessibilityService.GestureResultCallback() {
@Override
public void onCompleted(GestureDescription gestureDescription) {
super.onCompleted(gestureDescription);
}
}, null);
}
// 统计 text或id的控件数量
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static int countAttrNum(String attr, String val){
AccessibilityNodeInfo accessibilityNodeInfo = activeNodeInfo;
List<AccessibilityNodeInfo> nodeInfoList = null;
if (attr.equals("text")){
nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(val);
}else {
nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(val);
}
return nodeInfoList.size();
}
/**
* 根据text查找并点击该节点
*
* @param text
*/
public static boolean clickTextViewByText(String text, int index) {
boolean res = false;
AccessibilityNodeInfo accessibilityNodeInfo = activeNodeInfo;
if (accessibilityNodeInfo == null)
{
return res;
}
List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
if (nodeInfoList != null && !nodeInfoList.isEmpty())
{
if (index < 999){
return performViewClick(nodeInfoList.get(index));
}
for (AccessibilityNodeInfo nodeInfo : nodeInfoList)
{
if (nodeInfo != null)
{
res = performViewClick(nodeInfo);
break;
}
}
}
return res;
}
/**
* 根据Id查找并点击该节点
*
* @param id
* @return
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static boolean clickTextViewByID(String id, int index) {
boolean res = false;
AccessibilityNodeInfo accessibilityNodeInfo = activeNodeInfo;
if (accessibilityNodeInfo == null)
{
return res;
}
List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
if (nodeInfoList != null && !nodeInfoList.isEmpty())
{
if (index < 999){
return performViewClick(nodeInfoList.get(index));
}
for (AccessibilityNodeInfo nodeInfo : nodeInfoList)
{
if (nodeInfo != null)
{
res = performViewClick(nodeInfo);
break;
}
}
}
return res;
}
/**
* 根据描述查找控件
*
* @param des
* @return
*/
public static boolean clickViewByDesc(String des) {
boolean res = false;
if (des == null || "".equals(des))
{
return res;
}
List<AccessibilityNodeInfo> lists = listNodeInfo;
for (AccessibilityNodeInfo node : lists)
{
CharSequence desc = node.getContentDescription();
if (desc != null && des.equals(desc.toString()))
{
res = performViewClick(node);
break;
}
}
return res;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
AccessibilityNodeInfo rowNode = getRootInActiveWindow();
activeNodeInfo = rowNode;
if (rowNode == null) {
Log.i(TAG, "noteInfo is null");
return;
} else {
// 先清空数据
listNodeInfo.clear();
nodes.removeAll(nodes);
// 递归遍历添加数据
try {
recycle(rowNode);
} catch (JSONException e) {
e.printStackTrace();
}
NodeInfo ni = new NodeInfo();
ni.changeNodes(nodes);
}
}
/**
* 查找对应文本的View
*
* @param text text
* @return View
*/
public static AccessibilityNodeInfo findViewByText(String text) {
AccessibilityNodeInfo accessibilityNodeInfo = activeNodeInfo;
if (accessibilityNodeInfo == null)
{
return null;
}
List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByText(text);
if (nodeInfoList != null && !nodeInfoList.isEmpty())
{
for (AccessibilityNodeInfo nodeInfo : nodeInfoList)
{
if (nodeInfo != null && nodeInfo.getText() != null && nodeInfo.getText().toString().equals(text))
{
return nodeInfo;
}
}
}
return null;
}
/**
* 查找对应ID的View
*
* @param id id
* @return View
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static AccessibilityNodeInfo findViewByID(String id) {
AccessibilityNodeInfo accessibilityNodeInfo = activeNodeInfo;
if (accessibilityNodeInfo == null)
{
return null;
}
List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
if (nodeInfoList != null && !nodeInfoList.isEmpty())
{
for (AccessibilityNodeInfo nodeInfo : nodeInfoList)
{
if (nodeInfo != null)
{
return nodeInfo;
}
}
}
return null;
}
/**
* 根据描述查找控件
*
* @param des
* @return
*/
public static AccessibilityNodeInfo findViewByDes(String des) {
if (des == null || "".equals(des))
{
return null;
}
List<AccessibilityNodeInfo> lists = listNodeInfo;
for (AccessibilityNodeInfo node : lists)
{
CharSequence desc = node.getContentDescription();
if (desc != null && des.equals(desc.toString()))
{
return node;
}
}
return null;
}
/*
* 判断辅助功能是否启动
* */
public static boolean isStart() {
return aServer != null;
}
/**
* 模拟输入
*
* @param nodeInfo nodeInfo
* @param text text
*/
public static boolean inputTextByNode(AccessibilityNodeInfo nodeInfo, String text) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Bundle arguments = new Bundle();
arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text);
return nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
} else
{
MainActivity.setCliBoardText(text);
nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
return nodeInfo.performAction(AccessibilityNodeInfo.ACTION_PASTE);
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void recycle(AccessibilityNodeInfo info) throws JSONException {
if (info.getChildCount() == 0) {
JSONObject infoOne = new JSONObject();
infoOne.put("resource-id", info.getViewIdResourceName());
infoOne.put("class", info.getClassName());
infoOne.put("package", info.getPackageName());
infoOne.put("text", info.getText());
infoOne.put("content-desc", info.getContentDescription());
infoOne.put("checked", info.isChecked());
infoOne.put("clickable", info.isClickable());
infoOne.put("scrollable", info.isScrollable());
Matcher m = rID.matcher(info.toString());
// 用正则直接匹配得到bounds
if(m.find()){
infoOne.put("boundsInParent", m.group(1));
infoOne.put("bounds", m.group(2));
}
nodes.add(infoOne);
listNodeInfo.add(info);
} else {
for (int i = 0; i < info.getChildCount(); i++) {
if(info.getChild(i)!=null){
recycle(info.getChild(i));
}
}
}
}
}
class NodeInfo{
public static JSONArray nodes = new JSONArray();
public void changeNodes(JSONArray newNodes){
this.nodes = newNodes;
}
public JSONArray getNodes(){
return nodes;
}
} | 16,851 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
MainActivity.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/main/java/com/lookcos/hermit/MainActivity.java | package com.lookcos.hermit;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static ClipboardManager cm;
public static Context context;
private static int dwidth;
private static int dheight;
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ServerManager sm = new ServerManager(this);
sm.startServer();
context = this;
cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 申请 存储权限与无障碍权限
boolean isGrantExternalRW = Utils.isGrantExternalRW(this, 1);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(dm);
dwidth = dm.widthPixels;
dheight = dm.heightPixels;
}
/*
* 检查权限
* */
@Override
protected void onResume() {
super.onResume();
if (!AccessbilityCore.isStart()) {
Toast toast = Toast.makeText(this,"请注意检查无障碍权限", Toast.LENGTH_SHORT);
toast.show();
try {
this.startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
} catch (Exception e) {
this.startActivity(new Intent(Settings.ACTION_SETTINGS));
e.printStackTrace();
}
}
}
public static Context getContext() {
return context;
}
public static String getCliBoardText(){
ClipData data = cm.getPrimaryClip();
String content = null;
if(data != null){
ClipData.Item item = data.getItemAt(0);
content = item.getText().toString();
}
return content;
}
public static void setCliBoardText(String text){
ClipData data = ClipData.newPlainText("text", text);
cm.setPrimaryClip(data);
return ;
}
public static int getScreenHeight(){
return dheight;
}
public static int getScreenWidth(){
return dwidth;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 200) {
AccessbilityCore.result = resultCode;
AccessbilityCore.intentData = data;
}
}
} | 2,896 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
Router.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/main/java/com/lookcos/hermit/Router.java | package com.lookcos.hermit;
import android.os.Build;
import android.os.Environment;
import android.view.accessibility.AccessibilityNodeInfo;
import androidx.annotation.RequiresApi;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONException;
import com.yanzhenjie.andserver.annotation.Controller;
import com.yanzhenjie.andserver.annotation.GetMapping;
import com.yanzhenjie.andserver.annotation.PathVariable;
import com.yanzhenjie.andserver.annotation.PutMapping;
import com.yanzhenjie.andserver.annotation.RequestParam;
import com.yanzhenjie.andserver.annotation.RestController;
import com.yanzhenjie.andserver.framework.body.FileBody;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
@RestController
public class Router {
/**
* 首页测试
*/
@GetMapping("/")
String index() throws JSONException {
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", "Hermit is ok!");
return result.toString();
}
/**
* 获取当前布局
*/
@GetMapping("/data/nodes")
String infoNodes() throws JSONException {
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", "ok!");
NodeInfo ni = new NodeInfo();
result.put("count", ni.getNodes().size());
result.put("data", ni.getNodes());
return result.toJSONString();
}
/*
* 检查是否有root权限
* */
@GetMapping("/check/root")
String isRoot() throws JSONException {
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", ShellUtils.checkRootPermission());
return result.toString();
}
/*
* 查看手机端安装的所有app包名:
* */
@GetMapping("/data/packages")
String infoPackages() throws JSONException {
JSONObject result = new JSONObject();
ShellUtils.CommandResult shellResult = ShellUtils.execCommand("pm list packages", false);
if(shellResult.result==0){
result.put("code", 0);
result.put("msg", "ok");
ArrayList<String> packages = new ArrayList<String>(Arrays.asList(shellResult.successMsg.split("package:")));
ArrayList<String> list2 = new ArrayList<String>();
list2.add(packages.get(0));
packages.removeAll(list2);
result.put("count", packages.size());
result.put("data", packages);
}else {
result.put("code", -1);
result.put("msg", "error");
result.put("data", "[]");
}
return result.toString();
}
@GetMapping("/shell/start")
String shellStart(@RequestParam("packageName") String packageName) throws JSONException {
/**
* 启动某个app
* @param: packageName 也即是包名
* */
ShellUtils.checkRootPermission();
String command = "monkey -p " + packageName + " -v -v -v 1";
ShellUtils.CommandResult shellResult = ShellUtils.execCommand(command, true);
JSONObject result = new JSONObject();
if(shellResult.result==0){
result.put("code", 0);
result.put("msg", "ok");
}else {
result.put("code", -1);
result.put("msg", "请检查root权限授予情况");
}
return result.toString();
}
@GetMapping("/shell/keyevent")
String inputKeyEvent(@RequestParam("keycode") String keycode) throws JSONException {
String command = "input keyevent "+ keycode;
ShellUtils.CommandResult shellResult = ShellUtils.execCommand(command, true);
JSONObject result = new JSONObject();
if(shellResult.result==0){
result.put("code", 0);
result.put("msg", "ok");
}else {
result.put("code", -1);
result.put("msg", shellResult.errorMsg);
}
return result.toString();
}
@GetMapping("/shell/tap")
String inputTap(@RequestParam("x") String x, @RequestParam("y") String y) throws JSONException {
/*
* 点击操作
* @param:x,y坐标值
* */
String command = "input tap " + x + " " + y;
ShellUtils.CommandResult shellResult = ShellUtils.execCommand(command, true);
JSONObject result = new JSONObject();
if(shellResult.result==0){
result.put("code", 0);
result.put("msg", "ok");
}else {
result.put("code", -1);
result.put("msg", shellResult.errorMsg);
}
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.N)
@GetMapping("/click")
String newTapWay(@RequestParam("x") int x, @RequestParam("y") int y) throws JSONException {
/*
* 点击操作, 通过无障碍的方式点击,安卓版本7.0及以上可用
* @param:x,y坐标值
* */
boolean actionResult = AccessbilityCore.clickByCoordinate(x, y);
JSONObject result = new JSONObject();
if(actionResult){
result.put("code", 0);
result.put("msg", "ok");
}else {
result.put("code", -1);
result.put("msg", "error");
}
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.N)
@GetMapping("/swipe")
String swipeByCN(@RequestParam("x1") int x1,
@RequestParam("y1") int y1,
@RequestParam("x2") int x2,
@RequestParam("y2") int y2) throws JSONException {
/*
* 滑动操作
* @param:从(x1,y1)滑动到(x2, y2)
* */
boolean actionResult = AccessbilityCore.swipeByCoordinate(x1, y1, x2, y2, 20);
JSONObject result = new JSONObject();
if(actionResult){
result.put("code", 0);
result.put("msg", "ok");
}else {
result.put("code", -1);
result.put("msg", "error");
}
return result.toString();
}
@GetMapping("/shell/longtap")
String inputLongTap(@RequestParam("x") String x, @RequestParam("y") String y, @RequestParam("duration") String duration) throws JSONException {
/*
* 长按操作
* @param:x,y坐标值
* @param: duration 长按持续时间 单位ms
* */
String command = "input swipe " + x + " " + y + " " + x + " " + y + " " + duration;
ShellUtils.CommandResult shellResult = ShellUtils.execCommand(command, true);
JSONObject result = new JSONObject();
if(shellResult.result==0){
result.put("code", 0);
result.put("msg", "ok");
}else {
result.put("code", -1);
result.put("msg", shellResult.errorMsg);
}
return result.toString();
}
@GetMapping("/shell/swipe")
String inputSwipe(@RequestParam("x1") String x1,
@RequestParam("y1") String y1,
@RequestParam("x2") String x2,
@RequestParam("y2") String y2) throws JSONException {
/*
* 滑动操作
* @param:从(x1,y1)滑动到(x2, y2)
* */
String command = "input swipe "+ x1 + " " + y1 + " " + x2 + " " + y2;
ShellUtils.CommandResult shellResult = ShellUtils.execCommand(command, true);
JSONObject result = new JSONObject();
if(shellResult.result==0){
result.put("code", 0);
result.put("msg", "ok");
}else {
result.put("code", -1);
result.put("msg", shellResult.errorMsg);
}
return result.toString();
}
@GetMapping("/data/cliBoard")
String infoCliBoard() throws JSONException {
JSONObject result = new JSONObject();
String rs = MainActivity.getCliBoardText();
if(rs != null){
result.put("code", 0);
result.put("msg", "ok");
result.put("data", rs);
}else {
result.put("code", -1);
result.put("msg", "可能是剪贴板暂时没有内容");
}
return result.toString();
}
@PutMapping("/data/cliBoard")
String setCliBoard(@RequestParam("content") String content) throws JSONException{
MainActivity.setCliBoardText(content);
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg","ok");
result.put("data", content);
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@GetMapping("/click/text/{val}/_count")
String DataClickText(@PathVariable("val") String val) throws JSONException {
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", "ok");
result.put("data", AccessbilityCore.countAttrNum("text", val));
return result.toJSONString();
}
@GetMapping("/click/text/{obj}")
String clickByText(@PathVariable("obj") String textName) throws JSONException {
JSONObject result = new JSONObject();
boolean r = AccessbilityCore.clickTextViewByText(textName, 999);
if(r){
result.put("code", 0);
result.put("msg", "ok");
}
else {
result.put("code", -1);
result.put("msg", "没有找到text为:" + textName + "的可点击对象");
}
return result.toString();
}
@GetMapping("/click/text/{obj}/{index}")
String clickByText(@PathVariable("obj") String textName,
@PathVariable(value = "index", required = false, defaultValue = "999") int index) throws JSONException {
JSONObject result = new JSONObject();
boolean r = AccessbilityCore.clickTextViewByText(textName, index);
if(r){
result.put("code", 0);
result.put("msg", "ok");
}
else {
result.put("code", -1);
result.put("msg", "没有找到text为:" + textName + "的可点击对象");
}
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@GetMapping("/click/id/{app}/{id}/_count")
String DataClickId(@PathVariable("app") String app,
@PathVariable("id") String id) throws JSONException {
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", "ok");
result.put("data", AccessbilityCore.countAttrNum("id", app+"/"+id));
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@GetMapping("/click/id/{app}/{id}")
String clickById0(@PathVariable("app") String app,
@PathVariable("id") String id) throws JSONException {
JSONObject result = new JSONObject();
String viewID = app + "/" + id;
boolean r = AccessbilityCore.clickTextViewByID(viewID, 999);
if(r){
result.put("code", 0);
result.put("msg", "ok");
}
else {
result.put("code", -1);
result.put("msg", "没有找到id为:" + viewID + "的可点击对象");
}
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@GetMapping("/click/id/{app}/{id}/{index}")
String clickById(@PathVariable("app") String app,
@PathVariable("id") String id,
@PathVariable(value = "index", required = false, defaultValue = "999") int index) throws JSONException {
JSONObject result = new JSONObject();
String viewID = app + "/" + id;
boolean r = AccessbilityCore.clickTextViewByID(viewID, index);
if(r){
result.put("code", 0);
result.put("msg", "ok");
}
else {
result.put("code", -1);
result.put("msg", "没有找到id为:" + viewID + "的可点击对象");
}
return result.toString();
}
@GetMapping("/click/desc/{desc}")
String clickByDesc(@PathVariable("desc") String desc) throws JSONException {
JSONObject result = new JSONObject();
boolean r = AccessbilityCore.clickViewByDesc(desc);
if(r){
result.put("code", 0);
result.put("msg", "ok");
}
else {
result.put("code", -1);
result.put("msg", "没有找到content-desc为:" + desc + "的可点击对象");
}
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@GetMapping("/action/{obj}")
String perAction(@PathVariable("obj") String obj) throws JSONException {
JSONObject result = new JSONObject();
int action = Utils.getActionType(obj);
if (action != 0 && AccessbilityCore.getmAccessibilityService() != null){
result.put("code", 0);
result.put("msg", "ok");
AccessbilityCore.performAction(action);
} else {
result.put("code", -1);
result.put("msg", "操作失败,请检查无障碍权限是否开启,指令是否正确");
}
return result.toString();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@GetMapping("/input")
String inputById(@RequestParam("by") String by,
@RequestParam("obj") String obj,
@RequestParam("text") String text) throws JSONException {
JSONObject result = new JSONObject();
AccessibilityNodeInfo aNode = null;
if(by.equals("id")){
aNode = AccessbilityCore.findViewByID(obj);
}else if(by.equals("text")){
aNode = AccessbilityCore.findViewByText(obj);
}else if(by.equals("desc")){
aNode = AccessbilityCore.findViewByDes(obj);
}else {
result.put("code", -1);
result.put("msg", "请从id、text和desc中选一个");
return result.toJSONString();
}
AccessbilityCore.inputTextByNode(aNode, text);
result.put("code", 0);
result.put("msg", "操作成功");
return result.toString();
}
@GetMapping("/data/screen")
String screenInfo() throws JSONException {
JSONObject result = new JSONObject();
int height = MainActivity.getScreenHeight();
int width = MainActivity.getScreenWidth();
JSONObject screenInfo = new JSONObject();
screenInfo.put("height", height);
screenInfo.put("width", width);
result.put("code", 0);
result.put("msg", "ok");
result.put("data", screenInfo);
return result.toString();
}
@GetMapping("/shell/image/screen")
public FileBody imgScreenByRoot() {
// 推荐Android 7以下且具有root功能的使用此接口
ShellUtils.execCommand("screencap -p /sdcard/Pictures/hermit.png", true);
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, "hermit.png");
FileBody body = new FileBody(file);
return body;
}
@GetMapping("/image/screen")
public FileBody imgScreen(@RequestParam(value = "t", defaultValue = "3000", required = false) int t) {
// 推荐Android 7及以上的用此接口
// 发送截屏指令
System.out.println("imgScreen t : " + t);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AccessbilityCore.ScreenShotByAB();
}
if(t < 3000) {
t = 3000;
}
Thread.sleep(t);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
// 另一种方式
// AccessbilityCore.performAction(9);
// File file = Utils.getLastFile("/storage/emulated/0/Pictures/Screenshots");
File file = new File("/storage/emulated/0/Pictures", "HermitScreenShot.jpg");
FileBody body = new FileBody(file);
return body;
}
@GetMapping("/data/device")
String DeviceInfo() throws JSONException {
JSONObject result = new JSONObject();
result.put("code", 0);
result.put("msg", "ok");
JSONObject data = new JSONObject();
// 设备信息
data.put("SystemLanguage", SystemUtil.getSystemLanguage());
data.put("SystemVersion", SystemUtil.getSystemVersion());
data.put("SystemModel", SystemUtil.getSystemModel());
data.put("DeviceBrand", SystemUtil.getDeviceBrand());
// CPU 信息
data.put("CpuName", SystemUtil.getCpuName());
data.put("CurCpuFreq", new DecimalFormat("# MHz").format(Long.parseLong(SystemUtil.getCurCpuFreq())/1000));
data.put("MinCpuFreq", new DecimalFormat("# MHz").format(Long.parseLong(SystemUtil.getMinCpuFreq())/1000));
data.put("MAXCpuFreq", new DecimalFormat("# MHz").format(Long.parseLong(SystemUtil.getMaxCpuFreq())/1000));
// 内存信息
data.put("MemTotal", SystemUtil.getTotalRAM());
data.put("MemAvail", SystemUtil.getAvailableRAM());
// 存储信息
float [] StorageInfo = SystemUtil.getSDCardMemory();
data.put("StorageTotal", new DecimalFormat("#.### Gib").format(StorageInfo[0]/1024/1024/1024));
data.put("StorageAvail", new DecimalFormat("#.### Gib").format(StorageInfo[1]/1024/1024/1024));
result.put("data", data);
return result.toString();
}
}
@Controller
class PageController {
@GetMapping(path = "/viewer")
public String index() {
// Equivalent to [return "/index"].
return "forward:/index.html";
}
}
| 17,840 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
Utils.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/main/java/com/lookcos/hermit/Utils.java | package com.lookcos.hermit;
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/*
* 或许这里可以写上一句话
* */
public class Utils {
private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
public static int getActionType(String ac){
int action = 0;
if(ac.equals("back")){
action = 1; // 按下系统返回键
}else if (ac.equals("home")) {
action = 2; // 按下home键
}else if (ac.equals("recents")) {
action = 3; // 最近任务
}else if (ac.equals("noticefications")) {
action = 4; // 显示通知
}else if (ac.equals("quick_settings")) {
action = 5; // 下拉栏快速设置
}else if (ac.equals("power")) {
action = 6; // 长按电源键
}else if (ac.equals("split_screen")) {
action = 7; // 分屏
}else if (ac.equals("lock_screen")) {
action = 8; // 锁屏(安卓9.0适用)
}else if (ac.equals("screen_shot")) {
action = 9; // 截屏(安卓9.0适用)
}
return action;
}
public static void tapTest() throws IOException {
Runtime.getRuntime().exec("input tap 100 200");
}
// 申请存储相关权限
public static boolean isGrantExternalRW(Activity activity, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int storagePermission = activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
int cameraPermission = activity.checkSelfPermission(Manifest.permission.CAMERA);
//检测是否有权限,如果没有权限,就需要申请
if (storagePermission != PackageManager.PERMISSION_GRANTED ||
cameraPermission != PackageManager.PERMISSION_GRANTED) {
//申请权限
activity.requestPermissions(PERMISSIONS_CAMERA_AND_STORAGE, requestCode);
//返回false。说明没有授权
return false;
}
}
//说明已经授权
return true;
}
/**
* 获取某个目录下最新文件
*
* @param path
* @return
*/
public static File getLastFile(String path) {
List<File> list = getFiles(path, new ArrayList<>());
if (list != null && list.size() > 0) {
Collections.sort(list, (file, newFile) -> {
if (file.lastModified() < newFile.lastModified()) {
return -1;
} else if (file.lastModified() == newFile.lastModified()) {
return 0;
} else {
return 1;
}
});
}
return list.get(list.size() - 1);
}
/**
*
* 获取目录下所有文件
*
* @param realpath
* @param files
* @return
*/
public static List<File> getFiles(String realpath, List<File> files) {
File realFile = new File(realpath);
if (realFile.isDirectory()) {
File[] subfiles = realFile.listFiles();
for (File file : subfiles) {
if (file.isDirectory()) {
getFiles(file.getAbsolutePath(), files);
} else {
files.add(file);
}
}
}
return files;
}
}
class SystemUtil {
// 获取当前手机系统语言。
public static String getSystemLanguage() {
return Locale.getDefault().getLanguage();
}
// 获取当前手机系统版本号
public static String getSystemVersion() {
return android.os.Build.VERSION.RELEASE;
}
// 获取手机型号
public static String getSystemModel() {
return android.os.Build.MODEL;
}
// 获取手机厂商
public static String getDeviceBrand() {
return android.os.Build.BRAND;
}
// 获取总内存大小
public static String getTotalRAM() {
long size = 0;
Context context = MainActivity.getContext();
ActivityManager activityManager = (ActivityManager) context
.getSystemService(context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(outInfo);
size = outInfo.totalMem;
return Formatter.formatFileSize(context, size);
}
// 获取可用内存大小
public static String getAvailableRAM() {
Context context = MainActivity.getContext();
long size = 0;
ActivityManager activityManager = (ActivityManager) context
.getSystemService(context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(outInfo);
size = outInfo.availMem;
return Formatter.formatFileSize(context, size);
}
// 获取存储相关信息
public static float[] getSDCardMemory() {
float[] sdCardInfo=new float[2];
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File sdcardDir = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(sdcardDir.getPath());
float bSize = sf.getBlockSize();
float bCount = sf.getBlockCount();
float availBlocks = sf.getAvailableBlocks();
sdCardInfo[0] = bSize * bCount;//总大小
sdCardInfo[1] = bSize * availBlocks;//可用大小
}
return sdCardInfo;
}
// 获取CPU 最大频率
public static String getMaxCpuFreq() {
String result = "0";
ProcessBuilder cmd;
try {
String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[24];
while (in.read(re) != -1) {
result = result + new String(re);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
result = "0";
}
return result.trim();
}
// 获取CPU最小频率(单位KHZ)
public static String getMinCpuFreq() {
String result = "0";
ProcessBuilder cmd;
try {
String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" };
cmd = new ProcessBuilder(args);
Process process = cmd.start();
InputStream in = process.getInputStream();
byte[] re = new byte[24];
while (in.read(re) != -1) {
result = result + new String(re);
}
in.close();
} catch (IOException ex) {
ex.printStackTrace();
result = "0";
}
return result.trim();
}
// 实时获取CPU当前频率(单位KHZ)
public static String getCurCpuFreq() {
String result = "0";
try {
FileReader fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
result = text.trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// 获取CPU名字
public static String getCpuName() {
try {
FileReader fr = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
String[] array = text.split(":\\s+", 2);
for (int i = 0; i < array.length; i++) {
}
return array[1];
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| 8,806 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
ServerManager.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/main/java/com/lookcos/hermit/ServerManager.java | package com.lookcos.hermit;
import android.content.Context;
import android.util.Log;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;
import java.util.concurrent.TimeUnit;
public class ServerManager {
private static final String TAG = "ServerManager";
private Server mServer;
/**
* Create server.
*/
public ServerManager(Context context) {
mServer = AndServer.webServer(context)
.port(9999)
.timeout(10, TimeUnit.SECONDS)
.listener(new Server.ServerListener() {
@Override
public void onStarted() {
// TODO The server started successfully.
Log.d(TAG, "onStarted: ");
}
@Override
public void onStopped() {
// TODO The server has stopped.
Log.d(TAG, "onStarted: ");
}
@Override
public void onException(Exception e) {
Log.e(TAG, "onException: ",e );
// TODO An exception occurred while the server was starting.
}
})
.build();
}
/**
* Start server.
*/
public void startServer() {
if (mServer.isRunning()) {
// TODO The server is already up.
} else {
mServer.startup();
}
}
/**
* Stop server.
*/
public void stopServer() {
if (mServer.isRunning()) {
mServer.shutdown();
} else {
Log.w("AndServer", "The server has not started yet.");
}
}
}
| 1,760 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
ExampleInstrumentedTest.java | /FileExtraction/Java_unseen/austin2035_hermit/app/src/androidTest/java/com/lookcos/hermit/ExampleInstrumentedTest.java | package com.lookcos.hermit;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.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.getInstrumentation().getTargetContext();
assertEquals("com.lookcos.hermit", appContext.getPackageName());
}
} | 750 | Java | .java | austin2035/hermit | 317 | 62 | 4 | 2021-01-26T06:15:39Z | 2022-09-01T09:04:20Z |
SettingUtil.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/main/java/com/ghostflying/image2camera/SettingUtil.java | package com.ghostflying.image2camera;
/**
* Created by ghostflying on 15-8-25.
*/
public abstract class SettingUtil {
public static String SETTING_NAME = "Settings";
public static String DEFAULT_CAMERA_APP = "DefaultCameraApp";
public static String DEFAULT_CAMERA_APP_ACTIVITY = "DefaultCameraAppActivity";
public static String DEFAULT_CAMERA_APP_NAME = "DefaultCameraAppName";
}
| 399 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
BaseAlertDialogFragment.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/main/java/com/ghostflying/image2camera/BaseAlertDialogFragment.java | package com.ghostflying.image2camera;
import android.app.Activity;
import android.app.DialogFragment;
/**
* Created by ghostflying on 15-8-24.
*/
public abstract class BaseAlertDialogFragment extends DialogFragment {
protected OnFragmentInteractionListener mListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
public void onPositiveButtonClick(int value, int title);
public void onNegativeButtonClick(int value, int title);
}
}
| 1,405 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
SingleChooseDialogFragment.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/main/java/com/ghostflying/image2camera/SingleChooseDialogFragment.java | package com.ghostflying.image2camera;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ghostflying on 15-8-24.
*/
public class SingleChooseDialogFragment extends BaseAlertDialogFragment {
// the fragment initialization parameters
private static final String ARG_TITLE = "title";
private static final String ARG_ITEMS = "items";
private static final String ARG_ITEM_CHECKED = "checked";
private int mTitle;
private List<String> mItems;
private int mChecked;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param title the resoucce id of the title of the dialog.
* @param items the resource id of items to choose.
* @return A new instance of fragment SingleChooseDialogFragment.
*/
public static SingleChooseDialogFragment newInstance(int title, ArrayList<String> items, int checked) {
SingleChooseDialogFragment fragment = new SingleChooseDialogFragment();
Bundle args = new Bundle();
args.putInt(ARG_TITLE, title);
args.putStringArrayList(ARG_ITEMS, items);
args.putInt(ARG_ITEM_CHECKED, checked);
fragment.setArguments(args);
return fragment;
}
public SingleChooseDialogFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getInt(ARG_TITLE);
mItems = getArguments().getStringArrayList(ARG_ITEMS);
mChecked = getArguments().getInt(ARG_ITEM_CHECKED);
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
return new AlertDialog.Builder(getActivity())
.setTitle(mTitle)
.setSingleChoiceItems(mItems.toArray(new String[mItems.size()]), mChecked, onClickListener)
.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mListener.onPositiveButtonClick(mChecked, mTitle);
}
})
.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
}
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mChecked = which;
}
};
}
| 2,943 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
ImageReadDialogFragment.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/main/java/com/ghostflying/image2camera/ImageReadDialogFragment.java | package com.ghostflying.image2camera;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
public class ImageReadDialogFragment extends LoadingDialogFragment {
public static ImageReadDialogFragment newInstance() {
return new ImageReadDialogFragment();
}
public ImageReadDialogFragment() {
// Required empty public constructor
}
@Override
protected View getCustomView() {
return getActivity().getLayoutInflater().inflate(R.layout.fragment_image_read_dialog, null);
}
}
| 621 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
LoadingDialogFragment.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/main/java/com/ghostflying/image2camera/LoadingDialogFragment.java | package com.ghostflying.image2camera;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
/**
* Created by ghostflying on 15-8-25.
*/
public abstract class LoadingDialogFragment extends DialogFragment{
public LoadingDialogFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
View view = getCustomView();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setView(view);
Dialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
protected abstract View getCustomView();
}
| 898 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
MainActivity.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/main/java/com/ghostflying/image2camera/MainActivity.java | package com.ghostflying.image2camera;
import android.Manifest;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE = 10;
private static final String IMAGE_TYPE = "image/*";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL = 100;
private Uri outputUri;
private List<AppInfo> cameraApps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent cameraIntent = getIntent();
if (cameraIntent.getAction().equals(MediaStore.ACTION_IMAGE_CAPTURE)) {
startPickImages(cameraIntent);
}
}
private void startPickImages(Intent cameraIntent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ClipData clipData = cameraIntent.getClipData();
if (clipData != null) {
outputUri = clipData.getItemAt(0).getUri();
}
}
// compatibility for system below lollipop
if (outputUri == null) {
Bundle extra = cameraIntent.getExtras();
if (extra != null) {
outputUri = extra.getParcelable(MediaStore.EXTRA_OUTPUT);
}
}
if (outputUri == null) {
Toast.makeText(this, R.string.not_support_message, Toast.LENGTH_LONG).show();
return;
}
if (requestPermissionIfNeeded()) {
pickImages();
}
}
private boolean requestPermissionIfNeeded() {
if ("content".equals(outputUri.getScheme())) {
return true;
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage(R.string.permission_write_external_message)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(
MainActivity.this,
new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSION_WRITE_EXTERNAL
);
}
});
builder.create().show();
}
else {
ActivityCompat.requestPermissions(
this,
new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSION_WRITE_EXTERNAL
);
}
}
else {
return true;
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_WRITE_EXTERNAL:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
pickImages();
}
break;
}
}
private void pickImages() {
Intent intent = new Intent();
intent.setType(IMAGE_TYPE);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)), PICK_IMAGE);
}
private void saveFile(Uri source, Uri des) {
try {
final InputStream inputStream = getContentResolver().openInputStream(source);
final OutputStream outputStream = getContentResolver().openOutputStream(des);
try {
try {
final byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, read);
outputStream.flush();
// copy images successfully.
setResult(Activity.RESULT_OK);
} finally {
inputStream.close();
outputStream.close();
}
} catch (IOException e) {
handleException(e);
}
} catch (IOException e) {
handleException(e);
}
}
private void handleException(Exception e) {
e.printStackTrace();
setResult(Activity.RESULT_CANCELED);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, R.string.io_exception_toast, Toast.LENGTH_SHORT).show();
}
});
}
private void handleNotSelect() {
Toast.makeText(this, R.string.not_select_toast, Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (data == null || resultCode == Activity.RESULT_CANCELED) {
handleNotSelect();
setResult(RESULT_CANCELED);
return;
}
if (resultCode == Activity.RESULT_OK) {
new SaveFileTask().execute(data.getData(), outputUri);
setResult(RESULT_OK);
}
}
}
private class SaveFileTask extends AsyncTask<Uri, Void, Void> {
DialogFragment dialogFragment;
@Override
protected void onPreExecute() {
dialogFragment = ImageReadDialogFragment.newInstance();
dialogFragment.show(getFragmentManager(), null);
}
@Override
protected Void doInBackground(Uri... params) {
saveFile(params[0], params[1]);
return null;
}
@Override
protected void onPostExecute(Void result) {
dialogFragment.dismiss();
finish();
}
}
private class LoadAppTask extends AsyncTask<Void, Void, Void> {
private DialogFragment dialogFragment;
private ArrayList<String> appNames;
private int checked;
@Override
protected void onPreExecute() {
dialogFragment = AppLoadingDialogFragment.newInstance();
dialogFragment.show(getFragmentManager(), null);
}
@Override
protected Void doInBackground(Void... params) {
final Intent mainIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = MainActivity.this.getPackageManager();
final List<ResolveInfo> pkgAppsList = packageManager.queryIntentActivities(mainIntent, 0);
SharedPreferences preferences = getSharedPreferences(SettingUtil.SETTING_NAME, MODE_PRIVATE);
String defaultApp = preferences.getString(SettingUtil.DEFAULT_CAMERA_APP_ACTIVITY, null);
cameraApps = new ArrayList<>(pkgAppsList.size());
appNames = new ArrayList<>(pkgAppsList.size());
for (ResolveInfo each : pkgAppsList) {
if (!each.activityInfo.packageName.equals(BuildConfig.APPLICATION_ID)) {
AppInfo info = new AppInfo();
info.appName = each.loadLabel(packageManager).toString();
info.activityName = each.activityInfo.name;
info.packageName = each.activityInfo.packageName;
cameraApps.add(info);
appNames.add(info.appName);
if (defaultApp != null && info.activityName.equals(defaultApp)) {
checked = cameraApps.size() - 1;
}
}
}
return null;
}
protected void onPostExecute(Void result) {
dialogFragment.dismiss();
DialogFragment chooseDialog = SingleChooseDialogFragment
.newInstance(R.string.dialog_title_app_choose, appNames, checked);
chooseDialog.show(getFragmentManager(), null);
}
}
private static class AppInfo {
String packageName;
String activityName;
String appName;
}
}
| 9,540 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
AppLoadingDialogFragment.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/main/java/com/ghostflying/image2camera/AppLoadingDialogFragment.java | package com.ghostflying.image2camera;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
public class AppLoadingDialogFragment extends LoadingDialogFragment {
public static AppLoadingDialogFragment newInstance() {
return new AppLoadingDialogFragment();
}
public AppLoadingDialogFragment() {
// Required empty public constructor
}
@Override
protected View getCustomView() {
return getActivity().getLayoutInflater().inflate(R.layout.fragment_load_app_dialog, null);
}
}
| 623 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
ApplicationTest.java | /FileExtraction/Java_unseen/GhostFlying_image-to-camera/app/src/androidTest/java/com/ghostflying/image2camera/ApplicationTest.java | package com.ghostflying.image2camera;
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);
}
} | 359 | Java | .java | GhostFlying/image-to-camera | 82 | 29 | 5 | 2015-05-19T15:52:47Z | 2022-07-03T22:09:00Z |
Kuvel.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/Kuvel.java | package net.azisaba.kuvel;
import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.io.File;
import java.nio.file.Path;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import net.azisaba.kuvel.config.KuvelConfig;
import net.azisaba.kuvel.discovery.impl.redis.RedisLoadBalancerDiscovery;
import net.azisaba.kuvel.discovery.impl.redis.RedisServerDiscovery;
import net.azisaba.kuvel.listener.ChooseInitialServerListener;
import net.azisaba.kuvel.listener.LoadBalancerListener;
import net.azisaba.kuvel.redis.ProxyIdProvider;
import net.azisaba.kuvel.redis.RedisConnectionLeader;
import net.azisaba.kuvel.redis.RedisSubscriberExecutor;
import org.slf4j.Logger;
@Plugin(
id = "kuvel",
name = "Kuvel",
version = "2.1.0",
url = "https://github.com/AzisabaNetwork/Kuvel",
description =
"Server-discovery Velocity plugin for Minecraft servers running in a Kubernetes cluster.",
authors = {"Azisaba Network"})
@Getter
public class Kuvel {
private final ProxyServer proxy;
private final Logger logger;
private final File dataDirectory;
private KubernetesClient client;
private KuvelServiceHandler kuvelServiceHandler;
private RedisConnectionLeader redisConnectionLeader;
private ProxyIdProvider proxyIdProvider;
private RedisSubscriberExecutor redisSubscriberExecutor;
private KuvelConfig kuvelConfig;
@Inject
public Kuvel(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) {
this.proxy = server;
this.logger = logger;
this.dataDirectory = dataDirectory.toFile();
}
@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
client = new DefaultKubernetesClient();
kuvelConfig = new KuvelConfig(this);
try {
kuvelConfig.load();
} catch (Exception e) {
logger.error("Failed to load config file. Plugin feature will be disabled.", e);
return;
}
kuvelServiceHandler = new KuvelServiceHandler(this, client, kuvelConfig.getNamespace());
Objects.requireNonNull(kuvelConfig.getRedisConnectionData());
Objects.requireNonNull(kuvelConfig.getProxyGroupName());
proxyIdProvider =
new ProxyIdProvider(
kuvelConfig.getRedisConnectionData().createJedisPool(),
kuvelConfig.getProxyGroupName());
proxyIdProvider.runTask(proxy, this);
logger.info("This proxy's id is: " + proxyIdProvider.getId());
redisConnectionLeader =
new RedisConnectionLeader(
this,
kuvelConfig.getRedisConnectionData().createJedisPool(),
kuvelConfig.getProxyGroupName(),
proxyIdProvider.getId());
redisConnectionLeader.trySwitch();
kuvelServiceHandler.setAndRunLoadBalancerDiscovery(
new RedisLoadBalancerDiscovery(
client,
this,
kuvelConfig.getNamespace(),
kuvelConfig.getRedisConnectionData().createJedisPool(),
kuvelConfig.getProxyGroupName(),
redisConnectionLeader,
kuvelServiceHandler));
kuvelServiceHandler.setAndRunServerDiscovery(
new RedisServerDiscovery(
client,
this,
kuvelConfig.getNamespace(),
kuvelConfig.getRedisConnectionData().createJedisPool(),
kuvelConfig.getProxyGroupName(),
redisConnectionLeader,
kuvelServiceHandler));
proxy
.getScheduler()
.buildTask(
this,
() -> {
if (redisConnectionLeader.isLeader()) {
redisConnectionLeader.extendLeaderExpire();
} else {
redisConnectionLeader.trySwitch();
}
})
.repeat(5, TimeUnit.SECONDS)
.schedule();
redisSubscriberExecutor =
new RedisSubscriberExecutor(
kuvelConfig.getRedisConnectionData().createJedisPool(),
kuvelConfig.getProxyGroupName());
redisSubscriberExecutor.subscribe(this, kuvelServiceHandler, redisConnectionLeader);
proxy.getEventManager().register(this, new LoadBalancerListener(kuvelServiceHandler));
proxy
.getEventManager()
.register(this, new ChooseInitialServerListener(proxy, kuvelServiceHandler));
}
@Subscribe
public void onProxyShutdown(ProxyShutdownEvent event) {
if (kuvelServiceHandler != null) {
kuvelServiceHandler.shutdown();
}
if (redisConnectionLeader != null) {
redisConnectionLeader.leaveLeader();
}
if (proxyIdProvider != null) {
proxyIdProvider.deleteProxyId();
}
}
}
| 5,029 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
KuvelServiceHandler.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/KuvelServiceHandler.java | package net.azisaba.kuvel;
import com.velocitypowered.api.proxy.server.ServerInfo;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.discovery.LoadBalancerDiscovery;
import net.azisaba.kuvel.discovery.ServerDiscovery;
import net.azisaba.kuvel.loadbalancer.LoadBalancer;
import net.azisaba.kuvel.util.LabelKeys;
import net.azisaba.kuvel.util.UidAndServerNameMap;
@Getter
@RequiredArgsConstructor
public class KuvelServiceHandler {
private final Kuvel plugin;
private final KubernetesClient client;
private final String namespace;
private final HashMap<String, LoadBalancer> loadBalancerServerMap = new HashMap<>();
private final UidAndServerNameMap podUidAndServerNameMap = new UidAndServerNameMap();
private final UidAndServerNameMap replicaSetUidAndServerNameMap = new UidAndServerNameMap();
private final List<String> initialServerNames = new ArrayList<>();
private final AtomicReference<ServerDiscovery> serverDiscovery = new AtomicReference<>();
private final AtomicReference<LoadBalancerDiscovery> loadBalancerDiscovery =
new AtomicReference<>();
/**
* Registers a load balancer server to the map.
*
* @param loadBalancer The load balancer to register.
*/
public void registerLoadBalancer(LoadBalancer loadBalancer) {
String serverName = loadBalancer.getServer().getServerInfo().getName();
loadBalancerServerMap.put(serverName, loadBalancer);
replicaSetUidAndServerNameMap.register(loadBalancer.getReplicaSetUid(), serverName);
updateLoadBalancerEndpoints(loadBalancer);
if (loadBalancer.isInitialServer() && !initialServerNames.contains(serverName)) {
initialServerNames.add(serverName);
}
plugin
.getLogger()
.info(
"Registered load balancer: "
+ serverName
+ " ("
+ loadBalancer.getReplicaSetUid()
+ ")");
}
/**
* Unregisters a load balancer server from the map.
*
* @param replicaSetUid The ReplicaSet UID of the load balancer to unregister.
*/
public void unregisterLoadBalancer(String replicaSetUid) {
String serverName = replicaSetUidAndServerNameMap.getServerNameFromUid(replicaSetUid);
if (serverName == null) {
return;
}
LoadBalancer loadBalancer = loadBalancerServerMap.get(serverName);
if (loadBalancer != null) {
unregisterLoadBalancer(loadBalancer);
}
}
/**
* Unregisters a load balancer server from the Velocity server.
*
* @param loadBalancer The load balancer to unregister.
*/
public void unregisterLoadBalancer(LoadBalancer loadBalancer) {
String serverName = loadBalancer.getServer().getServerInfo().getName();
plugin
.getProxy()
.getServer(serverName)
.ifPresent(server -> plugin.getProxy().unregisterServer(server.getServerInfo()));
loadBalancerServerMap.remove(serverName);
replicaSetUidAndServerNameMap.unregister(loadBalancer.getReplicaSetUid());
initialServerNames.remove(serverName);
plugin
.getLogger()
.info(
"Unregistered load balancer: "
+ serverName
+ " ("
+ loadBalancer.getReplicaSetUid()
+ ")");
}
/**
* Get a registered load balancer instance.
*
* @param serverName The name of the load balancer server.
* @return The load balancer instance.
*/
public Optional<LoadBalancer> getLoadBalancer(String serverName) {
return Optional.ofNullable(loadBalancerServerMap.get(serverName));
}
/**
* Update endpoints of a load balancer.
*
* @param loadBalancer The load balancer to update.
*/
private void updateLoadBalancerEndpoints(LoadBalancer loadBalancer) {
// TODO: This may be replaced by more improved function
List<Pod> pods =
client
.pods()
.inNamespace(namespace)
.withLabel(LabelKeys.ENABLE_SERVER_DISCOVERY.getKey(), "true")
.list()
.getItems();
List<String> endpoints = new ArrayList<>();
for (Pod pod : pods) {
if (pod.hasOwnerReferenceFor(loadBalancer.getReplicaSetUid())) {
String serverName = podUidAndServerNameMap.getServerNameFromUid(pod.getMetadata().getUid());
if (serverName != null) {
endpoints.add(serverName);
}
}
}
loadBalancer.setEndpoints(endpoints);
}
/**
* Replace new server discovery instance and unregister old one. Specify null for shutdown current
* discovery instance.
*
* @param newServerDiscovery The new server discovery instance. Specify null for shutdown current
* one.
*/
public void setAndRunServerDiscovery(@Nullable ServerDiscovery newServerDiscovery) {
if (newServerDiscovery != null) {
HashMap<String, Pod> servers = newServerDiscovery.getServersForStartup();
for (Entry<String, Pod> entry : servers.entrySet()) {
Pod pod = entry.getValue();
InetSocketAddress address = new InetSocketAddress(pod.getStatus().getPodIP(), 25565);
plugin.getProxy().getServer(entry.getKey()).ifPresent(server -> plugin.getProxy().unregisterServer(server.getServerInfo()));
plugin.getProxy().registerServer(new ServerInfo(entry.getKey(), address));
String initialServerStr = pod.getMetadata().getLabels()
.getOrDefault(LabelKeys.INITIAL_SERVER.getKey(), "false");
if (Boolean.parseBoolean(initialServerStr)) {
initialServerNames.add(entry.getKey());
}
for (LoadBalancer loadBalancer : loadBalancerServerMap.values()) {
if (pod.hasOwnerReferenceFor(loadBalancer.getReplicaSetUid())) {
loadBalancer.addEndpoint(entry.getKey());
}
}
}
newServerDiscovery.start();
}
serverDiscovery.getAndUpdate(
(oldInstance) -> {
if (oldInstance != null) {
oldInstance.shutdown();
}
return newServerDiscovery;
});
}
/**
* Replace new load balancer discovery instance and unregister old one. Specify null for shutdown
* current discovery instance.
*
* @param newInstance The new load balancer discovery instance. Specify null for shutdown current
* one.
*/
public void setAndRunLoadBalancerDiscovery(@Nullable LoadBalancerDiscovery newInstance) {
if (newInstance != null) {
newInstance.registerLoadBalancersForStartup();
newInstance.start();
}
loadBalancerDiscovery.getAndUpdate(
oldInstance -> {
if (oldInstance != null) {
oldInstance.shutdown();
}
return newInstance;
});
}
/** Shutdown all discovery instances. */
public void shutdown() {
setAndRunServerDiscovery(null);
setAndRunLoadBalancerDiscovery(null);
}
/**
* Register a pod for the specified server name.
*
* @param pod The pod to register.
* @param serverName The name of the server.
*/
public void registerPod(Pod pod, String serverName) {
InetSocketAddress address = new InetSocketAddress(pod.getStatus().getPodIP(), 25565);
plugin.getProxy().registerServer(new ServerInfo(serverName, address));
podUidAndServerNameMap.register(pod.getMetadata().getUid(), serverName);
for (LoadBalancer loadBalancer : loadBalancerServerMap.values()) {
if (pod.hasOwnerReferenceFor(loadBalancer.getReplicaSetUid())) {
loadBalancer.addEndpoint(serverName);
}
}
String initialServerStr =
pod.getMetadata().getLabels().getOrDefault(LabelKeys.INITIAL_SERVER.getKey(), "false");
if (Boolean.parseBoolean(initialServerStr)) {
initialServerNames.add(serverName);
}
plugin
.getLogger()
.info("Registered server: " + serverName + " (" + pod.getMetadata().getUid() + ")");
}
/**
* Unregister a pod with pod uid from the specified server name.
*
* @param podUid The pod uid to register.
* @param serverName The name of the server.
*/
public void registerPod(String podUid, String serverName) {
Optional<Pod> pod =
client
.pods()
.inNamespace(namespace)
.withLabel(LabelKeys.ENABLE_SERVER_DISCOVERY.getKey(), "true")
.list()
.getItems()
.stream()
.filter(p -> p.getMetadata().getUid().equals(podUid))
.findFirst();
pod.ifPresent(p -> registerPod(p, serverName));
}
/**
* Unregister a pod with the pod uid.
*
* @param podUid The pod uid to unregister.
*/
public void unregisterPod(String podUid) {
if (podUidAndServerNameMap.getServerNameFromUid(podUid) == null) {
return;
}
String serverName = podUidAndServerNameMap.unregister(podUid);
plugin
.getProxy()
.getServer(serverName)
.ifPresent(server -> plugin.getProxy().unregisterServer(server.getServerInfo()));
for (LoadBalancer loadBalancer : loadBalancerServerMap.values()) {
if (loadBalancer.getEndpointServers().contains(serverName)) {
loadBalancer.removeEndpoint(serverName);
}
}
initialServerNames.remove(serverName);
plugin.getLogger().info("Unregistered server: " + serverName + " (" + podUid + ")");
}
/**
* Unregister a pod.
*
* @param pod The pod to unregister.
*/
public void unregisterPod(Pod pod) {
unregisterPod(pod.getMetadata().getUid());
}
/**
* Gets whether the specified server name is registered.
*
* @param podId The pod id to check.
* @return true if the specified server name is registered.
*/
public boolean isPodRegistered(String podId) {
return podUidAndServerNameMap.getServerNameFromUid(podId) != null;
}
}
| 10,105 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
LoadBalancerListener.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/listener/LoadBalancerListener.java | package net.azisaba.kuvel.listener;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.player.PlayerChooseInitialServerEvent;
import com.velocitypowered.api.event.player.ServerPreConnectEvent;
import com.velocitypowered.api.event.player.ServerPreConnectEvent.ServerResult;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.KuvelServiceHandler;
@RequiredArgsConstructor
public class LoadBalancerListener {
private final KuvelServiceHandler handler;
@Subscribe(order = PostOrder.LATE)
public void onInitialServerChoose(PlayerChooseInitialServerEvent event) {
event
.getInitialServer()
.ifPresent(
server -> {
String serverName = server.getServerInfo().getName();
handler
.getLoadBalancer(serverName)
.ifPresent(
lb -> {
RegisteredServer target = lb.getTarget();
if (target != null) {
event.setInitialServer(target);
}
});
});
}
@Subscribe(order = PostOrder.LATE)
public void onServerChanged(ServerPreConnectEvent event) {
event
.getResult()
.getServer()
.ifPresent(
server -> {
String serverName = server.getServerInfo().getName();
handler
.getLoadBalancer(serverName)
.ifPresent(
lb -> {
RegisteredServer target = lb.getTarget();
if (target != null) {
event.setResult(ServerResult.allowed(target));
} else {
event.setResult(ServerResult.denied());
}
});
});
}
}
| 1,996 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
ChooseInitialServerListener.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/listener/ChooseInitialServerListener.java | package net.azisaba.kuvel.listener;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.player.PlayerChooseInitialServerEvent;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.KuvelServiceHandler;
@RequiredArgsConstructor
public class ChooseInitialServerListener {
private final ProxyServer proxy;
private final KuvelServiceHandler handler;
@Subscribe
public void onInitialServerChoose(PlayerChooseInitialServerEvent event) {
if (handler.getInitialServerNames().isEmpty()) {
return;
}
List<String> initialServerNames = new ArrayList<>(handler.getInitialServerNames());
Collections.shuffle(initialServerNames);
RegisteredServer server = null;
for (String initialServerName : initialServerNames) {
Optional<RegisteredServer> optionalServer = proxy.getServer(initialServerName);
if (optionalServer.isPresent()) {
server = optionalServer.get();
break;
}
}
if (server == null) {
return;
}
event.setInitialServer(server);
}
}
| 1,292 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
KuvelConfig.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/config/KuvelConfig.java | package net.azisaba.kuvel.config;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.Kuvel;
import net.azisaba.kuvel.util.RedisConnectionData;
@Getter
@RequiredArgsConstructor
public class KuvelConfig {
private final Kuvel plugin;
private static final String CONFIG_FILE_NAME = "config.yml";
@Nullable private String namespace;
private boolean redisEnabled;
@Nullable private RedisConnectionData redisConnectionData;
@Nullable private String proxyGroupName;
public void load() throws IOException {
File uppercaseDataFolder = new File(plugin.getDataDirectory().getParentFile(), "Kuvel");
if (uppercaseDataFolder.exists() && !plugin.getDataDirectory().exists()) {
if (uppercaseDataFolder.renameTo(plugin.getDataDirectory())) {
plugin
.getLogger()
.info(
"Successfully renamed the data folder to use a lowercase name.");
} else {
plugin
.getLogger()
.warn(
"Failed to rename the data folder to be lowercase. Please manually rename the data folder to 'kuvel'.");
}
}
VelocityConfigLoader conf = VelocityConfigLoader.load(new File(plugin.getDataDirectory(), CONFIG_FILE_NAME));
conf.saveDefaultConfig();
Map<String, String> env = System.getenv();
namespace = env.getOrDefault("KUVEL_NAMESPACE", conf.getString("namespace", null));
String hostname = env.getOrDefault("KUVEL_REDIS_CONNECTION_HOSTNAME", conf.getString("redis.connection.hostname"));
int port = conf.getInt("redis.connection.port", -1);
if (env.containsKey("KUVEL_REDIS_CONNECTION_PORT")) {
try {
port = Integer.parseInt(env.get("KUVEL_REDIS_CONNECTION_PORT"));
} catch (NumberFormatException e) {
plugin
.getLogger()
.warn(
"Invalid port number for Redis connection specified in KUVEL_REDIS_CONNECTION_PORT environment variable. Using port " + port + " from config.yml.");
}
}
String username = env.getOrDefault("KUVEL_REDIS_CONNECTION_USERNAME", conf.getString("redis.connection.username"));
String password = env.getOrDefault("KUVEL_REDIS_CONNECTION_PASSWORD", conf.getString("redis.connection.password"));
if (hostname == null || port <= 0) {
redisEnabled = false;
plugin
.getLogger()
.warn(
"Redis is enabled, but hostname or port is invalid. Redis sync will be disabled.");
} else {
redisConnectionData = new RedisConnectionData(hostname, port, username, password);
}
proxyGroupName = env.getOrDefault("KUVEL_REDIS_GROUPNAME", conf.getString("redis.group-name", null));
}
}
| 2,811 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
VelocityConfigLoader.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/config/VelocityConfigLoader.java | package net.azisaba.kuvel.config;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.yaml.snakeyaml.Yaml;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class VelocityConfigLoader {
private final File file;
private final HashMap<String, Object> dataMap = new HashMap<>();
public static VelocityConfigLoader load(File file) {
return new VelocityConfigLoader(file).load();
}
public String getString(@Nonnull String key, String defaultValue) {
String lowerKey = key.toLowerCase(Locale.ROOT);
if (dataMap.containsKey(lowerKey)) {
return dataMap.get(lowerKey).toString();
} else {
return defaultValue;
}
}
public int getInt(@Nonnull String key, int defaultValue) {
String lowerKey = key.toLowerCase(Locale.ROOT);
if (dataMap.containsKey(lowerKey)) {
return Integer.parseInt(dataMap.get(lowerKey).toString());
} else {
return defaultValue;
}
}
public long getLong(@Nonnull String key, long defaultValue) {
String lowerKey = key.toLowerCase(Locale.ROOT);
if (dataMap.containsKey(lowerKey)) {
return Long.parseLong(dataMap.get(lowerKey).toString());
} else {
return defaultValue;
}
}
public boolean getBoolean(@Nonnull String key, boolean defaultValue) {
String lowerKey = key.toLowerCase(Locale.ROOT);
if (dataMap.containsKey(lowerKey)) {
return Boolean.parseBoolean(dataMap.get(lowerKey).toString());
} else {
return defaultValue;
}
}
public double getDouble(@Nonnull String key, double defaultValue) {
String lowerKey = key.toLowerCase(Locale.ROOT);
if (dataMap.containsKey(lowerKey)) {
return Double.parseDouble(dataMap.get(lowerKey).toString());
} else {
return defaultValue;
}
}
public @Nullable Object get(@Nonnull String key, Object defaultValue) {
String lowerKey = key.toLowerCase(Locale.ROOT);
return dataMap.getOrDefault(lowerKey, defaultValue);
}
public String getString(@Nonnull String key) {
return getString(key, null);
}
public int getInt(@Nonnull String key) {
return getInt(key, 0);
}
public long getLong(@Nonnull String key) {
return getLong(key, 0);
}
public boolean getBoolean(@Nonnull String key) {
return getBoolean(key, false);
}
public double getDouble(@Nonnull String key) {
return getDouble(key, 0);
}
public @Nullable Object get(@Nonnull String key) {
return get(key, null);
}
private VelocityConfigLoader load() {
Objects.requireNonNull(file);
String fileName = file.getName().toLowerCase(Locale.ROOT);
if (!fileName.endsWith(".yml") && !fileName.endsWith(".yaml")) {
throw new IllegalArgumentException("File must be a YAML file.");
}
Yaml yaml = new Yaml();
Map<String, Object> data;
try {
if (file.exists()) {
data = yaml.load(new FileReader(file));
} else {
data = new HashMap<>();
}
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("File not found.", e);
}
storeDataFor(null, data);
return this;
}
public void saveDefaultConfig() throws IOException {
if (file.exists()) {
return;
}
InputStream is = getClass().getClassLoader().getResourceAsStream(file.getName());
if (is == null) {
throw new IllegalStateException("Failed to load config.yml from resource.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
Files.createDirectories(file.getParentFile().toPath());
byte[] byteStr =
reader
.lines()
.collect(Collectors.joining(System.lineSeparator()))
.getBytes(StandardCharsets.UTF_8);
Files.write(file.toPath(), byteStr);
load();
}
private void storeDataFor(@Nullable String parentKey, Map<String, Object> map) {
for (String key : map.keySet()) {
String newKey = parentKey == null ? key : parentKey + "." + key;
newKey = newKey.toLowerCase(Locale.ROOT);
if (canDig(map, key)) {
storeDataFor(newKey, dig(map, key));
} else {
dataMap.put(newKey, map.get(key));
}
}
}
private boolean canDig(Map<String, Object> map, String key) {
return map.get(key) instanceof Map;
}
@SuppressWarnings("unchecked")
private Map<String, Object> dig(Map<String, Object> data, String key) {
Object o = data.get(key);
if (!(o instanceof Map)) {
throw new IllegalArgumentException("Cannot dig.");
}
return (Map<String, Object>) o;
}
}
| 5,075 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
KubernetesKindUpdateWatcher.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/discovery/KubernetesKindUpdateWatcher.java | package net.azisaba.kuvel.discovery;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class KubernetesKindUpdateWatcher<T> implements Watcher<T> {
private final List<Consumer<T>> updateConsumerList = new ArrayList<>();
@Override
public void eventReceived(Action action, T item) {
updateConsumerList.forEach(
consumer -> {
try {
consumer.accept(item);
} catch (Exception ex) {
ex.printStackTrace();
}
});
}
@Override
public void onClose(WatcherException e) {
e.printStackTrace();
}
public void registerPodUpdateConsumer(Consumer<T> consumer) {
updateConsumerList.add(consumer);
}
}
| 883 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
ServerDiscovery.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/discovery/ServerDiscovery.java | package net.azisaba.kuvel.discovery;
import io.fabric8.kubernetes.api.model.Pod;
import java.net.InetSocketAddress;
import java.util.HashMap;
public interface ServerDiscovery {
void start();
void shutdown();
HashMap<String, Pod> getServersForStartup();
}
| 266 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
LoadBalancerDiscovery.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/discovery/LoadBalancerDiscovery.java | package net.azisaba.kuvel.discovery;
public interface LoadBalancerDiscovery {
void start();
void shutdown();
void registerLoadBalancersForStartup();
}
| 161 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RedisServerDiscovery.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/discovery/impl/redis/RedisServerDiscovery.java | package net.azisaba.kuvel.discovery.impl.redis;
import com.velocitypowered.api.scheduler.ScheduledTask;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.Kuvel;
import net.azisaba.kuvel.KuvelServiceHandler;
import net.azisaba.kuvel.discovery.ServerDiscovery;
import net.azisaba.kuvel.discovery.diffchecker.PodDiffChecker;
import net.azisaba.kuvel.redis.RedisConnectionLeader;
import net.azisaba.kuvel.redis.RedisKeys;
import net.azisaba.kuvel.util.LabelKeys;
import org.apache.commons.lang3.time.DateFormatUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@RequiredArgsConstructor
public class RedisServerDiscovery implements ServerDiscovery {
private final KubernetesClient client;
private final Kuvel plugin;
private final String namespace;
private final JedisPool jedisPool;
private final String groupName;
private final RedisConnectionLeader redisConnectionLeader;
private final KuvelServiceHandler kuvelServiceHandler;
private final AtomicReference<ScheduledTask> taskReference = new AtomicReference<>();
private final PodDiffChecker podDiffChecker = new PodDiffChecker().init();
private final ReentrantLock lock = new ReentrantLock();
@Override
public void start() {
if (!redisConnectionLeader.isLeader()) {
return;
}
Runnable runnable =
() -> {
List<Pod> podList =
client
.pods()
.inNamespace(namespace)
.withLabel(LabelKeys.ENABLE_SERVER_DISCOVERY.getKey(), "true")
.list()
.getItems();
for (Pod pod : podList) {
if (podDiffChecker.diff(pod)) {
processUpdatedPod(pod);
}
}
List<String> uidList = podDiffChecker.getDeletedPodUidList(client);
uidList.forEach(this::unregisterPodOrIgnore);
};
taskReference.getAndUpdate(
task -> {
if (task != null) {
task.cancel();
}
return plugin
.getProxy()
.getScheduler()
.buildTask(plugin, runnable)
.repeat(5, TimeUnit.SECONDS)
.schedule();
});
}
@Override
public void shutdown() {
taskReference.getAndUpdate(
task -> {
if (task != null) {
task.cancel();
}
return null;
});
}
@Override
public HashMap<String, Pod> getServersForStartup() {
Map<String, String> podIdToServerNameMap;
if (redisConnectionLeader.isLeader()) {
try (Jedis jedis = jedisPool.getResource()) {
podIdToServerNameMap = new HashMap<>(jedis.hgetAll(RedisKeys.SERVERS_PREFIX + groupName));
for (String podUid : new ArrayList<>(podIdToServerNameMap.keySet())) {
if (getPodByUid(podUid) == null) {
podIdToServerNameMap.remove(podUid);
jedis.hdel(RedisKeys.SERVERS_PREFIX + groupName, podUid);
redisConnectionLeader.publishDeletedServer(podUid);
}
}
Map<String, String> loadBalancerMap =
jedis.hgetAll(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName);
client
.pods()
.inNamespace(namespace)
.withLabel(LabelKeys.ENABLE_SERVER_DISCOVERY.getKey(), "true")
.withField("status.phase", "Running")
.list()
.getItems()
.forEach(
pod -> {
String uid = pod.getMetadata().getUid();
if (podIdToServerNameMap.containsKey(uid)) {
return;
}
String preferServerName =
pod.getMetadata()
.getLabels()
.getOrDefault(
LabelKeys.PREFERRED_SERVER_NAME.getKey(),
pod.getMetadata().getName());
String serverName =
getValidServerName(
preferServerName,
(name) ->
!podIdToServerNameMap.containsValue(name)
&& !loadBalancerMap.containsValue(name)
&& plugin.getProxy().getServer(name).isEmpty());
podIdToServerNameMap.put(uid, serverName);
jedis.hset(RedisKeys.SERVERS_PREFIX + groupName, uid, serverName);
});
}
} else {
try (Jedis jedis = jedisPool.getResource()) {
podIdToServerNameMap = jedis.hgetAll(RedisKeys.SERVERS_PREFIX + groupName);
}
}
String verb = "Fetched";
if (redisConnectionLeader.isLeader()) {
verb = "Found";
}
for (String podUid : podIdToServerNameMap.keySet()) {
plugin
.getLogger()
.info(verb + " server: " + podIdToServerNameMap.get(podUid) + " (" + podUid + ")");
}
HashMap<String, Pod> servers = new HashMap<>();
for (Entry<String, String> entry : podIdToServerNameMap.entrySet()) {
Pod pod = getPodByUid(entry.getKey());
if (pod == null) {
continue;
}
servers.put(entry.getValue(), pod);
kuvelServiceHandler.getPodUidAndServerNameMap().register(entry.getKey(), entry.getValue());
}
return servers;
}
private void processUpdatedPod(Pod pod) {
lock.lock();
try {
if (pod.getStatus().getPhase().equalsIgnoreCase("Running")) {
registerPodOrIgnore(pod);
} else if (pod.getStatus().getPhase().equalsIgnoreCase("Terminating")) {
if (pod.getMetadata().getDeletionTimestamp() == null) {
return;
}
try {
Date deletionEndDate =
DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.parse(
pod.getMetadata().getDeletionTimestamp());
Date now = new Date();
long secondsRemaining = deletionEndDate.getTime() - now.getTime();
if (secondsRemaining < 50) {
unregisterPodOrIgnore(pod);
} else {
plugin
.getProxy()
.getScheduler()
.buildTask(
plugin,
() -> {
Pod p = getPodByUid(pod.getMetadata().getUid());
if (p != null) {
processUpdatedPod(p);
}
})
.delay(secondsRemaining - 49, TimeUnit.SECONDS)
.schedule();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
}
private void registerPodOrIgnore(Pod pod) {
String uid = pod.getMetadata().getUid();
if (kuvelServiceHandler.getPodUidAndServerNameMap().getServerNameFromUid(uid) != null) {
return;
}
String serverName;
try (Jedis jedis = jedisPool.getResource()) {
Map<String, String> serverMap = jedis.hgetAll(RedisKeys.SERVERS_PREFIX.getKey() + groupName);
Map<String, String> loadBalancerMap =
jedis.hgetAll(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName);
String preferServerName =
pod.getMetadata()
.getLabels()
.getOrDefault(LabelKeys.PREFERRED_SERVER_NAME.getKey(), pod.getMetadata().getName());
serverName =
getValidServerName(
preferServerName,
(name) ->
!serverMap.containsValue(name)
&& !loadBalancerMap.containsValue(name)
&& plugin.getProxy().getServer(name).isEmpty());
kuvelServiceHandler.getPodUidAndServerNameMap().register(uid, serverName);
jedis.hset(RedisKeys.SERVERS_PREFIX.getKey() + groupName, uid, serverName);
redisConnectionLeader.publishNewServer(uid, serverName);
kuvelServiceHandler.registerPod(pod, serverName);
}
}
private void unregisterPodOrIgnore(Pod pod) {
unregisterPodOrIgnore(pod.getMetadata().getUid());
}
public void unregisterPodOrIgnore(String uid) {
if (kuvelServiceHandler.getPodUidAndServerNameMap().getServerNameFromUid(uid) == null) {
return;
}
kuvelServiceHandler.unregisterPod(uid);
// podUidAndServerNameMap.unregister(uid); // no need
redisConnectionLeader.publishDeletedServer(uid);
try (Jedis jedis = jedisPool.getResource()) {
jedis.hdel(RedisKeys.SERVERS_PREFIX.getKey() + groupName, uid);
}
}
private Pod getPodByUid(String podUid) {
return client.pods().list().getItems().stream()
.filter(pod -> pod.getMetadata().getUid().equals(podUid))
.findFirst()
.orElse(null);
}
private String getValidServerName(String prefer, Function<String, Boolean> isValid) {
if (isValid.apply(prefer)) {
return prefer;
}
String name = prefer + "-1";
int i = 1;
while (!isValid.apply(name)) {
name = name.substring(0, name.length() - (1 + String.valueOf(i).length())) + "-" + (i + 1);
i++;
}
return name;
}
private Runnable getDelayRunnable(ExecutorService executor, Runnable runnable) {
return () -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
try {
runnable.run();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
executor.submit(getDelayRunnable(executor, runnable));
}
};
}
}
| 10,063 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RedisLoadBalancerDiscovery.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/discovery/impl/redis/RedisLoadBalancerDiscovery.java | package net.azisaba.kuvel.discovery.impl.redis;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerInfo;
import com.velocitypowered.api.scheduler.ScheduledTask;
import io.fabric8.kubernetes.api.model.apps.ReplicaSet;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.net.InetSocketAddress;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.Kuvel;
import net.azisaba.kuvel.KuvelServiceHandler;
import net.azisaba.kuvel.discovery.LoadBalancerDiscovery;
import net.azisaba.kuvel.discovery.diffchecker.ReplicaSetDiffChecker;
import net.azisaba.kuvel.loadbalancer.LoadBalancer;
import net.azisaba.kuvel.loadbalancer.strategy.impl.RoundRobinLoadBalancingStrategy;
import net.azisaba.kuvel.redis.RedisConnectionLeader;
import net.azisaba.kuvel.redis.RedisKeys;
import net.azisaba.kuvel.util.LabelKeys;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@RequiredArgsConstructor
public class RedisLoadBalancerDiscovery implements LoadBalancerDiscovery {
private final KubernetesClient client;
private final Kuvel plugin;
private final String namespace;
private final JedisPool jedisPool;
private final String groupName;
private final RedisConnectionLeader redisConnectionLeader;
private final KuvelServiceHandler kuvelServiceHandler;
private final AtomicReference<ScheduledTask> taskReference = new AtomicReference<>();
private final ReplicaSetDiffChecker replicaSetDiffChecker = new ReplicaSetDiffChecker().init();
private final ReentrantLock lock = new ReentrantLock();
private final HashMap<String, ArrayDeque<String>> loadBalancerDeleteWaitQueues = new HashMap<>();
@Override
public void start() {
if (!redisConnectionLeader.isLeader()) {
return;
}
Runnable runnable =
() -> {
List<ReplicaSet> replicaSetList =
client
.apps()
.replicaSets()
.inNamespace(namespace)
.withLabel(LabelKeys.ENABLE_SERVER_DISCOVERY.getKey(), "true")
.withLabel(LabelKeys.PREFERRED_SERVER_NAME.getKey())
.list()
.getItems();
for (ReplicaSet replicaSet : replicaSetList) {
if (replicaSetDiffChecker.diff(replicaSet)) {
processUpdatedReplicaSet(replicaSet);
}
}
List<String> deletedReplicaSetUid =
replicaSetDiffChecker.getDeletedReplicaSetUidList(client);
for (String uid : deletedReplicaSetUid) {
unregisterOrIgnore(uid);
}
};
taskReference.getAndUpdate(
task -> {
if (task != null) {
task.cancel();
}
return plugin
.getProxy()
.getScheduler()
.buildTask(plugin, runnable)
.repeat(5, TimeUnit.SECONDS)
.schedule();
});
}
private void processUpdatedReplicaSet(ReplicaSet replicaSet) {
lock.lock();
try {
if (replicaSet.getStatus().getReplicas() <= 0) {
unregisterOrIgnore(replicaSet.getMetadata().getUid());
} else {
registerOrIgnore(replicaSet);
}
} finally {
lock.unlock();
}
}
private void registerOrIgnore(ReplicaSet replicaSet) {
registerOrIgnore(replicaSet, false);
}
private void registerOrIgnore(ReplicaSet replicaSet, boolean isFetchedFromRedis) {
String uid = replicaSet.getMetadata().getUid();
if (kuvelServiceHandler.getReplicaSetUidAndServerNameMap().getServerNameFromUid(uid) != null) {
return;
}
String serverName =
replicaSet
.getMetadata()
.getLabels()
.getOrDefault(LabelKeys.PREFERRED_SERVER_NAME.getKey(), null);
boolean initialServer =
replicaSet
.getMetadata()
.getLabels()
.getOrDefault(LabelKeys.INITIAL_SERVER.getKey(), "false")
.equalsIgnoreCase("true");
if (serverName == null) {
return;
}
try (Jedis jedis = jedisPool.getResource()) {
if (!isFetchedFromRedis) {
Collection<String> loadBalancerNames =
jedis.hgetAll(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName).values();
if (loadBalancerNames.contains(serverName)
|| plugin.getProxy().getServer(serverName).isPresent()) {
if (loadBalancerDeleteWaitQueues.containsKey(serverName)) {
ArrayDeque<String> queue = loadBalancerDeleteWaitQueues.get(serverName);
if (!queue.contains(uid)) {
queue.add(uid);
}
} else {
ArrayDeque<String> queue = new ArrayDeque<>();
queue.add(uid);
loadBalancerDeleteWaitQueues.put(serverName, queue);
}
return;
}
}
kuvelServiceHandler.getReplicaSetUidAndServerNameMap().register(uid, serverName);
jedis.hset(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName, uid, serverName);
redisConnectionLeader.publishNewLoadBalancer(uid, serverName, initialServer);
RegisteredServer server =
plugin
.getProxy()
.registerServer(new ServerInfo(serverName, new InetSocketAddress("0.0.0.0", 0)));
kuvelServiceHandler.registerLoadBalancer(
new LoadBalancer(
plugin.getProxy(),
server,
new RoundRobinLoadBalancingStrategy(),
uid,
initialServer));
}
}
private void unregisterOrIgnore(String uid) {
String serverName =
kuvelServiceHandler.getReplicaSetUidAndServerNameMap().getServerNameFromUid(uid);
if (serverName == null) {
return;
}
kuvelServiceHandler.unregisterLoadBalancer(uid);
redisConnectionLeader.publishDeletedLoadBalancer(uid);
try (Jedis jedis = jedisPool.getResource()) {
jedis.hdel(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName, uid);
}
ArrayDeque<String> nextUidQueue = loadBalancerDeleteWaitQueues.get(serverName);
if (nextUidQueue == null) {
return;
}
ReplicaSet nextReplicaSet = null;
while (!nextUidQueue.isEmpty() && nextReplicaSet == null) {
String nextUid = nextUidQueue.poll();
nextReplicaSet = getReplicaSetFromUid(nextUid);
}
if (nextReplicaSet == null) {
return;
}
final ReplicaSet finalNextReplicaSet = nextReplicaSet;
plugin
.getProxy()
.getScheduler()
.buildTask(plugin, () -> registerOrIgnore(finalNextReplicaSet))
.delay(0, TimeUnit.SECONDS)
.schedule();
}
@Override
public void shutdown() {
taskReference.getAndUpdate(
task -> {
if (task != null) {
task.cancel();
}
return null;
});
}
@Override
public void registerLoadBalancersForStartup() {
if (redisConnectionLeader.isLeader()) {
try (Jedis jedis = jedisPool.getResource()) {
Map<String, String> uidAndServerNameMapInRedis =
jedis.hgetAll(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName);
for (Map.Entry<String, String> entry : uidAndServerNameMapInRedis.entrySet()) {
ReplicaSet replicaSet = getReplicaSetFromUid(entry.getKey());
if (replicaSet == null) {
jedis.hdel(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName, entry.getKey());
continue;
}
registerOrIgnore(replicaSet, true);
}
client
.apps()
.replicaSets()
.inNamespace(namespace)
.withLabel(LabelKeys.ENABLE_SERVER_DISCOVERY.getKey(), "true")
.withLabel(LabelKeys.PREFERRED_SERVER_NAME.getKey())
.list()
.getItems()
.stream()
.filter(replicaSet -> replicaSet.getStatus().getReplicas() > 0)
.filter(
replicaSet ->
!uidAndServerNameMapInRedis.containsKey(replicaSet.getMetadata().getUid()))
.forEach(this::registerOrIgnore);
}
} else {
try (Jedis jedis = jedisPool.getResource()) {
Map<String, String> uidAndServerNameMapInRedis =
jedis.hgetAll(RedisKeys.LOAD_BALANCERS_PREFIX.getKey() + groupName);
for (Map.Entry<String, String> entry : uidAndServerNameMapInRedis.entrySet()) {
ReplicaSet replicaSet = getReplicaSetFromUid(entry.getKey());
if (replicaSet == null) {
continue;
}
registerOrIgnore(replicaSet, true);
}
}
}
}
private ReplicaSet getReplicaSetFromUid(String uid) {
return client
.apps()
.replicaSets()
.inNamespace(namespace)
.withLabel(LabelKeys.ENABLE_SERVER_DISCOVERY.getKey(), "true")
.withLabel(LabelKeys.PREFERRED_SERVER_NAME.getKey())
.list()
.getItems()
.stream()
.filter(replicaSet -> replicaSet.getMetadata().getUid().equals(uid))
.findAny()
.orElse(null);
}
}
| 9,367 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
PodDiffChecker.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/discovery/diffchecker/PodDiffChecker.java | package net.azisaba.kuvel.discovery.diffchecker;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class PodDiffChecker {
private final HashMap<String, Pod> podMap = new HashMap<>();
private final List<BiFunction<Pod, Pod, Boolean>> comparators = new ArrayList<>();
public PodDiffChecker init() {
comparators.clear();
comparators.add(
(pod1, pod2) -> Objects.equals(pod1.getStatus().getPhase(), pod2.getStatus().getPhase()));
return this;
}
public boolean diff(Pod pod) {
String uid = pod.getMetadata().getUid();
if (!podMap.containsKey(uid)) {
podMap.put(uid, pod);
return true;
}
Pod oldPod = podMap.get(uid);
for (BiFunction<Pod, Pod, Boolean> comparator : comparators) {
boolean equal = comparator.apply(oldPod, pod);
if (!equal) {
podMap.put(uid, pod);
return true;
}
}
return false;
}
public List<String> getDeletedPodUidList(KubernetesClient client) {
List<String> uidList = new ArrayList<>(podMap.keySet());
client.pods().list().getItems().forEach(pod -> uidList.remove(pod.getMetadata().getUid()));
for (String uid : uidList) {
podMap.remove(uid);
}
return uidList;
}
}
| 1,476 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
ReplicaSetDiffChecker.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/discovery/diffchecker/ReplicaSetDiffChecker.java | package net.azisaba.kuvel.discovery.diffchecker;
import io.fabric8.kubernetes.api.model.apps.ReplicaSet;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.BiFunction;
import lombok.NoArgsConstructor;
@NoArgsConstructor
public class ReplicaSetDiffChecker {
private final HashMap<String, ReplicaSet> replicaSetMap = new HashMap<>();
private final List<BiFunction<ReplicaSet, ReplicaSet, Boolean>> comparators = new ArrayList<>();
public ReplicaSetDiffChecker init() {
comparators.clear();
comparators.add(
(replica1, replica2) ->
Objects.equals(replica1.getSpec().getReplicas(), replica2.getSpec().getReplicas()));
return this;
}
public boolean diff(ReplicaSet replicaSet) {
String uid = replicaSet.getMetadata().getUid();
if (!replicaSetMap.containsKey(uid)) {
replicaSetMap.put(uid, replicaSet);
return true;
}
ReplicaSet oldReplicaSet = replicaSetMap.get(uid);
for (BiFunction<ReplicaSet, ReplicaSet, Boolean> comparator : comparators) {
boolean equal = comparator.apply(oldReplicaSet, replicaSet);
if (!equal) {
replicaSetMap.put(uid, replicaSet);
return true;
}
}
return false;
}
public List<String> getDeletedReplicaSetUidList(KubernetesClient client) {
List<String> uidList = new ArrayList<>(replicaSetMap.keySet());
client
.apps()
.replicaSets()
.list()
.getItems()
.forEach(pod -> uidList.remove(pod.getMetadata().getUid()));
for (String uid : uidList) {
replicaSetMap.remove(uid);
}
return uidList;
}
}
| 1,745 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
ProxyIdProvider.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/redis/ProxyIdProvider.java | package net.azisaba.kuvel.redis;
import com.velocitypowered.api.proxy.ProxyServer;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.RandomStringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;
@RequiredArgsConstructor
public class ProxyIdProvider {
private final JedisPool jedisPool;
private final String groupName;
private String id;
public String getId() {
if (id != null) {
return id;
}
try (Jedis jedis = jedisPool.getResource()) {
String idTmp = null;
while (idTmp == null) {
idTmp = RandomStringUtils.randomAlphanumeric(8);
String key = RedisKeys.PROXY_ID_PREFIX.getKey() + groupName + ":" + idTmp;
String result = jedis.set(key, "using", SetParams.setParams().nx().ex(300));
if (result == null) {
idTmp = null;
}
}
id = idTmp;
}
return id;
}
public void runTask(ProxyServer proxy, Object plugin) {
proxy
.getScheduler()
.buildTask(
plugin,
() -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.expire(RedisKeys.PROXY_ID_PREFIX.getKey() + groupName + ":" + id, 300);
}
})
.repeat(2, TimeUnit.MINUTES)
.schedule();
}
public void deleteProxyId() {
if (id == null) {
return;
}
try (Jedis jedis = jedisPool.getResource()) {
jedis.del(RedisKeys.PROXY_ID_PREFIX.getKey() + groupName + ":" + id);
}
}
}
| 1,617 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RedisConnectionLeader.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/redis/RedisConnectionLeader.java | package net.azisaba.kuvel.redis;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.Kuvel;
import net.azisaba.kuvel.discovery.impl.redis.RedisLoadBalancerDiscovery;
import net.azisaba.kuvel.discovery.impl.redis.RedisServerDiscovery;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;
@RequiredArgsConstructor
public class RedisConnectionLeader {
private final Kuvel plugin;
private final JedisPool jedisPool;
private final String groupName;
private final String proxyId;
private boolean leader = false;
private long leaderExpireAt = 0;
public boolean isLeader() {
if (leader && leaderExpireAt < System.currentTimeMillis()) {
leader = false;
}
return leader;
}
public boolean trySwitch() {
try (Jedis jedis = jedisPool.getResource()) {
String key = RedisKeys.LEADER_PREFIX.getKey() + groupName;
String result = jedis.set(key, proxyId, SetParams.setParams().nx().ex(10));
if (result != null) {
leader = true;
leaderExpireAt = System.currentTimeMillis() + (10 * 1000);
plugin.getLogger().info("This proxy was selected as a new leader.");
jedis.publish(RedisKeys.LEADER_CHANGED_NOTIFY_PREFIX.getKey() + groupName, proxyId);
runDiscoveryTask();
return true;
} else {
String currentLeader = jedis.get(RedisKeys.LEADER_PREFIX.getKey() + groupName);
if (Objects.equals(proxyId, currentLeader)) {
leader = true;
return true;
}
if (leader) {
stopDiscoveryTask();
}
leader = false;
return false;
}
}
}
public void extendLeaderExpire() {
if (!trySwitch()) {
return;
}
try (Jedis jedis = jedisPool.getResource()) {
jedis.expire(RedisKeys.LEADER_PREFIX.getKey() + groupName, 10);
leaderExpireAt = System.currentTimeMillis() + (10 * 1000);
}
}
public void leaveLeader() {
try (Jedis jedis = jedisPool.getResource()) {
String currentLeader = jedis.get(RedisKeys.LEADER_PREFIX.getKey() + groupName);
if (!Objects.equals(proxyId, currentLeader)) {
return;
}
jedis.del(RedisKeys.LEADER_PREFIX.getKey() + groupName);
jedis.publish(RedisKeys.LEADER_LEAVE_NOTIFY_PREFIX.getKey() + groupName, proxyId);
}
}
public void publishNewLoadBalancer(
String replicaSetUid, String serverName, boolean initialServer) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(
RedisKeys.LOAD_BALANCER_ADDED_NOTIFY_PREFIX.getKey() + groupName,
replicaSetUid + ":" + serverName + ":" + initialServer);
}
}
public void publishNewServer(String podUid, String serverName) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(
RedisKeys.POD_ADDED_NOTIFY_PREFIX.getKey() + groupName, podUid + ":" + serverName);
}
}
public void publishDeletedLoadBalancer(String replicaSetUid) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(
RedisKeys.LOAD_BALANCER_DELETED_NOTIFY_PREFIX.getKey() + groupName, replicaSetUid);
}
}
public void publishDeletedServer(String podUid) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.publish(RedisKeys.POD_DELETED_NOTIFY_PREFIX.getKey() + groupName, podUid);
}
}
private void runDiscoveryTask() {
if (plugin.getKuvelConfig().getRedisConnectionData() == null) {
leaveLeader();
return;
}
plugin
.getKuvelServiceHandler()
.setAndRunLoadBalancerDiscovery(
new RedisLoadBalancerDiscovery(
plugin.getClient(),
plugin,
plugin.getKuvelConfig().getNamespace(),
plugin.getKuvelConfig().getRedisConnectionData().createJedisPool(),
plugin.getKuvelConfig().getProxyGroupName(),
this,
plugin.getKuvelServiceHandler()));
plugin
.getKuvelServiceHandler()
.setAndRunServerDiscovery(
new RedisServerDiscovery(
plugin.getClient(),
plugin,
plugin.getKuvelConfig().getNamespace(),
plugin.getKuvelConfig().getRedisConnectionData().createJedisPool(),
plugin.getKuvelConfig().getProxyGroupName(),
this,
plugin.getKuvelServiceHandler()));
}
private void stopDiscoveryTask() {
plugin.getKuvelServiceHandler().setAndRunLoadBalancerDiscovery(null);
plugin.getKuvelServiceHandler().setAndRunServerDiscovery(null);
}
}
| 4,673 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RedisSubscriberExecutor.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/redis/RedisSubscriberExecutor.java | package net.azisaba.kuvel.redis;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import net.azisaba.kuvel.Kuvel;
import net.azisaba.kuvel.KuvelServiceHandler;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;
@RequiredArgsConstructor
public class RedisSubscriberExecutor {
private final JedisPool jedisPool;
private final String groupName;
@Getter @Setter private ExecutorService executorService = Executors.newFixedThreadPool(1);
public void subscribe(
Kuvel plugin,
KuvelServiceHandler kuvelServiceHandler,
RedisConnectionLeader redisConnectionLeader) {
JedisPubSub subscriber =
new RedisSubscriber(plugin, groupName, kuvelServiceHandler, redisConnectionLeader);
Runnable task =
() -> {
try (Jedis jedis = jedisPool.getResource()) {
jedis.psubscribe(
subscriber, RedisKeys.NOTIFY_CHANNEL_PREFIX.getKey() + "*:" + groupName);
}
};
executorService.submit(getDelayRunnable(executorService, task));
}
private Runnable getDelayRunnable(ExecutorService executor, Runnable runnable) {
return () -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
try {
runnable.run();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
executor.submit(getDelayRunnable(executor, runnable));
}
};
}
}
| 1,636 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RedisSubscriber.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/redis/RedisSubscriber.java | package net.azisaba.kuvel.redis;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerInfo;
import java.net.InetSocketAddress;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import net.azisaba.kuvel.Kuvel;
import net.azisaba.kuvel.KuvelServiceHandler;
import net.azisaba.kuvel.loadbalancer.LoadBalancer;
import net.azisaba.kuvel.loadbalancer.strategy.impl.RoundRobinLoadBalancingStrategy;
import redis.clients.jedis.JedisPubSub;
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
public class RedisSubscriber extends JedisPubSub {
private final Kuvel plugin;
private final String groupName;
private final KuvelServiceHandler kuvelServiceHandler;
private final RedisConnectionLeader redisConnectionLeader;
@Override
public void onPMessage(String pattern, String channel, String message) {
String receivedGroupName = channel.split(":")[channel.split(":").length - 1];
if (!receivedGroupName.equalsIgnoreCase(groupName)) {
return;
}
if (channel.startsWith(RedisKeys.LEADER_CHANGED_NOTIFY_PREFIX.getKey())
|| channel.startsWith(RedisKeys.LEADER_LEAVE_NOTIFY_PREFIX.getKey())) {
redisConnectionLeader.trySwitch();
return;
}
if (redisConnectionLeader.isLeader()) {
return;
}
if (channel.startsWith(RedisKeys.POD_ADDED_NOTIFY_PREFIX.getKey())) {
String podUid = message.split(":")[0];
String serverName = message.split(":")[1];
kuvelServiceHandler.registerPod(podUid, serverName);
} else if (channel.startsWith(RedisKeys.LOAD_BALANCER_ADDED_NOTIFY_PREFIX.getKey())) {
String replicaSetUid = message.split(":")[0];
String serverName = message.split(":")[1];
boolean initialServer = Boolean.parseBoolean(message.split(":")[2]);
RegisteredServer server =
plugin
.getProxy()
.registerServer(new ServerInfo(serverName, new InetSocketAddress("0.0.0.0", 0)));
LoadBalancer loadBalancer =
new LoadBalancer(
plugin.getProxy(),
server,
new RoundRobinLoadBalancingStrategy(),
replicaSetUid,
initialServer);
kuvelServiceHandler.registerLoadBalancer(loadBalancer);
} else if (channel.startsWith(RedisKeys.POD_DELETED_NOTIFY_PREFIX.getKey())) {
kuvelServiceHandler.unregisterPod(message);
} else if (channel.startsWith(RedisKeys.LOAD_BALANCER_DELETED_NOTIFY_PREFIX.getKey())) {
kuvelServiceHandler.unregisterLoadBalancer(message);
}
}
}
| 2,587 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RedisKeys.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/redis/RedisKeys.java | package net.azisaba.kuvel.redis;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public enum RedisKeys {
LEADER_PREFIX("kuvel:leader:"),
PROXY_ID_PREFIX("kuvel:proxy-id:"),
SERVERS_PREFIX("kuvel:servers:"),
LOAD_BALANCERS_PREFIX("kuvel:load-balancers:"),
NOTIFY_CHANNEL_PREFIX("kuvel:notify:"),
POD_ADDED_NOTIFY_PREFIX("kuvel:notify:add:pod:"),
LOAD_BALANCER_ADDED_NOTIFY_PREFIX("kuvel:notify:add:lb:"),
POD_DELETED_NOTIFY_PREFIX("kuvel:notify:del:pod:"),
LOAD_BALANCER_DELETED_NOTIFY_PREFIX("kuvel:notify:del:lb:"),
LEADER_LEAVE_NOTIFY_PREFIX("kuvel:notify:leader-leave:"),
LEADER_CHANGED_NOTIFY_PREFIX("kuvel:notify:leader-changed:");
private final String key;
public String getKey() {
return key;
}
@Override
public String toString() {
return getKey();
}
}
| 881 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
LoadBalancer.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/loadbalancer/LoadBalancer.java | package net.azisaba.kuvel.loadbalancer;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public class LoadBalancer {
private final ProxyServer proxy;
private final RegisteredServer server;
private final LoadBalancingStrategy strategy;
private final String replicaSetUid;
private final boolean isInitialServer;
private final List<String> endpointServers = new ArrayList<>();
public void addEndpoint(String serverName) {
if (!endpointServers.contains(serverName)) {
endpointServers.add(serverName);
}
}
public void removeEndpoint(String serverName) {
endpointServers.remove(serverName);
}
public void setEndpoints(List<String> endpoints) {
endpointServers.clear();
endpointServers.addAll(endpoints);
}
public RegisteredServer getTarget() {
List<RegisteredServer> servers =
endpointServers.stream()
.map(name -> proxy.getServer(name).orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
return strategy.choose(servers);
}
// public List<RegisteredServer> getTargets(int count) {
// List<RegisteredServer> servers =
// endpointServers.stream()
// .map(name -> proxy.getServer(name).orElse(null))
// .filter(Objects::nonNull)
// .collect(Collectors.toList());
//
// return strategy.choose(servers, count);
// }
}
| 1,678 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
LoadBalancingStrategy.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/loadbalancer/LoadBalancingStrategy.java | package net.azisaba.kuvel.loadbalancer;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.List;
public interface LoadBalancingStrategy {
RegisteredServer choose(List<RegisteredServer> servers);
// List<RegisteredServer> choose(List<RegisteredServer> servers, int count);
}
| 311 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RoundRobinLoadBalancingStrategy.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/loadbalancer/strategy/impl/RoundRobinLoadBalancingStrategy.java | package net.azisaba.kuvel.loadbalancer.strategy.impl;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.List;
import net.azisaba.kuvel.loadbalancer.LoadBalancingStrategy;
public class RoundRobinLoadBalancingStrategy implements LoadBalancingStrategy {
private int lastIndex = 0;
@Override
public RegisteredServer choose(List<RegisteredServer> servers) {
if (servers.isEmpty()) {
return null;
}
lastIndex++;
if (servers.size() <= lastIndex) {
lastIndex = 0;
return servers.get(0);
}
return servers.get(lastIndex);
}
// @Override
// public List<RegisteredServer> choose(List<RegisteredServer> servers, int count) {
// List<RegisteredServer> chosenServers = new ArrayList<>();
// for (int i = 0; i < count; i++) {
// chosenServers.add(choose(servers));
// }
//
// return chosenServers;
// }
}
| 912 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
MinimumPlayerLoadBalancingStrategy.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/loadbalancer/strategy/impl/MinimumPlayerLoadBalancingStrategy.java | package net.azisaba.kuvel.loadbalancer.strategy.impl;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.Comparator;
import java.util.List;
import net.azisaba.kuvel.loadbalancer.LoadBalancingStrategy;
public class MinimumPlayerLoadBalancingStrategy implements LoadBalancingStrategy {
@Override
public RegisteredServer choose(List<RegisteredServer> servers) {
if (servers.isEmpty()) {
return null;
}
return servers.stream()
.min(Comparator.comparingInt(a -> a.getPlayersConnected().size()))
.orElse(null);
}
// @Override
// public List<RegisteredServer> choose(List<RegisteredServer> servers, int count) {
// List<RegisteredServer> chosenServers = new ArrayList<>();
// HashMap<String, Integer> addedPlayerCount = new HashMap<>();
//
// for (int i = 0; i < count; i++) {
// RegisteredServer server =
// servers.stream()
// .min(
// (server1, server2) -> {
// int server1Count =
// server1.getPlayersConnected().size()
// + addedPlayerCount.getOrDefault(server1.getServerInfo().getName(),
// 0);
// int server2Count =
// server2.getPlayersConnected().size()
// + addedPlayerCount.getOrDefault(server2.getServerInfo().getName(),
// 0);
// return server1Count - server2Count;
// })
// .orElse(null);
// if (server == null) {
// throw new IllegalStateException("No server found");
// }
//
// chosenServers.add(server);
// addedPlayerCount.put(
// server.getServerInfo().getName(),
// addedPlayerCount.getOrDefault(server.getServerInfo().getName(), 0) + 1);
// }
//
// return chosenServers;
// }
}
| 1,925 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
RedisConnectionData.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/util/RedisConnectionData.java | package net.azisaba.kuvel.util;
import java.util.Objects;
import lombok.Data;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Data
public class RedisConnectionData {
private final String hostname;
private final int port;
private final String username;
private final String password;
public RedisConnectionData(String hostname, int port, String username, String password) {
if (Objects.equals(username, "")) {
username = null;
}
if (Objects.equals(password, "")) {
password = null;
}
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
}
public RedisConnectionData(String hostname, int port) {
this(hostname, port, null, null);
}
public RedisConnectionData(String hostname, int port, String password) {
this(hostname, port, null, password);
}
public JedisPool createJedisPool() {
if (username != null && password != null) {
return new JedisPool(hostname, port, username, password);
} else if (password != null) {
return new JedisPool(new JedisPoolConfig(), hostname, port, 3000, password);
} else if (username != null) {
throw new IllegalArgumentException(
"Redis password cannot be null if redis username is not null");
} else {
return new JedisPool(new JedisPoolConfig(), hostname, port);
}
}
}
| 1,414 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
UidAndServerNameMap.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/util/UidAndServerNameMap.java | package net.azisaba.kuvel.util;
import java.util.HashMap;
import java.util.Map;
public class UidAndServerNameMap {
private final HashMap<String, String> uidToServerName = new HashMap<>();
public String getServerNameFromUid(String podUid) {
return uidToServerName.get(podUid);
}
public String getUidFromServerName(String serverName) {
for (String podUid : uidToServerName.keySet()) {
if (uidToServerName.get(podUid).equals(serverName)) {
return podUid;
}
}
return null;
}
public Map<String, String> getAllMap() {
return new HashMap<>(uidToServerName);
}
public void register(String uid, String serverName) {
uidToServerName.put(uid, serverName);
}
public String unregister(String uid) {
return uidToServerName.remove(uid);
}
}
| 804 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
LabelKeys.java | /FileExtraction/Java_unseen/AzisabaNetwork_Kuvel/src/main/java/net/azisaba/kuvel/util/LabelKeys.java | package net.azisaba.kuvel.util;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public enum LabelKeys {
ENABLE_SERVER_DISCOVERY("enable-server-discovery"),
PREFERRED_SERVER_NAME("preferred-server-name"),
INITIAL_SERVER("initial-server");
private final String key;
public String getKey() {
return "kuvel.azisaba.net/" + key;
}
@Override
public String toString() {
return getKey();
}
}
| 488 | Java | .java | AzisabaNetwork/Kuvel | 27 | 2 | 10 | 2022-03-22T09:56:50Z | 2024-04-28T03:34:03Z |
Logout.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/Logout.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "Logout", urlPatterns = {"/logout"})
public class Logout extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("ID", null);
session.setAttribute("UTYPE", null);
session.setAttribute("NAME", null);
session.setAttribute("MSG", null);
session.removeAttribute("ID");
session.removeAttribute("UTYPE");
session.removeAttribute("NAME");
session.removeAttribute("MSG");
session.invalidate();
HttpSession sess = request.getSession(true);
sess.setAttribute("LOGIN", "Logout Successfuly !!");
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.forward(request, response);
}
}
| 1,293 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
GenerateOTP.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/GenerateOTP.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "GenerateOTP", urlPatterns = {"/generateOTP"})
public class GenerateOTP extends HttpServlet {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs, rst = null;
String userid = null;
String email = null;
String result = "";
int otp = 0;
int i = 0;
String host = "smtp.gmail.com";
String port = "587";
String userName = "emailID";
String password = "emailPass";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
//connection from database
try {
con = connection.dbConnection.makeConnection();
} catch (Exception e) {
}
userid = request.getParameter("userid");
//Generate random no
Random rand = new Random();
otp = rand.nextInt((999999 - 100000) + 1) + 100000;
/*Self generated algorithm */
BigInteger ciphertxt = new BigInteger(userid);
byte[] byteArray2 = ciphertxt.toByteArray();
String s2 = new String(byteArray2);
userid = s2.substring(3, s2.length());
//send email to user
try {
String query = "SELECT email FROM users WHERE userid = '" + userid + "' AND u_status = '1'";
pst = con.prepareStatement(query);
rst = pst.executeQuery();
if (rst.next()) {
email = rst.getString(1);
System.out.println("email: " + email);
String subject = "OTP from Secure Cloud using ECC";
String message = "Your OTP is " + otp;
//Send email
try {
EmailUtility.sendEmail(host, port, userName, password, email, subject,
message);
// resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
//resultMessage = "There were an error: " + ex.getMessage();
}
} else {
result = "Your user id does not exits.";
}
} catch (Exception e) {
e.printStackTrace();
}
//Check user is today generate otp or not
//check otp is exits or not
try {
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
String curDate = ft.format(dNow);
String mysql_query = "SELECT * FROM user_login WHERE userid = '" + userid + "' AND created = '" + curDate + "'";
pst = con.prepareStatement(mysql_query);
rs = pst.executeQuery();
if (rs.next()) {
String mysqlupdate = "UPDATE user_login set otp = '" + otp + "' WHERE userid = '" + userid + "' AND created = '" + curDate + "'";
pst = con.prepareStatement(mysqlupdate);
i = pst.executeUpdate();
if (i > 0) {
result = "OTP has been successfully send on your registered email id.";
} else {
result = "OTP has not been generated, Please try again.";
}
} else {
String sqlquery = "INSERT INTO user_login(userid,otp,created) VALUES(?,?,NOW())";
pst = con.prepareStatement(sqlquery);
pst.setString(1, userid);
pst.setInt(2, otp);
i = pst.executeUpdate();
if (i > 0) {
result = "OTP has been successfully send on your registered email id.";
} else {
result = "OTP has not been generated, Please try again.";
}
}
} catch (Exception e) {
e.printStackTrace();
}
out.write("<status><sname>" + result + "</sname></status>");
}
}
| 4,727 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
Encryption.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/Encryption.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import connection.AES;
import static connection.ECC.bytesToHex;
import static connection.ECC.encryptString;
import static connection.ECC.generateSharedSecret;
import connection.GenerateRandomString;
import java.io.*;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.*;
@WebServlet(name = "Encryption", urlPatterns = {"/encryption"})
public class Encryption extends HttpServlet {
static Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
String filename = null;
String file_name = null;
String fullImagepath = null;
String count = null;
String upload_filepath = null;
String uploadfile = null;
String algo = null;
String aeskey = null;
String xkey = null;
boolean flag;
String encryptedkey = null;
String cipherText = null;
PrivateKey privKeyU = null;
PublicKey pubKeyU = null;
String secretU = null;
String secretV = null;
String instance = "ECDH";
int i = 0;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String file_path = request.getParameter("filepath");
HttpSession session = request.getSession(true);
String uid = (String) session.getAttribute("ID");
ServletConfig config = getServletConfig();
String context = config.getServletContext().getRealPath("/");
String filePath = context + File.separator + file_path;
try {
con = connection.dbConnection.makeConnection();
String query = "DELETE FROM files WHERE id= '" + id + "' and userid='" + uid + "' ";
pst = con.prepareStatement(query);
i = pst.executeUpdate();
//delete files
File file = new File(filePath);
file.delete();
} catch (Exception e) {
}
if (i > 0) {
session.setAttribute("MSG", "File has been successfuly deleted !!");
response.sendRedirect("downloadfile.jsp");
} else {
session.setAttribute("MSG", "File has not been deleted !!");
response.sendRedirect("downloadfile.jsp");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String uid = (String) session.getAttribute("ID");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ServletConfig config = getServletConfig();
String context = config.getServletContext().getRealPath("/");
//connection from database
try {
con = connection.dbConnection.makeConnection();
} catch (Exception e) {
}
String filePath = context + File.separator + "uploads" + File.separator;
boolean status = false;
String enc_filpath = null;
java.util.Date d = new java.util.Date();
long timestamp = d.getTime();
try {
File projectDir = new File(filePath);
if (!projectDir.exists()) {
projectDir.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
boolean isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List/*FileItem*/ items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase("xkey")) {
xkey = item.getString();
}
} else {
// upload first image
if (item.getFieldName().equalsIgnoreCase("txtfile")) {
filename = item.getName();
if (!filename.equalsIgnoreCase("")) {
String extension = filename.substring(filename.lastIndexOf("."), filename.length());
file_name = "encrypted" + extension;//full image path
enc_filpath = filePath + File.separator + file_name;
File file3 = new File(enc_filpath);
uploadfile = "f" + timestamp + extension;
upload_filepath = "uploads/" + uploadfile;
enc_filpath = filePath + uploadfile;
GenerateRandomString grs = new GenerateRandomString();
aeskey = grs.getAlphaNumeric(16);
try {
item.write(file3);
AES aes = new AES();
String res = aes.Aesencrypt(file3, aeskey, enc_filpath);
if (res.equals("2")) {
upload_filepath = upload_filepath + ".aes";
status = true;
KeyPairGenerator kpg;
kpg = KeyPairGenerator.getInstance("EC", "SunEC");
ECGenParameterSpec ecsp;
ecsp = new ECGenParameterSpec(xkey);
kpg.initialize(ecsp);
KeyPair kpU = kpg.genKeyPair();
privKeyU = kpU.getPrivate();
pubKeyU = kpU.getPublic();
KeyPair kpV = kpg.genKeyPair();
PrivateKey privKeyV = kpV.getPrivate();
PublicKey pubKeyV = kpV.getPublic();
KeyAgreement ecdhU = KeyAgreement.getInstance("ECDH");
ecdhU.init(privKeyU);
ecdhU.doPhase(pubKeyV, true);
KeyAgreement ecdhV = KeyAgreement.getInstance("ECDH");
ecdhV.init(privKeyV);
ecdhV.doPhase(pubKeyU, true);
secretU = new BigInteger(1, ecdhU.generateSecret()).toString(16).toUpperCase();
secretV = new BigInteger(1, ecdhV.generateSecret()).toString(16).toUpperCase();
SecretKey secretKeyA = generateSharedSecret(kpV.getPrivate(),
kpV.getPublic());
cipherText = encryptString(secretKeyA, aeskey);
byte[] plainTextBytes = aeskey.getBytes("UTF-8");
cipherText = bytesToHex(plainTextBytes);
} else {
status = false;
}
} catch (Exception e1) {
e1.printStackTrace();
status = false;
}
file3.delete();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
status = false;
}
}
if (status) {
try {
String sqlquery = "INSERT INTO files(file_name,file_path,userid,created,encrypted_aes_key,privatekey) VALUES(?,?,?,NOW(),?,?)";
pst = con.prepareStatement(sqlquery);
pst.setString(1, filename);
pst.setString(2, upload_filepath);
pst.setString(3, uid);
pst.setString(4, cipherText);
pst.setString(5, secretV);
i = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();;
}
if (i > 0) {
String messge = "<span style='darkgreen'>Your file has been successfully encrypted.<br/> Your key is <strong>" + secretU + ".</strong> <br/>Please enter your key at a time of downloading files.</span>";
session.setAttribute("MSG", messge);
response.sendRedirect("encryption.jsp");
} else {
session.setAttribute("MSG", "File has not been uploaded.");
response.sendRedirect("encryption.jsp");
}
} else {
session.setAttribute("MSG", "File has not been uploaded.");
response.sendRedirect("encryption.jsp");
}
}
}
| 10,567 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
KeyGeneration.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/KeyGeneration.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Random;
import javax.crypto.KeyAgreement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "KeyGeneration", urlPatterns = {"/keyGeneration"})
public class KeyGeneration extends HttpServlet {
Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
String userid = null;
String secretekey = null;
String secretU = null;
String secretV = null;
String email = null;
int otp = 0;
String host = "smtp.gmail.com";
String port = "587";
String userName = "emailID";
String password = "emailPass";
int i = 0;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
//connection from database
try {
con = connection.dbConnection.makeConnection();
} catch (Exception e) {
}
userid = request.getParameter("userid");
secretekey = request.getParameter("secretkey");
//Generation ECC Key Agreement
try {
KeyPairGenerator kpg;
kpg = KeyPairGenerator.getInstance("EC", "SunEC");
ECGenParameterSpec ecsp;
//String parameter = "sect113r2";
ecsp = new ECGenParameterSpec(secretekey);
kpg.initialize(ecsp);
KeyPair kpU = kpg.genKeyPair();
PrivateKey privKeyU = kpU.getPrivate();
PublicKey pubKeyU = kpU.getPublic();
KeyPair kpV = kpg.genKeyPair();
PrivateKey privKeyV = kpV.getPrivate();
PublicKey pubKeyV = kpV.getPublic();
KeyAgreement ecdhU = KeyAgreement.getInstance("ECDH");
ecdhU.init(privKeyU);
ecdhU.doPhase(pubKeyV, true);
KeyAgreement ecdhV = KeyAgreement.getInstance("ECDH");
ecdhV.init(privKeyV);
ecdhV.doPhase(pubKeyU, true);
secretU = new BigInteger(1, ecdhU.generateSecret()).toString(16).toUpperCase();
secretV = new BigInteger(1, ecdhV.generateSecret()).toString(16).toUpperCase();
} catch (Exception e) {
e.printStackTrace();
}
//Generate random no
Random rand = new Random();
otp = rand.nextInt((999999 - 100000) + 1) + 100000;
try {
String query = "SELECT email FROM users WHERE userid = '" + userid + "' AND u_status = '1'";
pst = con.prepareStatement(query);
rst = pst.executeQuery();
if (rst.next()) {
email = rst.getString(1);
String subject = "OTP from Secure Cloud using ECC";
String message = "Your OTP is " + otp;
//Send email
try {
EmailUtility.sendEmail(host, port, userName, password, email, subject,
message);
// resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
//resultMessage = "There were an error: " + ex.getMessage();
}
} else {
session.setAttribute("MSG", "Secret key has not been generated.");
response.sendRedirect("keyexchange.jsp?userid=" + userid);
}
} catch (Exception e) {
}
try {
String sqlquery = "update users set user_key=?,secretu=?,user_otp=? where userid = '" + userid + "'";
pst = con.prepareStatement(sqlquery);
pst.setString(1, secretekey);
pst.setString(2, secretU);
pst.setInt(3, otp);
i = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
//success or failure message
if (i > 0) {
session.setAttribute("MSG", "ECDH Key agreement has been successfully generated.");
response.sendRedirect("secretkey.jsp?userid=" + userid + "&secretkey=" + secretU);
} else {
session.setAttribute("MSG", "Secret key has not been generated.");
response.sendRedirect("keyexchange.jsp?userid=" + userid);
}
}
}
| 5,029 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
DecryptedKey.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/DecryptedKey.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import static connection.ECC.decryptString;
import static connection.ECC.hexToBytes;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "DecryptedKey", urlPatterns = {"/decryptedKey"})
public class DecryptedKey extends HttpServlet {
Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
String userid = null;
String secretekey = null;
String secretU = null;
String secretV = null;
String email = null;
int otp = 0;
String fileid = null;
String privatekey = null;
int i = 0;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
//connection from database
try {
con = connection.dbConnection.makeConnection();
} catch (Exception e) {
}
fileid = request.getParameter("fileid");
String pubkey = request.getParameter("publickey");
try {
String query = "SELECT privatekey,file_path,encrypted_aes_key FROM files WHERE privatekey = '" + pubkey + "' AND id = '" + fileid + "'";
System.out.println("query: " + query);
pst = con.prepareStatement(query);
rst = pst.executeQuery();
if (rst.next()) {
privatekey = rst.getString(1);
String file_path = rst.getString(2);
String encrypted_aes_key = rst.getString(3);
// decode the base64 encoded string
String decryptedPlainText = null;
byte[] desc = hexToBytes(encrypted_aes_key.toString());
decryptedPlainText = new String(desc, "UTF-8");
response.sendRedirect("download_file.jsp?filename=" + file_path + "&aes_key=" + decryptedPlainText);
} else {
session.setAttribute("MSG", "Please enter valid public key.");
response.sendRedirect("keydescription.jsp?fileid=" + fileid);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 2,745 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
MyAccount.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/MyAccount.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "MyAccount", urlPatterns = {"/myAccount"})
public class MyAccount extends HttpServlet {
static Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
String name = null;
String email = null;
String mobile = null;
String dob = null;
String gender = null;
String id = null;
int i = 0;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
//connection from database
try {
con = connection.dbConnection.makeConnection();
} catch (Exception e) {
}
name = request.getParameter("name");
email = request.getParameter("email");
gender = request.getParameter("gender");
dob = request.getParameter("dob");
mobile = request.getParameter("mobile");
id = (String) session.getAttribute("ID");
try {
String sqlquery = "update users set name=?,email=?,gender=?,dob=?,mobile=? where userid = '" + id + "'";
pst = con.prepareStatement(sqlquery);
pst.setString(1, name);
pst.setString(2, email);
pst.setString(3, gender);
pst.setString(4, dob);
pst.setString(5, mobile);
i = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
//success or failure message
if (i > 0) {
session.setAttribute("MSG", "Your profile has been successfully update.");
response.sendRedirect("myaccount.jsp");
} else {
session.setAttribute("MSG", "Your profile has not been update.");
response.sendRedirect("myaccount.jsp");
}
}
}
| 2,375 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
Decryption.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/Decryption.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.*;
import connection.AES;
@WebServlet(name = "Description", urlPatterns = {"/description"})
public class Decryption extends HttpServlet {
static Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
String filename = null;
String file_name = null;
String fullImagepath = null;
String count = null;
String upload_filepath = null;
String uploadfile = null;
String aeskey = null;
boolean flag;
int i = 0;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String file_path = request.getParameter("filepath");
HttpSession session = request.getSession(true);
ServletConfig config = getServletConfig();
String context = config.getServletContext().getRealPath("/");
String filePath = context + File.separator + file_path;
try {
con = connection.dbConnection.makeConnection();
String query = "DELETE FROM files WHERE id= '" + id + "'";
pst = con.prepareStatement(query);
i = pst.executeUpdate();
//delete files
File file = new File(filePath);
file.delete();
} catch (Exception e) {
}
if (i > 0) {
session.setAttribute("MSG", "File has been successfuly deleted !!");
response.sendRedirect("filelist.jsp");
} else {
session.setAttribute("MSG", "File has not been deleted !!");
response.sendRedirect("filelist.jsp");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String uid = (String) session.getAttribute("ID");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ServletConfig config = getServletConfig();
String context = config.getServletContext().getRealPath("/");
String filePath = context + File.separator + "uploads" + File.separator + "downloads" + File.separator;
//Make download folder automatically
File projectDir = new File(filePath + "demo.txt");
if (!projectDir.exists()) {
projectDir.mkdirs();
}
projectDir.delete();
//connection from database
try {
con = connection.dbConnection.makeConnection();
} catch (Exception e) {
}
boolean status = false;
String enc_filpath = null;
String err = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List/*FileItem*/ items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase("publickey")) {
aeskey = item.getString();
}
} else {
if (item.getFieldName().equalsIgnoreCase("txtfile")) {
filename = item.getName();
if (!filename.equalsIgnoreCase("")) {
enc_filpath = filePath + filename;
try {
File file = new File(enc_filpath);
item.write(file);
AES aes = new AES();
String res = aes.Aesdecrypt(file, aeskey);
if (res.equals("2")) {
if (filename.endsWith(".aes")) {
filename = filename.substring(
0, filename.length() - 3);
file.delete();
status = true;
} else {
status = false;
}
} else {
status = false;
}
} catch (Exception e) {
//e.printStackTrace();
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
err += sw.getBuffer().toString();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
err += sw.getBuffer().toString();
status = false;
}
}
if (status) {
response.sendRedirect("download.jsp?filename=" + filename);
} else {
session.setAttribute("MSG", "Please enter correct file." + err);
response.sendRedirect("description.jsp");
}
}
}
| 6,783 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
FirstLogin.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/FirstLogin.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "FirstLogin", urlPatterns = {"/firstLogin"})
public class FirstLogin extends HttpServlet {
static Connection con = null;
PreparedStatement pst = null;
ResultSet rs, rst = null;
String reg_id = null;
String name = null;
String utype = null;
String otp = null;
String result = "";
String system_key = null;
String user_id = null;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
reg_id = request.getParameter("userid");
otp = request.getParameter("otp");
system_key = request.getParameter("secretekey");
try {
con = connection.dbConnection.makeConnection();
String query = "SELECT name,utype FROM users WHERE userid = '" + reg_id + "' AND user_otp = '" + otp + "' AND u_status = '1'";
pst = con.prepareStatement(query);
rst = pst.executeQuery();
if (rst.next()) {
name = rst.getString(1);
utype = rst.getString(2);
session.setAttribute("ID", reg_id);
session.setAttribute("NAME", name);
session.setAttribute("UTYPE", utype);
/*Self generated algorithm */
String key = system_key.substring(0, 3);
String text = key + reg_id;
byte[] fooBytes = text.getBytes();
BigInteger ciper = new BigInteger(fooBytes);
//update table
String query_update = "UPDATE users SET gen_user_id = '" + ciper + "' WHERE userid = '" + reg_id + "'";
pst = con.prepareStatement(query_update);
pst.executeUpdate();
response.sendRedirect("sucess_registration.jsp?userid=" + ciper);
} else {
session.setAttribute("MSG", "Userid and otp are wrong.");
response.sendRedirect("secretkey.jsp?userid=" + reg_id + "&secretkey=" + system_key);
}
} catch (Exception e) {
session.setAttribute("MSG", "Userid does not exits.");
response.sendRedirect("secretkey.jsp?userid=" + reg_id + "&secretkey=" + system_key);
}
}
}
| 2,878 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
Login.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/Login.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.IOException;
import java.math.BigInteger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpSession;
@WebServlet(name = "Login", urlPatterns = {"/login"})
public class Login extends HttpServlet {
static Connection con = null;
PreparedStatement pst = null;
ResultSet rs, rst = null;
String userid = null;
String name = null;
String utype = null;
String otp = null;
String result = "";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
userid = request.getParameter("userid");
otp = request.getParameter("otp");
/*Self generated algorithm */
BigInteger ciphertxt = new BigInteger(userid);
byte[] byteArray2 = ciphertxt.toByteArray();
String s2 = new String(byteArray2);
userid = s2.substring(3, s2.length());
try {
con = connection.dbConnection.makeConnection();
String query = "SELECT name,utype FROM users WHERE userid = '" + userid + "' AND u_status = '1'";
pst = con.prepareStatement(query);
rst = pst.executeQuery();
if (rst.next()) {
name = rst.getString(1);
utype = rst.getString(2);
//check otp is exits or not
try {
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
String curDate = ft.format(dNow);
String mysql_query = "SELECT * FROM user_login WHERE userid = '" + userid + "' AND otp = '" + otp + "' AND created = '" + curDate + "'";
pst = con.prepareStatement(mysql_query);
rs = pst.executeQuery();
if (rs.next()) {
session.setAttribute("ID", userid);
session.setAttribute("NAME", name);
session.setAttribute("UTYPE", utype);
response.sendRedirect("myaccount.jsp");
} else {
session.setAttribute("MSG", "OTP is wrong. Please try again.");
response.sendRedirect("login.jsp");
}
} catch (Exception e) {
}
} else {
session.setAttribute("MSG", "Userid does not exits.");
response.sendRedirect("login.jsp");
}
} catch (Exception e) {
session.setAttribute("MSG", "Userid does not exits.");
response.sendRedirect("login.jsp");
}
}
}
| 3,282 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
Register.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/Register.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "Register", urlPatterns = {"/register"})
public class Register extends HttpServlet {
static Connection con = null;
PreparedStatement pst = null;
ResultSet rst = null;
String name = null;
String email = null;
String mobile = null;
String dob = null;
String gender = null;
String userid = null;
int i = 0;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
userid = request.getParameter("reg_id");
HttpSession session = request.getSession(true);
try {
con = connection.dbConnection.makeConnection();
String query = "delete from users WHERE userid= '" + userid + "' ";
pst = con.prepareStatement(query);
i = pst.executeUpdate();
} catch (Exception e) {
}
if (i > 0) {
session.setAttribute("MSG", "User has been successfuly deleted !!");
response.sendRedirect("usrelist.jsp");
} else {
session.setAttribute("MSG", "User has not been deleted !!");
response.sendRedirect("usrelist.jsp");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ServletConfig config = getServletConfig();
String context = config.getServletContext().getRealPath("/");
//connection from database
try {
con = connection.dbConnection.makeConnection();
} catch (Exception e) {
}
userid = connection.AutoID.globalGenId("registration");
name = request.getParameter("name");
email = request.getParameter("email");
mobile = request.getParameter("mobile");
dob = request.getParameter("dob");
gender = request.getParameter("gender");
try {
String sqlquery = "INSERT INTO users(userid,name,email,mobile,dob,gender,created) VALUES(?,?,?,?,?,?, NOW())";
pst = con.prepareStatement(sqlquery);
pst.setString(1, userid);
pst.setString(2, name);
pst.setString(3, email);
pst.setString(4, mobile);
pst.setString(5, dob);
pst.setString(6, gender);
i = pst.executeUpdate();
} catch (Exception e) {
e.printStackTrace();;
}
if (i > 0) {
connection.AutoID.updateAutoID("registration", userid);
response.sendRedirect("keyexchange.jsp?userid=" + userid);
} else {
session.setAttribute("MSG", "Your data has not been registered.");
response.sendRedirect("register.jsp");
}
}
}
| 3,506 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
EmailUtility.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/EmailUtility.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import com.sun.mail.util.MailSSLSocketFactory;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) throws AddressException,
MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
MailSSLSocketFactory sf;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException ex) {
Logger.getLogger(EmailUtility.class.getName()).log(Level.SEVERE, null, ex);
}
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = {new InternetAddress(toAddress)};
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
| 2,369 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
AdminLogin.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/org/AdminLogin.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package org;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.http.HttpSession;
@WebServlet(name = "AdminLogin", urlPatterns = {"/adminLogin"})
public class AdminLogin extends HttpServlet {
static Connection con = null;
PreparedStatement pst = null;
ResultSet rs, rst = null;
String userid = null;
String name = null;
String utype = null;
String password = null;
String result = "";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
userid = request.getParameter("userid");
password = request.getParameter("password");
try {
con = connection.dbConnection.makeConnection();
String query = "SELECT name,utype FROM users WHERE userid = '" + userid + "' AND user_otp = '" + password + "' AND u_status = '1'";
pst = con.prepareStatement(query);
rst = pst.executeQuery();
if (rst.next()) {
name = rst.getString(1);
utype = rst.getString(2);
session.setAttribute("ID", userid);
session.setAttribute("NAME", name);
session.setAttribute("UTYPE", utype);
response.sendRedirect("myaccount.jsp");
} else {
session.setAttribute("MSG", "Userid and password are wrong.");
response.sendRedirect("adminlogin.jsp");
}
} catch (Exception e) {
e.printStackTrace();
session.setAttribute("MSG", "Userid and password are wrong.");
response.sendRedirect("adminlogin.jsp");
}
}
}
| 2,164 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
GenerateRandomString.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/connection/GenerateRandomString.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package connection;
public class GenerateRandomString {
private static final String ALPHA_NUM
= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public String getAlphaNumeric(int len) {
StringBuffer sb = new StringBuffer(len);
for (int i = 0; i < len; i++) {
int ndx = (int) (Math.random() * ALPHA_NUM.length());
sb.append(ALPHA_NUM.charAt(ndx));
}
return sb.toString();
}
}
| 524 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
dbConnection.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/connection/dbConnection.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package connection;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
public class dbConnection {
static Connection con = null;
PreparedStatement pst = null;
public static Connection makeConnection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cryptography", "root", "root");
} catch (Exception e) {
}
return con;
}
} | 574 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
AES.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/connection/AES.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package connection;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
/* Aes file encryption */
public class AES {
private static final long serialVersionUID = 1L;
private long read = 0;
//decryption method
public String Aesdecrypt(File f, String pwd) {
String res = null;
try {
String kind = "AES";
Cipher c = Cipher.getInstance(kind);
Key k = new SecretKeySpec(pwd.getBytes(), kind);
c.init(Cipher.DECRYPT_MODE, k);
String filename = f.getCanonicalPath();
if (filename.endsWith(".aes")) {
filename = filename.substring(
0, filename.length()
- kind.length()); // -suffix
} else {
res = "1";
}
FileInputStream fis
= new FileInputStream(f.getCanonicalPath());
FileOutputStream fos = new FileOutputStream(filename);
CipherInputStream cis = new CipherInputStream(fis, c);
byte[] buffer = new byte[0xFFFF];
final long size = f.length();
for (int len; (len = cis.read(buffer)) != -1;) {
fos.write(buffer, 0, len);
read += len;
}
cis.close();
fos.flush();
fos.close();
fis.close();
read = 0;
res = "2";
} catch (Exception x) {
res = "3";
x.printStackTrace();
}
return res;
}
//encrypt method
public String Aesencrypt(File f, String pwd, String uploadfilepath) {
String res = null;
try {
String kind = "AES";
Cipher c = Cipher.getInstance(kind);
Key k = new SecretKeySpec(pwd.getBytes(), kind);
c.init(Cipher.ENCRYPT_MODE, k);
FileInputStream fis
= new FileInputStream(f);
FileOutputStream fos
= new FileOutputStream(uploadfilepath + ".aes");
CipherOutputStream cos = new CipherOutputStream(fos, c);
final int size = (int) f.length();
byte[] buffer = new byte[0xFFFF];
for (int len; (len = fis.read(buffer)) != -1;) {
cos.write(buffer, 0, len);
read += len;
}
cos.flush();
cos.close();
fos.flush();
fos.close();
fis.close();
read = 0;
res = "2";
} catch (Exception x) {
res = "1";
x.printStackTrace();
}
return res;
}
} | 2,852 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
ECC.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/connection/ECC.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package connection;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyAgreement;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class ECC {
public static byte[] iv = new SecureRandom().generateSeed(16);
public static KeyPair generateECKeys(String secretekey) {
KeyPair kpU = null;
try {
KeyPairGenerator kpg;
kpg = KeyPairGenerator.getInstance("EC", "SunEC");
ECGenParameterSpec ecsp;
//String parameter = "sect113r2";
ecsp = new ECGenParameterSpec(secretekey);
kpg.initialize(ecsp);
kpU = kpg.genKeyPair();
} catch (Exception e) {
e.printStackTrace();
}
return kpU;
}
public static SecretKey generateSharedSecret(PrivateKey privateKey,
PublicKey publicKey) {
try {
KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH", "BC");
keyAgreement.init(privateKey);
keyAgreement.doPhase(publicKey, true);
SecretKey key = keyAgreement.generateSecret("AES");
return key;
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static String encryptString(SecretKey key, String plainText) {
try {
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] plainTextBytes = plainText.getBytes("UTF-8");
byte[] cipherText;
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipherText = new byte[cipher.getOutputSize(plainTextBytes.length)];
int encryptLength = cipher.update(plainTextBytes, 0,
plainTextBytes.length, cipherText, 0);
encryptLength += cipher.doFinal(cipherText, encryptLength);
return bytesToHex(cipherText);
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | UnsupportedEncodingException | ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
public static String decryptString(SecretKey key, String cipherText) {
try {
Key decryptionKey = new SecretKeySpec(key.getEncoded(),
key.getAlgorithm());
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] cipherTextBytes = hexToBytes(cipherText);
byte[] plainText;
cipher.init(Cipher.DECRYPT_MODE, decryptionKey, ivSpec);
plainText = new byte[cipher.getOutputSize(cipherTextBytes.length)];
int decryptLength = cipher.update(cipherTextBytes, 0,
cipherTextBytes.length, plainText, 0);
decryptLength += cipher.doFinal(plainText, decryptLength);
return new String(plainText, "UTF-8");
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | ShortBufferException | UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String bytesToHex(byte[] data, int length) {
String digits = "0123456789ABCDEF";
StringBuffer buffer = new StringBuffer();
for (int i = 0; i != length; i++) {
int v = data[i] & 0xff;
buffer.append(digits.charAt(v >> 4));
buffer.append(digits.charAt(v & 0xf));
}
return buffer.toString();
}
public static String bytesToHex(byte[] data) {
return bytesToHex(data, data.length);
}
public static byte[] hexToBytes(String string) {
int length = string.length();
byte[] data = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
data[i / 2] = (byte) ((Character.digit(string.charAt(i), 16) << 4) + Character
.digit(string.charAt(i + 1), 16));
}
return data;
}
}
| 5,307 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
AutoID.java | /FileExtraction/Java_unseen/varundhall_MajorProject-SecureCloud/Source Code/src/java/connection/AutoID.java | /**
* @author Varun Dhall
* All Rights Reserved.
*/
package connection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
public class AutoID {
static Connection con = null;
static ResultSet rs = null;
static PreparedStatement ps = null;
static String genID = "";
static String generateid = "";
public static String globalGenId(String form_name) {
try {
con = connection.dbConnection.makeConnection();
//genID = pref;
String temp = null;
String num = null;
int r = 1;
String sql = "select prefix from auto_id where form_name='" + form_name + "'";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
temp = rs.getString(1).trim();
//String auto_id[] = temp.split("-");
//num = auto_id[1];
r = Integer.parseInt(temp) + 1;
}
generateid = "";
if (r < 10) {
generateid = genID + "0000" + r;
} else if (r < 100) {
generateid = genID + "000" + r;
} else if (r < 1000) {
generateid = genID + "00" + r;
} else if (r < 10000) {
generateid = genID + "0" + r;
} else {
generateid = genID + r;
}
} catch (Exception e) {
}
return (generateid);
}
/********************** Method for update Auto generate id ***************************/
public static void updateAutoID(String form_name, String id) {
try {
Connection con22 = connection.dbConnection.makeConnection();
PreparedStatement pst22 = con22.prepareStatement("update auto_id set prefix='" + id + "' where form_name='" + form_name + "'");
pst22.executeUpdate();
} catch (Exception e) {
}
}
}
| 1,990 | Java | .java | varundhall/MajorProject-SecureCloud | 43 | 13 | 0 | 2016-11-11T18:54:48Z | 2017-04-11T20:40:14Z |
GrammarTransformer.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/tpg2bnf/GrammarTransformer.java | package ksp.kos.tpg2bnf;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Created on 06/03/16.
*
* @author ptasha
*/
public class GrammarTransformer {
private static final String TPG_PATH = "src/main/grammar/kRISC.tpg";
private static final String FLEX_PATH = "src/main/grammar/KerboScript.flex";
private static final String BNF_PATH = "src/main/grammar/KerboScript.bnf";
private String tpg;
private String flex;
private String bnf;
public static void main(String[] args) throws IOException {
new GrammarTransformer().transform();
}
private void transform() throws IOException {
tpg = new String(Files.readAllBytes(Paths.get(TPG_PATH)));
createFlex();
createBnf();
}
private void createFlex() throws IOException {
flex = tpg.replaceAll("(?s)" +
".*(" +
"// Terminals\n" +
"// ===================================================\n" +
".*" +
")" +
"// Rules\n.*",
"$1");
flex = flex.replaceAll("->", "=");
flex = flex.replaceAll("@\"(.*)\";", "$1");
flex = flex.replaceAll("\\(\\?i\\)", "");
flex = flex.replaceAll("\\\\b", "");
flex = flex.replaceAll("\\\\\"\"", "\\\\\"");
flex = flex.replaceAll("a-z", "a-zA-Z");
flex = flex.replaceAll("=(.+?)//", "=$1\\\\/\\\\/");
flex = flex.replaceAll("=([^\\\\\n]+?)/", "=$1\\\\/");
flex = flex.replaceAll("(\\[Skip\\])", "//$1");
flex = flex.replaceAll("(EOF)", "//$1");
Files.write(Paths.get(FLEX_PATH), flex.getBytes());
}
private void createBnf() throws IOException {
bnf = tpg.replaceAll("(?s)" +
".*(" +
"// Rules" +
".*" +
")",
"$1");
bnf = bnf.replaceAll("->", "::=");
bnf = bnf.replaceAll(";", "");
bnf = bnf.replaceAll("EOF", "");
Files.write(Paths.get(BNF_PATH), bnf.getBytes());
}
}
| 2,183 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
TrueAbstractMap.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/utils/TrueAbstractMap.java | package ksp.kos.utils;
import java.util.AbstractMap;
/**
* Created on 09/10/16.
*
* @author ptasha
*/
public abstract class TrueAbstractMap<K, V> extends AbstractMap<K, V> {
@Override
public boolean containsKey(Object key) {
return get(key)!=null;
}
@Override
public abstract V get(Object key);
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
| 536 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
MapBuilder.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/utils/MapBuilder.java | package ksp.kos.utils;
import java.util.Map;
/**
* Created on 10/04/16.
*
* @author ptasha
*/
public class MapBuilder<K, V> {
private final Map<K, V> map;
public MapBuilder(Map<K, V> map) {
this.map = map;
}
public MapBuilder<K, V> put(K key, V value) {
map.put(key, value);
return this;
}
public Map<K, V> getMap() {
return map;
}
}
| 403 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
KerboScriptFindUsagesProvider.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/KerboScriptFindUsagesProvider.java | package ksp.kos.ideaplugin;
import com.intellij.lang.cacheBuilder.DefaultWordsScanner;
import com.intellij.lang.cacheBuilder.WordsScanner;
import com.intellij.lang.findUsages.FindUsagesProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.TokenSet;
import ksp.kos.ideaplugin.parser.KerboScriptLexerAdapter;
import ksp.kos.ideaplugin.psi.KerboScriptTypes;
import ksp.kos.ideaplugin.psi.impl.KerboScriptNamedElementImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Created on 04/01/16.
*
* @author ptasha
*/
public class KerboScriptFindUsagesProvider implements FindUsagesProvider {
@Nullable
@Override
public WordsScanner getWordsScanner() {
return new DefaultWordsScanner(new KerboScriptLexerAdapter(),
TokenSet.create(KerboScriptTypes.IDENTIFIER, KerboScriptTypes.FILEIDENT),
TokenSet.create(TokenType.WHITE_SPACE), TokenSet.create(KerboScriptTypes.STRING));
}
@Override
public boolean canFindUsagesFor(@NotNull PsiElement psiElement) {
return psiElement instanceof PsiNamedElement;
}
@Nullable
@Override
public String getHelpId(@NotNull PsiElement psiElement) {
return null;
}
@NotNull
@Override
public String getType(@NotNull PsiElement element) {
if (element instanceof KerboScriptNamedElementImpl) {
KerboScriptNamedElementImpl kerboScriptElement = (KerboScriptNamedElementImpl) element;
switch (kerboScriptElement.getReferableType()) {
case FUNCTION:
return "function";
case VARIABLE:
return "variable";
case FILE:
return "script";
}
}
return "";
}
@NotNull
@Override
public String getDescriptiveName(@NotNull PsiElement element) {
if (element instanceof PsiNamedElement) {
String name = ((PsiNamedElement) element).getName();
if (name!=null) {
return name;
}
}
return "";
}
@NotNull
@Override
public String getNodeText(@NotNull PsiElement element, boolean useFullName) {
return getDescriptiveName(element);
}}
| 2,372 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
KerboScriptLanguage.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/KerboScriptLanguage.java | package ksp.kos.ideaplugin;
import com.intellij.lang.Language;
/**
* Created on 26/12/15.
*
* @author ptasha
*/
public class KerboScriptLanguage extends Language {
public static final KerboScriptLanguage INSTANCE = new KerboScriptLanguage();
public KerboScriptLanguage() {
super("KerboScript");
}
@Override
public boolean isCaseSensitive() {
return false;
}
}
| 408 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
KerboScriptFile.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/KerboScriptFile.java | package ksp.kos.ideaplugin;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.problems.WolfTheProblemSolver;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import ksp.kos.ideaplugin.psi.KerboScriptNamedElement;
import ksp.kos.ideaplugin.psi.KerboScriptPsiWalker;
import ksp.kos.ideaplugin.psi.KerboScriptScope;
import ksp.kos.ideaplugin.reference.*;
import ksp.kos.ideaplugin.reference.context.FileContext;
import ksp.kos.ideaplugin.reference.context.FileDuality;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created on 26/12/15.
*
* @author ptasha
*/
public class KerboScriptFile extends PsiFileBase implements KerboScriptScope, KerboScriptNamedElement, FileDuality {
private static final ReferenceType TYPE = new ReferenceType(ReferableType.FILE, OccurrenceType.GLOBAL);
private final Cache<PsiFileContext> cache = new Cache<>(this, new PsiFileContext(this));
public KerboScriptFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, KerboScriptLanguage.INSTANCE);
// Check is needed for tests
if (!getProject().isDefault() && getProject().getService(DumbService.class) != null) {
DumbService.getInstance(getProject()).runWhenSmart(() -> {
VirtualFile virtualFile = getVirtualFile();
if (virtualFile != null) {
WolfTheProblemSolver wolf = WolfTheProblemSolver.getInstance(getProject());
ApplicationManager.getApplication().executeOnPooledThread(() -> wolf.queue(virtualFile));
}
});
}
}
@NotNull
@Override
public FileType getFileType() {
return KerboScriptFileType.INSTANCE;
}
public KerboScriptFile resolveFile(String name) {
return findFile(stripExtension(name));
}
@Nullable
public KerboScriptFile findFile(String name) {
PsiDirectory directory = getContainingDirectory();
if (directory == null) return null;
for (PsiFile file : directory.getFiles()) {
if (file instanceof KerboScriptFile) {
if (((KerboScriptFile) file).getPureName().equals(name)) {
return (KerboScriptFile) file;
}
}
}
return null;
}
private long version = -1;
private final ReentrantLock cacheLock = new ReentrantLock();
public void checkVersion() {
if (!cacheLock.isHeldByCurrentThread()) {
if (cacheLock.tryLock()) {
try {
checkVersionInternal();
} finally {
cacheLock.unlock();
}
} else {
cacheLock.lock();
try {
checkVersionInternal();
} finally {
cacheLock.unlock();
}
}
}
}
private void checkVersionInternal() {
if (version != getModificationStamp()) {
getCachedScope().clear();
this.accept(new KerboScriptPsiWalker());
version = getModificationStamp();
}
}
@Override
public PsiFileContext getCachedScope() {
return cache.getScope();
}
@Override
public KerboScriptScope getScope() {
return this;
}
public static String getExtension(String name) {
if (name.endsWith(".ks")) {
return ".ks";
} else if (name.endsWith(".ksm")) {
return ".ksm";
}
return "";
}
public static String stripExtension(String name) {
String extension = getExtension(name);
return name.substring(0, name.length() - extension.length());
}
@NotNull
public String getPureName() {
return stripExtension(getName());
}
@Override
public ReferenceType getType() {
return TYPE;
}
@Override
public void setType(ReferenceType type) {
}
@Override
public @NotNull KerboScriptFile getSyntax() {
return this;
}
@Override
public FileContext getSemantics() {
return getCachedScope();
}
}
| 4,502 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
KerboScriptRefactoringSupportProvider.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/KerboScriptRefactoringSupportProvider.java | package ksp.kos.ideaplugin;
import com.intellij.lang.refactoring.RefactoringSupportProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner;
import org.jetbrains.annotations.NotNull;
/**
* Created on 04/01/16.
*
* @author ptasha
*/
public class KerboScriptRefactoringSupportProvider extends RefactoringSupportProvider {
@Override
public boolean isMemberInplaceRenameAvailable(@NotNull PsiElement element, PsiElement context) {
return (element instanceof PsiNameIdentifierOwner) && ((PsiNameIdentifierOwner) element).getNameIdentifier()!=null;
}
}
| 609 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
KerboScriptFileType.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/KerboScriptFileType.java | package ksp.kos.ideaplugin;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.fileTypes.LanguageFileType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* Created on 26/12/15.
*
* @author ptasha
*/
public class KerboScriptFileType extends LanguageFileType {
public static final KerboScriptFileType INSTANCE = new KerboScriptFileType();
public KerboScriptFileType() {
super(KerboScriptLanguage.INSTANCE);
}
@NotNull
@Override
public String getName() {
return "KerboScript";
}
@NotNull
@Override
public String getDescription() {
return "KerboScript";
}
@NotNull
@Override
public String getDefaultExtension() {
return "ks";
}
@Nullable
@Override
public Icon getIcon() {
return AllIcons.FileTypes.Text;
}
}
| 909 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
ParameterFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/ParameterFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.psi.KerboScriptDeclareParameterClause;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import java.util.Objects;
/**
* Created on 17/03/16.
*
* @author ptasha
*/
public class ParameterFlow extends BaseFlow<ParameterFlow> implements NamedFlow<ParameterFlow> {
private final String name;
public ParameterFlow(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public boolean addContext(ContextBuilder context) {
context.getMap().put(getName(), this);
return true;
}
@Override
public ParameterFlow differentiate(LocalContext context, ContextBuilder contextBuilder) {
contextBuilder.add(new ParameterFlow(name));
ParameterFlow diff = differentiate(context);
contextBuilder.add(diff);
return diff;
}
@Override
public ParameterFlow differentiate(LocalContext context) {
return new ParameterFlow(name+"_");
}
@Override
public String getText() {
return "parameter "+name+".";
}
public static ParameterFlow parse(KerboScriptDeclareParameterClause parameterClause) {
return new ParameterFlow(parameterClause.getName());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterFlow that = (ParameterFlow) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
| 1,656 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
FlowImporter.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/FlowImporter.java | package ksp.kos.ideaplugin.dataflow;
import com.intellij.psi.codeStyle.CodeStyleManager;
import ksp.kos.ideaplugin.KerboScriptFile;
import ksp.kos.ideaplugin.psi.KerboScriptBase;
import ksp.kos.ideaplugin.psi.KerboScriptElementFactory;
import ksp.kos.ideaplugin.psi.KerboScriptInstruction;
import ksp.kos.ideaplugin.psi.KerboScriptNamedElement;
import ksp.kos.ideaplugin.reference.context.Duality;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
/**
* Created on 05/04/16.
*
* @author ptasha
*/
public abstract class FlowImporter<F extends NamedFlow<F>> {
@NotNull
protected abstract Map<String, Duality> getMap(KerboScriptFile file);
public void importFlow(KerboScriptFile file, F flow) {
// TODO sort out /ns
Map<String, Duality> map = getMap(file);
KerboScriptInstruction instruction = importFlow(file, flow, map);
CodeStyleManager.getInstance(file.getProject()).reformatNewlyAddedElement(instruction.getParent().getNode(), instruction.getNode());
}
protected KerboScriptInstruction importFlow(KerboScriptFile file, F flow, Map<String, Duality> map) {
KerboScriptInstruction instruction = KerboScriptElementFactory.instruction(file.getProject(), flow.getText());
KerboScriptInstruction existing = getInstruction(map, flow);
if (existing != null) {
instruction = replaceExisting(instruction, existing);
} else {
instruction = insertInstruction(file, instruction, flow.getName(), map);
}
return instruction;
}
private KerboScriptInstruction getInstruction(Map<String, Duality> map, F flow) {
KerboScriptNamedElement element = Duality.getSyntax(map.get(flow.getName()));
if (element==null) {
return null;
}
return element.upTill(KerboScriptInstruction.class);
}
protected KerboScriptInstruction replaceExisting(KerboScriptInstruction instruction, KerboScriptInstruction existing) {
return (KerboScriptInstruction) existing.replace(instruction);
}
private KerboScriptInstruction insertInstruction(KerboScriptFile file, KerboScriptInstruction instruction, String name, Map<String, Duality> map) {
KerboScriptInstruction before = null;
for (Duality element : map.values()) {
if (element.getName().compareToIgnoreCase(name)>0) {
before = element.getSyntax().upTill(KerboScriptInstruction.class);
break;
}
}
if (before==null) {
instruction = addNewInstruction(file, instruction);
} else {
separator(instruction);
instruction = (KerboScriptInstruction) file.addBefore(instruction, before);
}
return instruction;
}
protected KerboScriptInstruction addNewInstruction(KerboScriptFile file, KerboScriptInstruction instruction) {
separator(file);
return (KerboScriptInstruction) file.add(instruction);
}
protected void separator(KerboScriptBase element) {
element.newLine();
}
}
| 3,090 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
BaseFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/BaseFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.expressions.ExpressionVisitor;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import java.util.HashSet;
import java.util.Set;
/**
* Created on 18/03/16.
*
* @author ptasha
*/
public abstract class BaseFlow<F extends BaseFlow<F>> implements Flow<F> {
private final Set<Flow<?>> dependees = new HashSet<>();
@Override
public void addDependee(Flow<?> flow) {
dependees.add(flow);
}
@Override
public void removeDependee(Flow<?> flow) {
dependees.remove(flow);
}
@Override
public Set<Flow<?>> getDependees() {
return dependees;
}
@Override
public boolean hasDependees() {
return !dependees.isEmpty();
}
@Override
public boolean addContext(ContextBuilder context) {
return true;
}
@Override
public F differentiate(LocalContext context, ContextBuilder contextBuilder) {
return differentiate(context);
}
@Override
public void accept(ExpressionVisitor visitor) {
}
}
| 1,082 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
ImportFlowImporter.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/ImportFlowImporter.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.KerboScriptFile;
import ksp.kos.ideaplugin.psi.KerboScriptDirective;
import ksp.kos.ideaplugin.psi.KerboScriptInstruction;
import ksp.kos.ideaplugin.psi.KerboScriptRunStmt;
import ksp.kos.ideaplugin.reference.context.Duality;
import ksp.kos.ideaplugin.reference.context.PsiDuality;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
/**
* Created on 09/04/16.
*
* @author ptasha
*/
public class ImportFlowImporter extends FlowImporter<ImportFlow> {
public static final ImportFlowImporter INSTANCE = new ImportFlowImporter();
@NotNull
@Override
protected Map<String, Duality> getMap(KerboScriptFile file) {
return file.getCachedScope().getImports();
}
@Override
protected KerboScriptInstruction addNewInstruction(KerboScriptFile file, KerboScriptInstruction instruction) {
for (KerboScriptInstruction before : file.getChildren(KerboScriptInstruction.class)) {
if (!(before instanceof KerboScriptDirective)) {
instruction = (KerboScriptInstruction) file.addBefore(instruction, before);
separator(instruction);
separator(instruction);
return instruction;
}
}
return super.addNewInstruction(file, instruction);
}
@Override
protected KerboScriptInstruction replaceExisting(KerboScriptInstruction instruction, KerboScriptInstruction existing) {
return existing;
}
@Override
protected KerboScriptInstruction importFlow(KerboScriptFile file, ImportFlow flow, Map<String, Duality> map) {
KerboScriptInstruction instruction = super.importFlow(file, flow, map);
KerboScriptRunStmt runStmt = instruction.getRunStmt();
map.put(runStmt.getName(), new PsiDuality(runStmt));
return instruction;
}
}
| 1,886 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
FunctionFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/FunctionFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.actions.differentiate.DiffContext;
import ksp.kos.ideaplugin.expressions.Number;
import ksp.kos.ideaplugin.expressions.*;
import ksp.kos.ideaplugin.expressions.inline.InlineFunction;
import ksp.kos.ideaplugin.psi.*;
import ksp.kos.ideaplugin.reference.DualitySelfResolvable;
import ksp.kos.ideaplugin.reference.FlowSelfResolvable;
import ksp.kos.ideaplugin.reference.ReferableType;
import ksp.kos.ideaplugin.reference.Reference;
import ksp.kos.ideaplugin.reference.context.Duality;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* Created on 12/03/16.
*
* @author ptasha
*/
public class FunctionFlow extends BaseFlow<FunctionFlow> implements NamedFlow<FunctionFlow>,
ReferenceFlow<FunctionFlow>, Duality {
private final LocalContext context;
private final String name;
private final ContextBuilder parameters;
private final ContextBuilder instructions;
public FunctionFlow(LocalContext context, String name, ContextBuilder parameters, ContextBuilder instructions) {
this.context = context;
this.name = name;
this.parameters = parameters;
parameters.buildMap();
this.instructions = instructions;
buildInstructionsMap();
}
private void buildInstructionsMap() {
instructions.buildMap();
instructions.getReturn().addDependee(this);
}
public static FunctionFlow parse(KerboScriptDeclareFunctionClause function) throws SyntaxException {
FunctionParser parser = new FunctionParser();
String name = function.getName();
parser.parseInstructions(function.getInstructionBlock().getInstructionList());
return new FunctionFlow(function.getKerboScriptFile().getCachedScope(), name, parser.getContext(), parser.getFlowContext());
// throw new SyntaxException("Return statement is not found for function " + name); // TODO check for return statement
}
@Override
public FunctionFlow differentiate(LocalContext context) {
ContextBuilder parameters = new ContextBuilder();
ContextBuilder flows = new ContextBuilder(parameters);
if (this.parameters.getList().size()==1) {
String name = getParameters().get(0).getName();
parameters.add(new ParameterFlow(name));
flows.add(new VariableFlow(false, name+"_", Number.ONE));
} else {
this.parameters.differentiate(context, parameters);
}
FunctionFlow diff = new FunctionFlow(context, name + "_", parameters, flows);
context.register(diff);
this.instructions.differentiate(context, flows);
diff.buildInstructionsMap();
diff.simplify();
return diff;
}
private void simplify() {
instructions.simplify();
parameters.simplify();
instructions.sort();
}
@Override
public String getText() {
String text = "";
text += "function " + name + " {\n";
text += parameters.getText() + "\n";
if (!parameters.getList().isEmpty()) text += "\n";
text += instructions.getText() + "\n";
text += "}";
return text;
}
@Override
public LocalContext getKingdom() {
return context;
}
@Override
public ReferableType getReferableType() {
return ReferableType.FUNCTION;
}
@Override
public String getName() {
return name;
}
public void visitExpresssions(ExpressionVisitor visitor) {
parameters.visit(visitor);
instructions.visit(visitor);
}
public InlineFunction getInlineFunction() {
MixedDependency dependency = instructions.getReturn();
ReturnFlow flow = dependency.getReturnFlow();
if (flow != null) {
Expression expression = flow.getExpression();
if (isSimple(expression)) {
return createInlineFunction(expression);
}
}
return null;
}
private boolean isSimple(Expression expression) {
if (ExpressionFlow.isSimple(expression)) {
return true;
} else if (expression instanceof Constant) {
return true;
} else if (expression instanceof Function) {
Function function = (Function) expression;
if (function.getArgs().length == 0) {
return true;
} else if (function.getArgs().length == 1) {
Expression arg = function.getArgs()[0];
if (arg instanceof Variable) {
Variable variable = (Variable) arg;
return parameters.getFlow(variable.getName()) != null;
}
}
} else if (expression instanceof Element) {
Element element = (Element) expression;
if (element.getPower().equals(Number.ONE)) {
return isSimple(element.getAtom());
}
}
return false;
}
@NotNull
private InlineFunction createInlineFunction(Expression expression) {
return new InlineFunction(name, getArgNames(), expression);
}
private String[] getArgNames() {
ArrayList<String> names = new ArrayList<>();
for (Flow<?> parameter : parameters.getList()) {
names.add(((ParameterFlow)parameter).getName());
}
return names.toArray(new String[0]);
}
@Override
public @Nullable KerboScriptNamedElement getSyntax() {
return null; // TODO implement
}
@Override
public FunctionFlow getSemantics() {
return this;
}
public List<ParameterFlow> getParameters() {
List<ParameterFlow> rtn = new ArrayList<>(parameters.getList().size());
for (Flow<?> parameter : parameters.getList()) {
rtn.add((ParameterFlow) parameter);
}
return rtn;
}
public void checkUsages() {
// TODO more elegant?
visitExpresssions(new ExpressionVisitor() {
@Override
public void visitFunction(Function function) {
FunctionFlow functionFlow = (FunctionFlow) FlowSelfResolvable.function(context, function.getName()).findDeclaration();
if (functionFlow!=null) {
if (functionFlow.getKingdom() instanceof DiffContext) {
functionFlow.addDependee(FunctionFlow.this);
}
}
addImport(functionFlow);
super.visitFunction(function);
}
@Override
public void visitVariable(Variable variable) {
addImport(DualitySelfResolvable.variable(context, variable.getName()).findDeclaration());
super.visitVariable(variable);
}
private void addImport(Reference declaration) {
if (declaration!=null) {
LocalContext context = declaration.getKingdom();
Duality duality = FunctionFlow.this.context.getDeclarations(ReferableType.FILE).get(context.getFileContext().getName());
if (duality != null) {
ImportFlow importFlow = (ImportFlow) duality.getSemantics();
importFlow.addDependee(FunctionFlow.this);
}
}
}
});
}
private static class FunctionParser extends InstructionsParser {
private final InstructionsParser parser = new InstructionsParser(getContext());
private boolean parametersParsed = false;
@Override
public boolean parseInstruction(KerboScriptInstruction instruction) throws SyntaxException {
if (parametersParsed) {
return parser.parseInstruction(instruction);
} else if (instruction instanceof KerboScriptDeclareStmt) {
KerboScriptDeclareStmt declareStmt = (KerboScriptDeclareStmt) instruction;
KerboScriptDeclareParameterClause declareParameterClause = declareStmt.getDeclareParameterClause();
if (declareParameterClause != null) {
addFlow(ParameterFlow.parse(declareParameterClause));
} else if (declareStmt.getDeclareIdentifierClause() != null) {
parametersParsed = true;
return parser.parseInstruction(instruction);
}
} else {
parametersParsed = true;
return parser.parseInstruction(instruction);
}
return true;
}
public ContextBuilder getFlowContext() {
return parser.getContext();
}
}
}
| 8,846 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
FunctionFlowImporter.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/FunctionFlowImporter.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.KerboScriptFile;
import ksp.kos.ideaplugin.psi.KerboScriptBase;
import ksp.kos.ideaplugin.reference.context.Duality;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
/**
* Created on 05/04/16.
*
* @author ptasha
*/
public class FunctionFlowImporter extends FlowImporter<FunctionFlow> {
public static final FunctionFlowImporter INSTANCE = new FunctionFlowImporter();
@Override
public void importFlow(KerboScriptFile file, FunctionFlow flow) {
super.importFlow(file, flow);
}
@Override
@NotNull
protected Map<String, Duality> getMap(KerboScriptFile file) {
return file.getCachedScope().getFunctions();
}
@Override
protected void separator(KerboScriptBase element) {
super.separator(element);
super.separator(element);
}
}
| 884 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
ReturnFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/ReturnFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.expressions.Expression;
import ksp.kos.ideaplugin.expressions.SyntaxException;
import ksp.kos.ideaplugin.psi.KerboScriptReturnStmt;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import org.jetbrains.annotations.NotNull;
/**
* Created on 12/03/16.
*
* @author ptasha
*/
public class ReturnFlow extends ExpressionFlow<ReturnFlow> {
public ReturnFlow(Expression expression) {
super(expression);
}
@NotNull
@Override
protected ReturnFlow create(Expression diff) {
return new ReturnFlow(diff);
}
@Override
public ReturnFlow differentiate(LocalContext context, ContextBuilder contextBuilder) {
ReturnFlow diff = differentiate(context);
contextBuilder.add(diff);
return diff;
}
@Override
public boolean addContext(ContextBuilder context) {
super.addContext(context);
context.addReturnFlow(this);
return false;
}
@Override
public String getText() {
return "return "+getExpression().getText()+".";
}
public static ReturnFlow parse(KerboScriptReturnStmt returnStmt) throws SyntaxException {
return new ReturnFlow(Expression.parse(returnStmt.getExpr()));
}
}
| 1,282 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
ExpressionFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/ExpressionFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.expressions.Constant;
import ksp.kos.ideaplugin.expressions.Expression;
import ksp.kos.ideaplugin.expressions.ExpressionVisitor;
import ksp.kos.ideaplugin.expressions.Number;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
/**
* Created on 12/03/16.
*
* @author ptasha
*/
public abstract class ExpressionFlow<F extends ExpressionFlow<F>> extends BaseFlow<F> {
private Expression expression;
public ExpressionFlow(Expression expression) {
this.expression = expression;
}
public Expression getExpression() {
return expression;
}
@SuppressWarnings("unchecked")
@Override
public boolean addContext(ContextBuilder context) {
HashMap<String, Expression> inline = new HashMap<>();
for (String name : expression.getVariableNames()) {
Dependency flow = context.getFlow(name);
if (flow != null) {
// TODO inline simple functions
// TODO add ability to add user function to inline (InlineFunctions)
// TODO add function to inline automatically
if (flow instanceof VariableFlow && ((VariableFlow) flow).isSimple()) {
inline.put(name, ((VariableFlow) flow).getExpression());
}
} else if (name.endsWith("_")) {
inline.put(name, Number.ZERO);
}
}
if (!inline.isEmpty()) {
expression = expression.inline(inline);
}
for (String name : expression.getVariableNames()) {
Dependency flow = context.getFlow(name);
if (flow != null) {
flow.addDependee(this);
}
}
return true;
}
public boolean isSimple() {
return isSimple(expression);
}
public static boolean isSimple(Expression expression) {
return expression.equals(Number.ZERO) ||
expression.equals(Number.ONE);
}
@Override
public F differentiate(LocalContext context) {
return create(expression.differentiate(context));
}
@NotNull
protected abstract F create(Expression diff);
@Override
public void accept(ExpressionVisitor visitor) {
getExpression().accept(visitor);
}
}
| 2,399 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
Flow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/Flow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.expressions.ExpressionVisitor;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import java.util.Set;
/**
* Created on 12/03/16.
*
* @author ptasha
*/
public interface Flow<F extends Flow<F>> extends Dependency {
F differentiate(LocalContext context, ContextBuilder contextBuilder);
F differentiate(LocalContext context);
String getText();
boolean addContext(ContextBuilder context);
void accept(ExpressionVisitor visitor);
void removeDependee(Flow<?> flow);
Set<Flow<?>> getDependees();
boolean hasDependees();
default boolean isDependee(Flow<?> flow) {
if (getDependees().contains(flow)) {
return true;
}
for (Flow<?> dependee : getDependees()) {
if (dependee.isDependee(flow)) {
return true;
}
}
return false;
}
}
| 936 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
FlowParser.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/FlowParser.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.KerboScriptFile;
import ksp.kos.ideaplugin.expressions.SyntaxException;
import ksp.kos.ideaplugin.psi.KerboScriptDeclareFunctionClause;
import ksp.kos.ideaplugin.psi.KerboScriptNamedElement;
import java.util.function.Function;
/**
* Created on 23/10/16.
*
* @author ptasha
*/
public class FlowParser implements Function<KerboScriptNamedElement, ReferenceFlow<?>> {
public static final FlowParser INSTANCE = new FlowParser();
@Override
public ReferenceFlow<?> apply(KerboScriptNamedElement psi) {
if (psi instanceof KerboScriptDeclareFunctionClause) {
try {
return FunctionFlow.parse((KerboScriptDeclareFunctionClause) psi);
} catch (SyntaxException e) {
e.printStackTrace(); // TODO
}
} else if (psi instanceof KerboScriptFile) {
return ((KerboScriptFile) psi).getCachedScope();
}
return null;
}
}
| 997 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
NamedFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/NamedFlow.java | package ksp.kos.ideaplugin.dataflow;
import java.util.Objects;
/**
* Created on 18/03/16.
*
* @author ptasha
*/
public interface NamedFlow<F extends NamedFlow<F>> extends Flow<F> {
String getName();
}
| 211 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
Dependency.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/Dependency.java | package ksp.kos.ideaplugin.dataflow;
/**
* Created on 30/08/16.
*
* @author ptasha
*/
public interface Dependency {
void addDependee(Flow<?> flow);
}
| 159 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
VariableFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/VariableFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.expressions.Expression;
import ksp.kos.ideaplugin.expressions.SyntaxException;
import ksp.kos.ideaplugin.psi.*;
import ksp.kos.ideaplugin.reference.ReferableType;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import org.jetbrains.annotations.NotNull;
/**
* Created on 12/03/16.
*
* @author ptasha
*/
public class VariableFlow extends ExpressionFlow<VariableFlow> implements NamedFlow<VariableFlow> {
private final boolean declare;
private final String name;
public VariableFlow(boolean declare, String name, Expression expression) {
super(expression);
this.declare = declare;
this.name = name;
}
@Override
public VariableFlow differentiate(LocalContext context, ContextBuilder contextBuilder) {
contextBuilder.add(new VariableFlow(declare, name, getExpression()));
VariableFlow diff = differentiate(context);
contextBuilder.add(diff);
return diff;
}
@Override
public boolean addContext(ContextBuilder context) {
super.addContext(context);
if (!declare || context.getFlow(name) == null) {
context.getMap().put(getName(), this);
}
return true;
}
@NotNull
@Override
protected VariableFlow create(Expression diff) {
return new VariableFlow(declare, name+"_", diff);
}
@Override
public String getName() {
return name;
}
@Override
public String getText() {
String text = "";
text+=declare?"local ":"set ";
text+=name;
text+=" to "+getExpression().getText()+".";
return text;
}
public static VariableFlow parse(KerboScriptDeclareIdentifierClause declareIdentifierClause) throws SyntaxException {
return new VariableFlow(true, declareIdentifierClause.getName(), Expression.parse(declareIdentifierClause.getExpr()));
}
public static VariableFlow parse(KerboScriptSetStmt setStmt) throws SyntaxException {
KerboScriptExpr nameExpr = setStmt.getVaridentifierList().get(0).downTill(KerboScriptExpr.class);
if (nameExpr instanceof KerboScriptSuffixterm) {
KerboScriptAtom atom = ((KerboScriptSuffixterm) nameExpr).getAtom();
if (atom.getReferableType() == ReferableType.VARIABLE) {
String name = atom.getName();
return new VariableFlow(false, name, Expression.parse(setStmt.getExpr()));
}
}
return null;
}
}
| 2,544 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
ReferenceFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/ReferenceFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.reference.Reference;
/**
* Created on 05/10/16.
*
* @author ptasha
*/
public interface ReferenceFlow<F> extends Reference { //TODO remove me
}
| 212 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
IfFlow.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/IfFlow.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.expressions.Expression;
import ksp.kos.ideaplugin.expressions.SyntaxException;
import ksp.kos.ideaplugin.psi.*;
import ksp.kos.ideaplugin.reference.context.LocalContext;
import java.util.List;
import java.util.Set;
/**
* Created on 14/08/16.
*
* @author ptasha
*/
public class IfFlow extends BaseFlow<IfFlow> {
private final KerboScriptExpr expr;
private final ContextBuilder trueList;
private final ContextBuilder falseList;
public IfFlow(KerboScriptExpr expr, ContextBuilder trueList, ContextBuilder falseList) {
this.expr = expr;
this.trueList = trueList;
this.falseList = falseList;
}
public static IfFlow parse(KerboScriptIfStmt ifStmt, ContextBuilder parent) throws SyntaxException {
KerboScriptExpr expr = ifStmt.getExpr();
List<KerboScriptInstruction> list = ifStmt.getInstructionList();
ContextBuilder trueList = parseBlock(list.get(0), parent);
ContextBuilder falseList;
if (list.size()>1) {
falseList = parseBlock(list.get(1), parent);
} else {
falseList = new ContextBuilder();
}
return new IfFlow(expr, trueList, falseList);
}
@Override
public boolean addContext(ContextBuilder context) {
addExpressionContext(expr, context);
trueList.setParent(context);
boolean trueCont = trueList.buildMap();
falseList.setParent(context);
boolean falseCont = falseList.buildMap();
// TODO merge contexts
context.addReturnFlow(trueList.getReturn());
context.addReturnFlow(falseList.getReturn());
if (!trueList.getReturn().isEmpty() || !falseList.getReturn().isEmpty()) {
context.addReturnFlow(this);
}
return trueCont || falseCont;
}
private void addExpressionContext(KerboScriptExpr expr, ContextBuilder context) {
// TODO add them to Expression
if (expr instanceof KerboScriptOrExpr) {
addExpressionsContext(((KerboScriptOrExpr) expr).getExprList(), context);
} else if (expr instanceof KerboScriptAndExpr) {
addExpressionsContext(((KerboScriptAndExpr) expr).getExprList(), context);
} else {
try {
Set<String> names = Expression.parse(expr).getVariableNames();
for (String name : names) {
Dependency flow = context.getFlow(name);
if (flow != null) {
flow.addDependee(this);
}
}
} catch (SyntaxException e) {
e.printStackTrace(); // TODO it should be already parsed thus no exception here
}
}
}
private void addExpressionsContext(List<KerboScriptExpr> list, ContextBuilder context) {
for (KerboScriptExpr kerboScriptExpr : list) {
addExpressionContext(kerboScriptExpr, context);
}
}
private static ContextBuilder parseBlock(KerboScriptInstruction kerboScriptInstruction, ContextBuilder parent) throws SyntaxException {
InstructionsParser parser = new InstructionsParser(parent);
parser.parseInstruction(kerboScriptInstruction);
return parser.getContext();
}
@Override
public IfFlow differentiate(LocalContext context, ContextBuilder contextBuilder) {
IfFlow diff = differentiate(context);
contextBuilder.add(diff);
return diff;
}
@Override
public IfFlow differentiate(LocalContext context) {
ContextBuilder trueContext = new ContextBuilder();
trueList.differentiate(context, trueContext);
ContextBuilder falseContext = new ContextBuilder();
falseList.differentiate(context, falseContext);
// TODO simplify
return new IfFlow(expr, trueContext, falseContext);
}
@Override
public String getText() {
String text = "";
text += "if " + expr.getText() + " " + print(trueList);
if (!falseList.getList().isEmpty()) {
text += "\n else " + print(falseList);
}
return text;
}
private String print(ContextBuilder context) {
//if (context.getList().size()==1) return context.getText();
return "{\n" + context.getText() + "\n}";
}
}
| 4,361 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
MixedDependency.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/MixedDependency.java | package ksp.kos.ideaplugin.dataflow;
import java.util.ArrayList;
/**
* Created on 30/08/16.
*
* @author ptasha
*/
public class MixedDependency implements Dependency {
private final ArrayList<Dependency> dependencies = new ArrayList<>();
public MixedDependency() {
}
public void addDependency(Dependency dependency) {
dependencies.add(dependency);
}
@Override
public void addDependee(Flow<?> flow) {
for (Dependency dependency : dependencies) {
dependency.addDependee(flow);
}
}
public boolean isEmpty() {
return dependencies.isEmpty();
}
public ReturnFlow getReturnFlow() {
if (dependencies.size()==1) {
Dependency dependency = dependencies.get(0);
if (dependency instanceof ReturnFlow) {
return (ReturnFlow) dependency;
}
}
return null;
}
}
| 921 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
InstructionsParser.java | /FileExtraction/Java_unseen/KSP-KOS_EditorTools/IDEA/src/main/java/ksp/kos/ideaplugin/dataflow/InstructionsParser.java | package ksp.kos.ideaplugin.dataflow;
import ksp.kos.ideaplugin.expressions.SyntaxException;
import ksp.kos.ideaplugin.psi.*;
import java.util.List;
/**
* Created on 27/08/16.
*
* @author ptasha
*/
public class InstructionsParser {
private final ContextBuilder context;
public InstructionsParser() {
this(null);
}
public InstructionsParser(ContextBuilder parent) {
context = new ContextBuilder(parent);
}
public boolean parseInstructions(List<KerboScriptInstruction> instructions) throws SyntaxException {
for (KerboScriptInstruction instruction : instructions) {
if (!parseInstruction(instruction)) return false;
}
return true;
}
public boolean parseInstruction(KerboScriptInstruction instruction) throws SyntaxException {
if (instruction instanceof KerboScriptSetStmt) {
VariableFlow variableFlow = VariableFlow.parse((KerboScriptSetStmt) instruction);
if (variableFlow != null) {
addFlow(variableFlow);
}
} else if (instruction instanceof KerboScriptDeclareStmt) {
KerboScriptDeclareStmt declareStmt = (KerboScriptDeclareStmt) instruction;
KerboScriptDeclareParameterClause declareParameterClause = declareStmt.getDeclareParameterClause();
if (declareParameterClause != null) {
addFlow(ParameterFlow.parse(declareParameterClause));
} else if (declareStmt.getDeclareIdentifierClause() != null) {
addFlow(VariableFlow.parse(declareStmt.getDeclareIdentifierClause()));
}
} else if (instruction instanceof KerboScriptReturnStmt) {
addFlow(ReturnFlow.parse((KerboScriptReturnStmt) instruction));
return false;
} else if (instruction instanceof KerboScriptIfStmt) {
KerboScriptIfStmt ifStmt = (KerboScriptIfStmt) instruction;
addFlow(IfFlow.parse(ifStmt, context));
} else if (instruction.getInstructionBlock()!=null) {
KerboScriptInstructionBlock instructionBlock = instruction.getInstructionBlock();
return parseInstructions(instructionBlock.getInstructionList());
}
// TODO throw exception on unknown instructions?
return true;
}
protected void addFlow(Flow<?> flow) {
context.add(flow);
}
public ContextBuilder getContext() {
return context;
}
}
| 2,459 | Java | .java | KSP-KOS/EditorTools | 51 | 42 | 2 | 2015-04-13T18:45:12Z | 2023-06-09T09:20:51Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.