blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34 values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2 values | text stringlengths 9 3.8M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
5b88b39f1e062dbdd4c6c06a43a52340b60c92f7 | Java | chaitu16/jUnit_DataDriven | /src/testcases/RegistrationTest.java | UTF-8 | 2,804 | 2.0625 | 2 | [] | no_license | package testcases;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import Util.TestUtil;
import datatable.Xls_Reader;
import testbase.ExtentManager;
import testbase.TestBase;
@RunWith(Parameterized.class)
public class RegistrationTest extends TestBase{
public String email;
public String username;
public String phone;
public String password;
public RegistrationTest(String email , String username, String phone, String password) {
this.email =email;
this.username = username;
this.phone= phone;
this.password = password;
}
@Before
public void beforeTest() {
launchBrowser("firefox");
if(TestUtil.isSkip("RegistrationTest")) {
Assume.assumeTrue(false);
}
}
@Test
public void registerTest() throws InterruptedException {
// launchBrowser("firefox");
driver.get(CONFIG.getProperty("url"));
// waitForPageToLoad();
Thread.sleep(3000);
getObject("login_register_xpath").click();
// getObject("email_mobile_xpath").sendKeys(CONFIG.getProperty("user_email"));
// getObject("email_mobile_xpath").sendKeys("Abchello@world.com");
Thread.sleep(3000);
getObject("email_mobile_xpath").sendKeys(email);
getObject("continue_btn_xpath").click();
// getObject("reg_name_css").sendKeys("AbcMan");
getObject("reg_name_css").sendKeys(username);
// getObject("reg_mobileNum_css").sendKeys("9998889898");
getObject("reg_mobileNum_css").sendKeys(phone);
// getObject("reg_password_xpath").sendKeys(CONFIG.getProperty(encryptDecrypt("user_password")));
// getObject("reg_chkbx_xpath").click();
// getObject("reg_password_xpath").sendKeys("AbcAbcAbc123");
getObject("reg_password_xpath").sendKeys(password);
getObject("reg_cntinuebtn_xpath").click();
Thread.sleep(5000);
}
@Parameters
public static Collection<Object[]> readData(){
// datatable = new Xls_Reader(System.getProperty("user.dir")+"\\src\\config\\Suite1.xlsx");
Object [][] data = TestUtil.getData("RegistrationTest");
/* Object[][] para = new Object[2][4];
//1st row
para[0][0] = "sub3@suba.com";
para[0][1] = "helloOne12";
para[0][2] = "9345065988";
para[0][3] = "pass12345";
//2nd row
para[1][0] = "sub4@suba.com";
para[1][1] = "helloTwo32";
para[1][2] = "9534465977";
para[1][3] = "pass123456";
*/
return Arrays.asList(data);
}
}
| true |
28ec2835c6002c88137f7bef9f722f951d899298 | Java | Bing-Max/AlgorithmPractice | /src/structure/stack/ArrayStack.java | UTF-8 | 909 | 3.859375 | 4 | [] | no_license | package structure.stack;
public class ArrayStack {
private int maxSize;
private int[] vals;
private int top;
public ArrayStack() {
// TODO Auto-generated constructor stub
}
public ArrayStack(int maxSize) {
super();
this.maxSize = maxSize;
this.vals = new int[maxSize];
this.top = -1;
}
public boolean isEmpty() {
return this.top == -1;
}
public boolean isFull() {
return this.top == maxSize - 1;
}
public void push(int val) {
if(!isFull()) {
this.vals[++top] = val;
}else {
throw new RuntimeException("stack is already full!");
}
}
public int pop() {
if(isEmpty()) {
throw new RuntimeException("stack is empty!");
}
return this.vals[top--];
}
public void show() {
if(isEmpty()) {
System.out.println("Empty stack");
return;
}
for(int i = top ; i >= 0; i--) {
System.out.printf("index[%d]: %d\n", i, vals[i]);
}
}
}
| true |
5d762ad7239b16aa679c2fd844e3e670215e8356 | Java | JunGitHong/JavaDesignPattern | /src/jhz/pattern/mediator/ColleagueA.java | GB18030 | 432 | 2.59375 | 3 | [] | no_license | package jhz.pattern.mediator;
/**
* ͬA
* @author zhj
* @version 1.0.0
* @date 2018413 4:19:12
*/
public class ColleagueA extends AbstractColleague {
// @Override
// public void setNumber(int number, AbstractColleague coll) {
// this.number = number;
// coll.setNumber(number*100);
// }
@Override
public void setNumber(int number, AbstractMediator md) {
this.number = number;
md.AaffectB();
}
}
| true |
66120fbd0c4c554da8ff1bbe09b544054c7dc52c | Java | javiergerard1986/MercadoLibre | /src/test/java/com/javier/tutorials/pages/BasePage.java | UTF-8 | 1,363 | 2.625 | 3 | [] | no_license | package com.javier.tutorials.pages;
import java.io.InputStream;
import java.util.Properties;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public abstract class BasePage {
//-----------------------------------
//ATTRIBUTES
//-----------------------------------
protected WebDriver driver;
protected InputStream confFile = null;
protected Properties properties = new Properties();
//-----------------------------------
//CONTRUCTORS
//-----------------------------------
public BasePage (WebDriver driver){
this.driver = driver;
}
//-----------------------------------
//VOID AND FUNCTIONS
//-----------------------------------
/**
* Method to verify if element is present
* @param element (WebElement) this is the webElement to check if is present
* @return boolean - If element is present it will return true, if not, false
* @author Javier_Gerard
*/
protected boolean isElementPresent(WebElement element) {
try{
WebDriverWait wait = new WebDriverWait(driver, 5000);
wait.until(ExpectedConditions.visibilityOf(element));
return true;
}catch(TimeoutException ex){
return false;
}
}
} | true |
60cf8ab621262d4de64e2157b86de3fe16bc57ab | Java | MostafaOmar98/virtual-file-system-simulator | /src/PersistenceManager/FileManager.java | UTF-8 | 199 | 2.078125 | 2 | [] | no_license | package PersistenceManager;
import MainPack.VirtualFileSystem;
public interface FileManager
{
public void save();
public void load();
public VirtualFileSystem getVirtualFileSystem();
}
| true |
f4700d0755158b1d3b6c0da55b5a33bdfe680715 | Java | MrYuguangbao/spring-springmvc | /src/main/java/com/springtest/aop/xml/XmlAspectMainTest.java | UTF-8 | 965 | 2.296875 | 2 | [] | no_license | package com.springtest.aop.xml;
import com.springtest.RoleVO;
import com.springtest.aop.aop2.AOP验证器;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author admin
* @date 2020/1/7 14:55
*/
public class XmlAspectMainTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(XmlConfig.class);
RoleService roleService = context.getBean(RoleService.class);
AOP验证器 aop = (AOP验证器) roleService;
RoleVO roleVO = new RoleVO();
roleVO.setId(1L);
roleVO.setName("testname");
roleVO.setNote("testnote");
if (aop.verify(null)) {
System.out.println("实体对象为空");
} else {
System.out.println("实体对象不为空");
roleService.print(roleVO);
}
context.close();
}
}
| true |
83969a571bb3e5180e419f39fca208b159270275 | Java | luume/potoview | /src/main/java/com/kr/pv/dao/SelectDao.java | UTF-8 | 279 | 1.765625 | 2 | [] | no_license | package com.kr.pv.dao;
import java.util.List;
import java.util.Map;
import com.kr.pv.vo.BoardFileJoinVO;
public interface SelectDao {
public BoardFileJoinVO selectByIdx(int idx);
public List<BoardFileJoinVO> selectList(Map<String, Integer> map);
public int totalCount();
}
| true |
02a8f133f562d64cf70ddf8fb952b285165abc26 | Java | duyme18/Backend_Project-Library-5-11-2019 | /src/main/java/com/codegym/model/Book.java | UTF-8 | 1,274 | 2.46875 | 2 | [] | no_license | package com.codegym.model;
import javax.persistence.*;
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Book(String title, String authors, Category category, Status status) {
this.title = title;
this.authors = authors;
this.category = category;
this.status = status;
}
private String title;
private String authors;
public Book() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@ManyToOne
private Category category;
@ManyToOne
private Status status;
}
| true |
e5c24bdf21f27d56448568eba2fca08d16cc4af0 | Java | younghkb/CS121 | /java/workspace/Goodreads/src/BookParserTest.java | UTF-8 | 1,120 | 2.859375 | 3 | [] | no_license | import static org.junit.Assert.*;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class BookParserTest {
QueryBuilder builder;
BookParser parser;
@Before
public void setUp() {
builder = new QueryBuilder();
parser = new BookParser();
}
@Test
public void testISBNQuery() {
try {
String query = QueryBuilder.makeURLfromISBN("0544272994");
System.out.println(query);
List<Book> booksFound = BookParser.parseQuery(query);
assertEquals(1, booksFound.size());
Book book = booksFound.get(0);
//assertEquals(book.isbn, "0544272994"); Not implemented yet.
assertEquals("21413662", book.id);
assertEquals("What If?: Serious Scientific Answers to Absurd Hypothetical Questions", book.title);
assertEquals("Randall Munroe", book.author);
assertEquals("https://d.gr-assets.com/books/1394648139m/21413662.jpg", book.imageUrl);
assertEquals("https://d.gr-assets.com/books/1394648139s/21413662.jpg", book.smallImageUrl);
} catch (Exception e) {
fail("Query failed with exception " + e.toString());
e.printStackTrace();
}
}
}
| true |
c4c6b96990e97e46a580e9fe60bff6a896507ef8 | Java | imathresearch/iMathCloud_BBVA | /src/test/java/com/imath/core/model/JobTest.java | UTF-8 | 3,317 | 2.328125 | 2 | [] | no_license | /* (C) 2013 iMath Research S.L. - All rights reserved. */
package com.imath.core.model;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.imath.core.model.Job.States;
public class JobTest {
private Job job;
private String desc = "DESCRTIPTION";
private Date endDate = new Date(1000);
private Date startDate = new Date(1001);
private File file1 = new File();
private File file2 = new File();
private Set<File> files = new HashSet<File>();
private Set<File> filesSource = new HashSet<File>();
private Set<File> filesOutput = new HashSet<File>();
private Session session = new Session();
private IMR_User owner = new IMR_User();
private Host hosted = new Host();
private JobResult jobResult = new JobResult();
@Before
public void setUp() throws Exception {
job = new Job();
job.setDescription(desc);
job.setEndDate(endDate);
job.setStartDate(startDate);
files.add(file1);
files.add(file2);
job.setFiles(files);
filesSource.add(file1);
filesSource.add(file2);
job.setSourceFiles(filesSource);
filesOutput.add(file1);
filesOutput.add(file2);
job.setOutputFiles(filesOutput);
job.setSession(session);
job.setOwner(owner);
job.setHosted(hosted);
job.setJobResult(jobResult);
job.setState(States.CREATED);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testGetOwner() {
assertTrue(job.getOwner() == owner);
}
@Test
public void testGetHosted() {
assertTrue(job.getHosted()== hosted);
}
@Test
public void testGetStartDate() {
assertTrue(job.getStartDate()== startDate);
assertTrue(job.getStartDate().getTime()== startDate.getTime());
}
@Test
public void testGetEndDate() {
assertTrue(job.getEndDate()== endDate);
assertTrue(job.getEndDate().getTime()== endDate.getTime());
}
@Test
public void testGetSession() {
assertTrue(job.getSession()==session);
}
@Test
public void testGetDescription() {
assertTrue(job.getDescription()==desc);
assertTrue(job.getDescription().equals(desc));
}
@Test
public void testGetFiles() {
assertTrue(job.getFiles()==files);
assertTrue(job.getFiles().size()==2);
Iterator<File> it = job.getFiles().iterator();
File a1 = it.next();
File a2 = it.next();
assertTrue(a1==file1 || a1 == file2);
assertTrue(a2==file1 || a2 == file2);
}
@Test
public void testGetOutputFiles() {
assertTrue(job.getOutputFiles()==filesOutput);
assertTrue(job.getOutputFiles().size()==2);
Iterator<File> it = job.getOutputFiles().iterator();
File a1 = it.next();
File a2 = it.next();
assertTrue(a1==file1 || a1 == file2);
assertTrue(a2==file1 || a2 == file2);
}
@Test
public void testGetSourceFiles() {
assertTrue(job.getSourceFiles()==filesSource);
assertTrue(job.getSourceFiles().size()==2);
Iterator<File> it = job.getSourceFiles().iterator();
File a1 = it.next();
File a2 = it.next();
assertTrue(a1==file1 || a1 == file2);
assertTrue(a2==file1 || a2 == file2);
}
@Test
public void testGetState() {
assertTrue(job.getState()==States.CREATED);
}
@Test
public void testGetJobResult() {
assertTrue(job.getJobResult()==jobResult);
}
}
| true |
b1cbd2a99e8138b2077cd5b14fd5591ef31c3afc | Java | guanyibei1204/iLMS | /iLMS_PEC/src/com/hanthink/dpm/model/DpmDepPersonModel.java | UTF-8 | 3,124 | 1.929688 | 2 | [] | no_license | package com.hanthink.dpm.model;
import com.hotent.base.core.model.AbstractModel;
/**
*
* <pre>
* Description:
* Company: HanThink
* Date: 2018年9月14日 上午10:36:18
* </pre>
* @author luoxq
*/
public class DpmDepPersonModel extends AbstractModel<String>{
/**
*
*/
private static final long serialVersionUID = 6806900589581227241L;
/**逻辑主键**/
private String id;
/**工厂**/
private String factoryCode;
/**人员id**/
private String userId;
/**用户名**/
private String account;
/**姓名**/
private String fullname;
/**部门**/
private String name;
/**责任组**/
private String depCode;
/**责任组名称**/
private String depName;
/**部门审核人**/
private String depChecker;
/**所属科室**/
private String belongDep;
/**默认发现区域**/
private String defaultDiscoArea;
/**创建人**/
private String creationUser;
/**修改人**/
private String lastModifiedUser;
/**账号--名称(部门)**/
private String accountName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepCode() {
return depCode;
}
public void setDepCode(String depCode) {
this.depCode = depCode;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getBelongDep() {
return belongDep;
}
public void setBelongDep(String belongDep) {
this.belongDep = belongDep;
}
public String getDefaultDiscoArea() {
return defaultDiscoArea;
}
public void setDefaultDiscoArea(String defaultDiscoArea) {
this.defaultDiscoArea = defaultDiscoArea;
}
public String getDepName() {
return depName;
}
public void setDepName(String depName) {
this.depName = depName;
}
public String getDepChecker() {
return depChecker;
}
public void setDepChecker(String depChecker) {
this.depChecker = depChecker;
}
public String getCreationUser() {
return creationUser;
}
public void setCreationUser(String creationUser) {
this.creationUser = creationUser;
}
public String getLastModifiedUser() {
return lastModifiedUser;
}
public void setLastModifiedUser(String lastModifiedUser) {
this.lastModifiedUser = lastModifiedUser;
}
public String getFactoryCode() {
return factoryCode;
}
public void setFactoryCode(String factoryCode) {
this.factoryCode = factoryCode;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
}
| true |
48777fc9ea8e22c9c4b30e3a03dc980f67ac6f84 | Java | dklenke/java-schule | /ÜbungenDrittesLehrjahr/src/ruhl/fluege/Flugzeug.java | MacCentralEurope | 1,106 | 3.328125 | 3 | [] | no_license | package ruhl.fluege;
public class Flugzeug {
private String typ;
private int anzahlPlaetze;
public Platz[] passagierListe;
public Flugzeug(String typ, int anzahlPlaetze) {
this.typ = typ;
this.anzahlPlaetze = anzahlPlaetze;
this.passagierListe = new Platz[anzahlPlaetze];
for (int i = 0; i<this.passagierListe.length; i++) {
this.passagierListe[i] = new Platz(i + 1);
}
}
public String getTyp() {
return this.typ;
}
public boolean hinzufuegen(Passagier passagier) {
for (Platz p : this.passagierListe) {
if(p.getPassagier() == null) {
p.setPassagier(passagier);
return true;
}
}
return false;
}
public String getPassagiere() {
String out = "";
int belegtePlaetze = 0;
for (Platz p : this.passagierListe) {
if (p.getPassagier() != null) {
out += "Platznummer " + p.getNummer() + " sitzt " + p.getPassagier().getName() + ".\n";
belegtePlaetze++;
}
}
String verb = belegtePlaetze == 1 ? "ist " : "sind ";
out = "Es " + verb + belegtePlaetze + " von " + this.anzahlPlaetze + " Pltzen belegt.\n" + out;
return out;
}
}
| true |
97878754d8b683254bdcdf1d40a9ebdb05df463c | Java | tpltnt/binnavi | /src/main/java/com/google/security/zynamics/binnavi/Gui/GraphWindows/CommentDialogs/FunctionComments/CGlobalFunctionCommentAccessor.java | UTF-8 | 3,054 | 2.3125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
Copyright 2011-2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.FunctionComments;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntDeleteException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.Interfaces.IComment;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.Interfaces.ICommentAccessor;
import com.google.security.zynamics.binnavi.disassembly.INaviFunction;
/**
* Implements the comment accessor functionality for global function comments.
*
* @author timkornau
*
*/
public class CGlobalFunctionCommentAccessor implements ICommentAccessor {
private final INaviFunction m_function;
/**
* Generates a new {@link CGlobalFunctionCommentAccessor} object.
*
* @param function The function to access comments on.
*/
public CGlobalFunctionCommentAccessor(final INaviFunction function) {
m_function = Preconditions.checkNotNull(function, "IE02665: function argument can not be null");
}
@Override
public List<IComment> appendComment(final String commentText) throws CouldntSaveDataException,
CouldntLoadDataException {
Preconditions.checkNotNull(commentText, "IE02666: commentText argument can not be null");
return m_function.appendGlobalComment(commentText);
}
@Override
public void deleteComment(final IComment comment) throws CouldntDeleteException {
Preconditions.checkNotNull(comment, "IE02667: commentId argument can not be null");
m_function.deleteGlobalComment(comment);
}
@Override
public IComment editComment(final IComment commentId, final String newComment)
throws CouldntSaveDataException {
Preconditions.checkNotNull(commentId, "IE02668: commentId argument can not be null");
Preconditions.checkNotNull(newComment, "IE02669: newComment argument can not be null");
return m_function.editGlobalComment(commentId, newComment);
}
@Override
public List<IComment> getComment() {
return m_function.getGlobalComment();
}
@Override
public boolean isOwner(final IComment comment) {
Preconditions.checkNotNull(comment, "IE02670: comment argument can not be null");
return m_function.isOwner(comment);
}
}
| true |
cee034441cf4d6c6b141b00c4e243c78b9abd829 | Java | aws/aws-sdk-java | /aws-java-sdk-resiliencehub/src/main/java/com/amazonaws/services/resiliencehub/model/EventSubscription.java | UTF-8 | 12,727 | 1.851563 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.resiliencehub.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Indicates an event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> and <b>Scheduled assessment failure</b> events.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/resiliencehub-2020-04-30/EventSubscription" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EventSubscription implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment failure</b>
* (<code>ScheduledAssessmentFailure</code>) events.
* </p>
*/
private String eventType;
/**
* <p>
* Unique name to identify an event subscription.
* </p>
*/
private String name;
/**
* <p>
* Amazon Resource Name (ARN) of the Amazon Simple Notification Service topic. The format for this ARN is: arn:
* <code>partition</code>:resiliencehub:<code>region</code>:<code>account</code>:app/<code>app-id</code>. For more
* information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">
* Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i> guide.
* </p>
*/
private String snsTopicArn;
/**
* <p>
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment failure</b>
* (<code>ScheduledAssessmentFailure</code>) events.
* </p>
*
* @param eventType
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment
* failure</b> (<code>ScheduledAssessmentFailure</code>) events.
* @see EventType
*/
public void setEventType(String eventType) {
this.eventType = eventType;
}
/**
* <p>
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment failure</b>
* (<code>ScheduledAssessmentFailure</code>) events.
* </p>
*
* @return The type of event you would like to subscribe and get notification for. Currently, Resilience Hub
* supports notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled
* assessment failure</b> (<code>ScheduledAssessmentFailure</code>) events.
* @see EventType
*/
public String getEventType() {
return this.eventType;
}
/**
* <p>
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment failure</b>
* (<code>ScheduledAssessmentFailure</code>) events.
* </p>
*
* @param eventType
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment
* failure</b> (<code>ScheduledAssessmentFailure</code>) events.
* @return Returns a reference to this object so that method calls can be chained together.
* @see EventType
*/
public EventSubscription withEventType(String eventType) {
setEventType(eventType);
return this;
}
/**
* <p>
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment failure</b>
* (<code>ScheduledAssessmentFailure</code>) events.
* </p>
*
* @param eventType
* The type of event you would like to subscribe and get notification for. Currently, Resilience Hub supports
* notifications only for <b>Drift detected</b> (<code>DriftDetected</code>) and <b>Scheduled assessment
* failure</b> (<code>ScheduledAssessmentFailure</code>) events.
* @return Returns a reference to this object so that method calls can be chained together.
* @see EventType
*/
public EventSubscription withEventType(EventType eventType) {
this.eventType = eventType.toString();
return this;
}
/**
* <p>
* Unique name to identify an event subscription.
* </p>
*
* @param name
* Unique name to identify an event subscription.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* Unique name to identify an event subscription.
* </p>
*
* @return Unique name to identify an event subscription.
*/
public String getName() {
return this.name;
}
/**
* <p>
* Unique name to identify an event subscription.
* </p>
*
* @param name
* Unique name to identify an event subscription.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public EventSubscription withName(String name) {
setName(name);
return this;
}
/**
* <p>
* Amazon Resource Name (ARN) of the Amazon Simple Notification Service topic. The format for this ARN is: arn:
* <code>partition</code>:resiliencehub:<code>region</code>:<code>account</code>:app/<code>app-id</code>. For more
* information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">
* Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i> guide.
* </p>
*
* @param snsTopicArn
* Amazon Resource Name (ARN) of the Amazon Simple Notification Service topic. The format for this ARN is:
* arn:<code>partition</code>:resiliencehub:<code>region</code>:<code>account</code>:app/<code>app-id</code>.
* For more information about ARNs, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html"> Amazon Resource Names
* (ARNs)</a> in the <i>AWS General Reference</i> guide.
*/
public void setSnsTopicArn(String snsTopicArn) {
this.snsTopicArn = snsTopicArn;
}
/**
* <p>
* Amazon Resource Name (ARN) of the Amazon Simple Notification Service topic. The format for this ARN is: arn:
* <code>partition</code>:resiliencehub:<code>region</code>:<code>account</code>:app/<code>app-id</code>. For more
* information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">
* Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i> guide.
* </p>
*
* @return Amazon Resource Name (ARN) of the Amazon Simple Notification Service topic. The format for this ARN is:
* arn:<code>partition</code>:resiliencehub:<code>region</code>:<code>account</code>:app/<code>app-id</code>
* . For more information about ARNs, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html"> Amazon Resource Names
* (ARNs)</a> in the <i>AWS General Reference</i> guide.
*/
public String getSnsTopicArn() {
return this.snsTopicArn;
}
/**
* <p>
* Amazon Resource Name (ARN) of the Amazon Simple Notification Service topic. The format for this ARN is: arn:
* <code>partition</code>:resiliencehub:<code>region</code>:<code>account</code>:app/<code>app-id</code>. For more
* information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">
* Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i> guide.
* </p>
*
* @param snsTopicArn
* Amazon Resource Name (ARN) of the Amazon Simple Notification Service topic. The format for this ARN is:
* arn:<code>partition</code>:resiliencehub:<code>region</code>:<code>account</code>:app/<code>app-id</code>.
* For more information about ARNs, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html"> Amazon Resource Names
* (ARNs)</a> in the <i>AWS General Reference</i> guide.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public EventSubscription withSnsTopicArn(String snsTopicArn) {
setSnsTopicArn(snsTopicArn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEventType() != null)
sb.append("EventType: ").append(getEventType()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getSnsTopicArn() != null)
sb.append("SnsTopicArn: ").append(getSnsTopicArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof EventSubscription == false)
return false;
EventSubscription other = (EventSubscription) obj;
if (other.getEventType() == null ^ this.getEventType() == null)
return false;
if (other.getEventType() != null && other.getEventType().equals(this.getEventType()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getSnsTopicArn() == null ^ this.getSnsTopicArn() == null)
return false;
if (other.getSnsTopicArn() != null && other.getSnsTopicArn().equals(this.getSnsTopicArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEventType() == null) ? 0 : getEventType().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getSnsTopicArn() == null) ? 0 : getSnsTopicArn().hashCode());
return hashCode;
}
@Override
public EventSubscription clone() {
try {
return (EventSubscription) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.resiliencehub.model.transform.EventSubscriptionMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| true |
8c03ee4359039b0a56553ffe41dad8d25062a14e | Java | TrueSide1005/PA_LAB12_BIBIRE_RALUCA_2A3 | /Lab11/src/main/java/main/GameController.java | UTF-8 | 1,506 | 2.390625 | 2 | [] | no_license | package main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@RestController
@RequestMapping("/games")
public class GameController {
private final List<Games> games=new ArrayList<>();
@Autowired
private GameRepo gameRepo;
@GetMapping
public List<Games> getAllGames() {
List<Games> g= (List<Games>) gameRepo.findAll();
if(g==null)
throw new MyException("Games not found");
return g;
}
@GetMapping("/{id}")
public Games show(@PathVariable("id") Integer id){
return games.stream()
.filter(g->g.getId()==id).findFirst()
.orElseThrow( ()->new MyException("Game not found"));
}
@PostMapping("/games")
public Games create(@RequestBody Map<String, String> body){
String id_castigator = body.get("id_castigator");
Games g = new Games();
g.setIdCastigator(Integer.parseInt(id_castigator));
String id_player1=body.get("id_player1");
g.setIdPlayer1(Integer.parseInt(id_player1));
String id_player2=body.get("id_player2");
g.setIdPlayer2(Integer.parseInt(id_player2));
games.add(g);
return gameRepo.save(g);
}
}
| true |
b68c81a023cb80585621519b2bda0b4304fd2902 | Java | inspire-software/geda-genericdto | /core/src/test/java/com/inspiresoftware/lib/dto/geda/assembler/examples/collections/TestEntity7CollectionClass.java | UTF-8 | 981 | 1.898438 | 2 | [] | no_license |
/*
* This code is distributed under The GNU Lesser General Public License (LGPLv3)
* Please visit GNU site for LGPLv3 http://www.gnu.org/copyleft/lesser.html
*
* Copyright Denis Pavlov 2009
* Web: http://www.genericdtoassembler.org
* SVN: https://svn.code.sf.net/p/geda-genericdto/code/trunk/
* SVN (mirror): http://geda-genericdto.googlecode.com/svn/trunk/
*/
package com.inspiresoftware.lib.dto.geda.assembler.examples.collections;
import org.junit.Ignore;
import java.util.Collection;
/**
* .
*
* User: Denis Pavlov
* Date: Jan 25, 2010
* Time: 1:55:45 PM
*/
@Ignore
public class TestEntity7CollectionClass {
private Collection<TestEntity7CollectionSubClass> collection;
/** {@inheritDoc} */
public Collection<TestEntity7CollectionSubClass> getCollection() {
return collection;
}
/** {@inheritDoc} */
public void setCollection(final Collection<TestEntity7CollectionSubClass> collection) {
this.collection = collection;
}
}
| true |
82f406f5436172ad55e903e05b56b987bc61f72a | Java | Aiushtha/Go-RxJava | /sample-app/src/main/java/rx/android/samples/demo/condition/Fragment_Amb.java | UTF-8 | 1,107 | 2.5 | 2 | [
"Apache-2.0"
] | permissive | package rx.android.samples.demo.condition;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Observer;
import rx.android.samples.demo.BaseFragment;
/**
* Created by Lin on 2016/10/13.
*/
public class Fragment_Amb extends BaseFragment {
public void runCode() {
Observable.amb(
Observable.just(1,2,3).delay(2, TimeUnit.SECONDS),
Observable.just(4,5,6).delay(3, TimeUnit.SECONDS),
Observable.just(7,8,9).delay(1, TimeUnit.SECONDS)
)
.subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
println("-------->onCompleted()");
}
@Override
public void onError(Throwable e) {
println("-------->onError()" + e);
}
@Override
public void onNext(Integer i) {
println("-------->onNext()" + i);
}
});
}
}
| true |
6351113c2b50153bdb6f3cbe5bae6e59320345b7 | Java | WigginsLi/Java_IM | /src/Messager.java | UTF-8 | 405 | 2.671875 | 3 | [] | no_license | // 消息对象
class Messager implements java.io.Serializable{
String fromID,toID, operation, cont, time;
// operation 0:普通消息 ; 1:其他消息(好友申请,是否在线)
Messager(String f, String t, String op, String cont, String time) {
this.fromID = f;
this.toID = t;
this.operation = op;
this.cont = cont;
this.time = time;
}
} | true |
c3c70a2b34baa93da4c0e0c36cdf56965ff21738 | Java | charasril/ITM801-THESIS | /app/src/main/java/com/akexorcist/googledirection/sample/AlternativeDirectionActivity.java | UTF-8 | 13,965 | 1.757813 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | package com.akexorcist.googledirection.sample;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.akexorcist.googledirection.DirectionCallback;
import com.akexorcist.googledirection.GoogleDirection;
import com.akexorcist.googledirection.constant.TransportMode;
import com.akexorcist.googledirection.model.Direction;
import com.akexorcist.googledirection.model.Route;
import com.akexorcist.googledirection.util.DirectionConverter;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import java.util.ArrayList;
public class AlternativeDirectionActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener, DirectionCallback {
private Button btnRequestDirection;
private GoogleMap googleMap;
private String serverKey = "AIzaSyDkxXWseLD9nGDV81y6DgBA1PLbwp5tzwU";
private LatLng camera ;// = new LatLng(35.1773909, 136.9471357);
private LatLng origin ;//= new LatLng(35.1766982, 136.9413508);
private LatLng destination;//= new LatLng(35.1800441, 136.9532567);
private String[] colors = {"#7fff7272", "#7f31c7c5", "#7fff8a00"}; //ระบสี
private Double startLatADouble = 0.0, startLngADouble = 0.0;
private Double endLatADouble , endLngADouble;
private LocationManager locationManager;
private Criteria criteria;
private EditText originEditText, destinationEditText;
private String originString, destinationString;
private MyManage myManage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alternative_direction);
btnRequestDirection = (Button) findViewById(R.id.btn_request_direction);
btnRequestDirection.setOnClickListener(this);
//my setup
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
myManage = new MyManage(AlternativeDirectionActivity.this);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
} // Main Method
//ต้นหาพิกัด
@Override
protected void onResume() {
super.onResume();
afterResume();
}
private void afterResume() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(locationListener);
//หาพิกัด
Location networkLocation = myfindLocation(LocationManager.NETWORK_PROVIDER);
if (networkLocation != null) {
startLatADouble = networkLocation.getLatitude();
startLngADouble = networkLocation.getLongitude();
}
Location gpsLocation = myfindLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
startLatADouble = gpsLocation.getLatitude();
startLngADouble = gpsLocation.getLongitude();
}
Log.d("29janV1", "Lat ==> " + startLatADouble);
Log.d("29janV1", "Lat ==> " + startLngADouble);
} //after Resume
//Overide on stop เพื่อสืบทอดเพื่อนำมาทำงาน
@Override
protected void onStop() {
super.onStop();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(locationListener);
}
// Method ค้นหา Location
public Location myfindLocation(String strProvider) {
Location location = null;
if (locationManager.isProviderEnabled(strProvider)) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
} //
locationManager.requestLocationUpdates(strProvider, 1000, 10, locationListener);
location = locationManager.getLastKnownLocation(strProvider);
}
return location;
}
//get Location
public LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
startLatADouble = location.getLatitude();
startLngADouble = location.getLongitude();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
@Override
//ทำการดแลเกี่ยวกัที่
public void onMapReady(final GoogleMap googleMap) {
this.googleMap = googleMap;
//set up center map
camera = new LatLng(startLatADouble, startLngADouble);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(camera, 15));
//การสร้าง marker ของ user ==> สร้างจุดเริมตินเป็น marker
createMarkerUser();
//get event click map
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
googleMap.clear();
createMarkerUser(); //refresh marker
createMakerDestination(latLng);
} //onMapClick
});
}
private void createMakerDestination(LatLng latLng) {
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));;
endLatADouble = latLng.latitude;
endLngADouble = latLng.longitude;
Log.d("30janV1","Destination Lat ==> "+endLatADouble);
Log.d("30janV1","Destination Lng ==> "+endLngADouble);
destination = new LatLng(endLatADouble,endLngADouble);
} // createMakerDestination
private void createMarkerUser() {
origin = new LatLng(startLatADouble, startLngADouble);
googleMap.addMarker(new MarkerOptions().position(origin));
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_request_direction) {
requestDirection();
}
}
public void requestDirection() {
Snackbar.make(btnRequestDirection, "Direction Requesting...", Snackbar.LENGTH_SHORT).show();
GoogleDirection.withServerKey(serverKey)
.from(origin)
.to(destination)
.transportMode(TransportMode.DRIVING) //select mode travel
.alternativeRoute(true)
.execute(this);
}
@Override
public void onDirectionSuccess(Direction direction, String rawBody) {
Snackbar.make(btnRequestDirection, "Success with status : " + direction.getStatus(), Snackbar.LENGTH_SHORT).show();
Polyline[] polylines = new Polyline[direction.getRouteList().size()];
if (direction.isOK()) {
// googleMap.addMarker(new MarkerOptions().position(origin));
// googleMap.addMarker(new MarkerOptions().position(destination));
//getRouteList หาจำนวนเส้นทาง
Log.d("30janV2","จำนวนเส้นทางที่ google แนะนำา "+direction.getRouteList().size());
for (int i = 0; i < direction.getRouteList().size(); i++) {
Route route = direction.getRouteList().get(i);
String color = colors[i % colors.length]; //เส้นทางถูกจำกัด
ArrayList<LatLng> directionPositionList = route.getLegList().get(0).getDirectionPoint();
//googleMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 5, Color.parseColor(color)));
polylines[i] = googleMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 15, Color.parseColor(color)));
polylines[i].setClickable(true);
polylines[i].setZIndex(i);
//addPolyline สร้างเส้น
} //for
// btnRequestDirection.setVisibility(View.GONE); ==> Hide ป่ม เพื่อทำให้ืำการ เลือก ได้ใหม่
} //if
googleMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
@Override
public void onPolylineClick(Polyline polyline) {
Log.d("30janV2","Clik Polyline OK");
Log.d("30janV2","Index ==> "+polyline.getZIndex());
int index = (int) polyline.getZIndex();
// Toast.makeText(AlternativeDirectionActivity.this,"คุณเลือกเส้นทางที่ : "+Integer.toString(index),Toast.LENGTH_SHORT).show();
myAlertDiaglog(index);
}
});
}
private void myAlertDiaglog(int index) {
AlertDialog.Builder bulider = new AlertDialog.Builder(AlternativeDirectionActivity.this);
bulider.setCancelable(false);
bulider.setIcon(R.drawable.doremon48);
bulider.setTitle("ข้อมลที่ต้องการบันทึก");
LayoutInflater layoutInflater = AlternativeDirectionActivity.this.getLayoutInflater();
final View view = layoutInflater.inflate(R.layout.mylayout, null);
bulider.setView(view);
bulider.setMessage("คุณเลือกเส้นทาง : " + Integer.toString(index));
bulider.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
bulider.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Bind widget
originEditText = (EditText) view.findViewById(R.id.editText);
destinationEditText = (EditText) view.findViewById(R.id.editText2);
originString = originEditText.getText().toString().trim();
destinationString = destinationEditText.getText().toString().trim();
Log.d("30janV2", "Origin ==>" + originString);
Log.d("30janV2", "Destinaton ==>" + destinationString);
dialog.dismiss();
}
});
bulider.show();
} //myAlertDialog
@Override
public void onDirectionFailure(Throwable t) {
Snackbar.make(btnRequestDirection, t.getMessage(), Snackbar.LENGTH_SHORT).show();
}
}
| true |
ae8f7f7d98ec758189df56295b624129a759c8b9 | Java | jelem/capella | /task_30/andrew.samsonov/src/main/java/ua/pp/darknsoft/Counter02.java | UTF-8 | 753 | 2.96875 | 3 | [] | no_license | package ua.pp.darknsoft;
import java.util.concurrent.LinkedBlockingQueue;
public class Counter02 implements Runnable {
private LinkedBlockingQueue<Count> queue1 = new LinkedBlockingQueue();
private LinkedBlockingQueue<Count> queue2 = new LinkedBlockingQueue();
public Counter02(LinkedBlockingQueue queue1, LinkedBlockingQueue queue2) {
this.queue1 = queue1;
this.queue2 = queue2;
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
Count count = queue1.take();
count.setName("Counter_2");
count.setCountIt();
System.out.println(count);
queue2.put(count);
}
} catch (InterruptedException ex) {
System.out.println("COUNTER_2 OFF");
}
}
}
| true |
9a84d73937bf716a05edc1df628af410c70e41ed | Java | pankajksewalia/communication | /core/src/main/java/com/tricounsel/communication/core/enums/SequenceKeyEnum.java | UTF-8 | 291 | 2.25 | 2 | [] | no_license | package com.tricounsel.communication.core.enums;
public enum SequenceKeyEnum {
TEMPLATE("template");
private String sequenceKey;
public String getSequenceKey() {
return sequenceKey;
}
private SequenceKeyEnum(String sequenceKey) {
this.sequenceKey = sequenceKey;
}
}
| true |
bc9ba120e4f3ed54903dcbe499aa86e9504ce4ff | Java | petitizere89/project2 | /FirstThyme/src/main/java/com/project2/controllers/UserContoller.java | UTF-8 | 2,005 | 2.375 | 2 | [] | no_license | package com.project2.controllers;
import java.util.LinkedHashMap;
import org.hibernate.usertype.UserVersionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.project2.models.User;
import com.project2.services.UserService;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@RestController
@RequestMapping(value="/users")
@NoArgsConstructor
@AllArgsConstructor(onConstructor=@__(@Autowired))
@CrossOrigin(value = "*")
public class UserContoller {
private UserService uServ;
@PostMapping("/signup")
public ResponseEntity<String> createUser(@RequestBody LinkedHashMap<String,String>user){
User u = new User(user.get("firstName"),user.get("lastName"),user.get("email"),user.get("password"));
if(uServ.createUser(u)) {
return new ResponseEntity<String>("User was registered",HttpStatus.CREATED);
}else {
return new ResponseEntity<String>("Username or email was already taken", HttpStatus.CONFLICT);
}
}
@PostMapping("/login")
//@RequestMapping(method = RequestMethod.POST, consumes = "application/json", value = "/login")
public ResponseEntity<User> loginUser(@RequestBody LinkedHashMap<String, String> user){
System.out.println(user);
User u = uServ.loginUser(user.get("username"), user.get("password"));
if(u==null) {
return new ResponseEntity<User>(u,HttpStatus.FORBIDDEN);
}
u.toString();
return new ResponseEntity<User>(u,HttpStatus.OK);
}
}
| true |
4d48a8a3af230fccb5ecfafe858e22d3270bdebc | Java | LarryMckuydee/cally_theory | /src/app/App.java | UTF-8 | 3,885 | 3.15625 | 3 | [] | no_license | package app;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import app.models.CallRequest;
import app.models.Employee;
import app.models.CustomerService;
import app.models.TechnicalLead;
import app.queues.JobQueues;
import app.models.ProductManager;
import app.services.EmployeeCollection;
import app.services.ReceiveCall;
import app.services.ResponseCall;
public class App {
public static void main(String[] args) throws Exception {
CustomerService kelly = new CustomerService("Kelly", "kelly@gmail.com");
CustomerService sam = new CustomerService("Sam", "sam@gmail.com");
CustomerService sebastian = new CustomerService("Sebastian", "sebastian@gmail.com");
CustomerService nina = new CustomerService("Nina", "nina@gmail.com");
TechnicalLead larry = new TechnicalLead("Larry", "larry@gmail.com");
ProductManager ashley = new ProductManager("Ashley", "ashley@gmail.com");
Employee[] employees = {
kelly,
sam,
sebastian,
nina,
larry,
ashley
};
// kelly.engaging();
// larry.engaging();
EmployeeCollection employeeCollection = new EmployeeCollection(Arrays.asList(employees));
List<Employee> employeeList = employeeCollection.getAvailableEmployees();
employeeList.forEach(employee -> System.out.println("Available employee : " + employee.getName()));
Queue<CallRequest> csQueue = new LinkedList<CallRequest>();
Queue<CallRequest> tlQueue = new LinkedList<CallRequest>();
Queue<CallRequest> pmQueue = new LinkedList<CallRequest>();
HashMap<Integer, Queue<CallRequest>> queueMap = new HashMap<Integer, Queue<CallRequest>>();
queueMap.put(1, csQueue);
queueMap.put(2, tlQueue);
queueMap.put(3, pmQueue);
System.out.println(queueMap);
JobQueues jq = new JobQueues();
jq.initialize();
System.out.println(jq.customerServiceQueue());
CallRequest callRequest1 = new CallRequest();
CallRequest callRequest2 = new CallRequest();
CallRequest callRequest3 = new CallRequest();
CallRequest callRequest4 = new CallRequest();
CallRequest callRequest5 = new CallRequest();
CallRequest callRequest6 = new CallRequest();
CallRequest callRequest7 = new CallRequest();
CallRequest callRequest8 = new CallRequest();
CallRequest callRequest9 = new CallRequest();
CallRequest callRequest10 = new CallRequest();
CallRequest callRequest11 = new CallRequest();
CallRequest[] callRequests = {
callRequest1,
callRequest2,
callRequest3,
callRequest4,
callRequest5,
callRequest6,
callRequest7,
callRequest8,
callRequest9,
callRequest10,
callRequest11
};
List<CallRequest> callRequestList = Arrays.asList(callRequests);
System.out.println("cr1 " + callRequest1.getUUID());
System.out.println("cr2 " + callRequest2.getUUID());
System.out.println("cr3 " + callRequest3.getUUID());
for(CallRequest callRequest: callRequestList) {
Thread receiveThread = new Thread(new ReceiveCall(callRequest, queueMap, employeeCollection));
receiveThread.start();
};
for(Employee employee: employeeList) {
Thread responseThread = new Thread(new ResponseCall(employee, queueMap, employeeCollection));
responseThread.start();
}
// CallRequest cr = csQueue.poll();
// System.out.println("crpol " + cr.getUUID());
// cr = csQueue.poll();
// System.out.println("crpol " + cr.getUUID());
System.out.println("Hello Java");
}
} | true |
d2859e0b06fe42b2919a3245301f4778f8e4faf8 | Java | consulo/consulo-xml | /xml-impl/src/main/java/consulo/xml/navigation/LinkedToHtmlFilesContributor.java | UTF-8 | 2,700 | 1.734375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.xml.navigation;
import consulo.annotation.component.ExtensionImpl;
import consulo.xml.psi.xml.XmlAttribute;
import consulo.xml.psi.xml.XmlAttributeValue;
import consulo.xml.psi.xml.XmlFile;
import consulo.xml.psi.xml.XmlTag;
import consulo.application.util.function.Processor;
import com.intellij.xml.util.HtmlLinkUtil;
import consulo.language.psi.PsiElement;
import consulo.language.psi.PsiFile;
import consulo.language.psi.PsiPolyVariantReference;
import consulo.language.psi.PsiReference;
import consulo.language.psi.ResolveResult;
import javax.annotation.Nonnull;
import java.util.Set;
/**
* @author Eugene.Kudelevsky
*/
@ExtensionImpl
public class LinkedToHtmlFilesContributor extends RelatedToHtmlFilesContributor {
@Override
public void fillRelatedFiles(@Nonnull final XmlFile xmlFile, @Nonnull final Set<PsiFile> resultSet) {
HtmlLinkUtil.processLinks(xmlFile, new Processor<XmlTag>() {
@Override
public boolean process(XmlTag tag) {
final XmlAttribute attribute = tag.getAttribute("href");
if (attribute == null) {
return true;
}
final XmlAttributeValue link = attribute.getValueElement();
if (link == null) {
return true;
}
for (PsiReference reference : link.getReferences()) {
if (reference instanceof PsiPolyVariantReference) {
final ResolveResult[] results = ((PsiPolyVariantReference)reference).multiResolve(false);
for (ResolveResult result : results) {
final PsiElement resolvedElement = result.getElement();
if (resolvedElement instanceof PsiFile) {
resultSet.add((PsiFile)resolvedElement);
}
}
}
else {
final PsiElement resolvedElement = reference.resolve();
if (resolvedElement instanceof PsiFile) {
resultSet.add((PsiFile)resolvedElement);
}
}
}
return true;
}
});
}
@Override
public String getGroupName() {
return "Linked files";
}
}
| true |
e7a1bb77507a67a60fbb9f10e0edb844e967ab71 | Java | sonnyred15/mpbomberman | /server/src/main/java/org/amse/bomberman/server/net/tcpimpl/sessions/control/RequestExecutor.java | UTF-8 | 1,487 | 1.757813 | 2 | [] | no_license | package org.amse.bomberman.server.net.tcpimpl.sessions.control;
//~--- non-JDK imports --------------------------------------------------------
import java.util.List;
import org.amse.bomberman.protocol.InvalidDataException;
/**
*
* @author Kirilchuk V.E
*/
public interface RequestExecutor {
// commands
void sendGames() throws InvalidDataException ;
void tryCreateGame(List<String> args) throws InvalidDataException ;
void tryJoinGame(List<String> args) throws InvalidDataException ;
void tryDoMove(List<String> args) throws InvalidDataException ;
void sendGameMapInfo() throws InvalidDataException ;
void tryStartGame() throws InvalidDataException ;
void tryLeave() throws InvalidDataException ;
void tryPlaceBomb() throws InvalidDataException ;
@Deprecated
void sendDownloadingGameMap(List<String> args) throws InvalidDataException ;
void sendGameStatus() throws InvalidDataException ;
void sendGameMapsList() throws InvalidDataException ;
void tryAddBot(List<String> args) throws InvalidDataException ;
void sendGameInfo() throws InvalidDataException ;
void addMessageToChat(List<String> args) throws InvalidDataException ;
void sendNewMessagesFromChat() throws InvalidDataException ;
void tryKickPlayer(List<String> args) throws InvalidDataException ;
void sendGamePlayersStats() throws InvalidDataException ;
void setClientNickName(List<String> args) throws InvalidDataException ;
}
| true |
4cbb0b38b208b80a1075ba04277af2f7abe24cf5 | Java | jiangyun2014/minishop | /back_end/minishop/src/main/java/com/cndata/minishop/service/impl/ReceiverServiceImpl.java | UTF-8 | 1,350 | 2.109375 | 2 | [] | no_license | package com.cndata.minishop.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cndata.minishop.domain.Receiver;
import com.cndata.minishop.domain.ReceiverExample;
import com.cndata.minishop.mapper.ReceiverMapper;
import com.cndata.minishop.service.ReceiverService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Service("receiverService")
public class ReceiverServiceImpl implements ReceiverService {
@Autowired
private ReceiverMapper receiverMapper;
@Override
public void add(Receiver receiver) {
receiverMapper.insert(receiver);
}
@Override
public void delete(Integer id) {
receiverMapper.deleteByPrimaryKey(id);
}
@Override
public void update(Receiver receiver) {
receiverMapper.updateByPrimaryKeySelective(receiver);
}
@Override
public Receiver getById(Integer id) {
return receiverMapper.selectByPrimaryKey(id);
}
@Override
public List<Receiver> getByList(ReceiverExample example) {
return receiverMapper.selectByExample(example);
}
@Override
public PageInfo<Receiver> getByPage(ReceiverExample example, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
return new PageInfo<Receiver>(receiverMapper.selectByExample(example));
}
}
| true |
512584c1ac3ffd5f5262e4b457d24a660a7753ce | Java | shanpengfei7/jmy | /zjk_isp/src/main/java/com/jmy/dao/Coi_category_threeMapper.java | UTF-8 | 3,760 | 1.84375 | 2 | [] | no_license | package com.jmy.dao;
import com.jmy.entity.Coi_category_three;
import com.jmy.entity.Coi_category_threeExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface Coi_category_threeMapper {
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int countByExample(Coi_category_threeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int deleteByExample(Coi_category_threeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int insert(Coi_category_three record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int insertSelective(Coi_category_three record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
List<Coi_category_three> selectByExampleWithBLOBs(Coi_category_threeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
List<Coi_category_three> selectByExample(Coi_category_threeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
Coi_category_three selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int updateByExampleSelective(@Param("record") Coi_category_three record,
@Param("example") Coi_category_threeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int updateByExampleWithBLOBs(@Param("record") Coi_category_three record,
@Param("example") Coi_category_threeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int updateByExample(@Param("record") Coi_category_three record,
@Param("example") Coi_category_threeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int updateByPrimaryKeySelective(Coi_category_three record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int updateByPrimaryKeyWithBLOBs(Coi_category_three record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table isp_coi_category_three
* @mbggenerated Mon Mar 27 19:10:41 CST 2017
*/
int updateByPrimaryKey(Coi_category_three record);
} | true |
17c79aea39dc2117cda13571917b4e020f8095f9 | Java | hbwzhsh/tutorials | /bigdata/src/main/java/com/zdatainc/rts/spark/TwitterFilterFunction.java | UTF-8 | 1,384 | 2.421875 | 2 | [] | no_license | package com.zdatainc.rts.spark;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.spark.api.java.function.*;
import scala.Tuple2;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
public class TwitterFilterFunction
implements PairFunction<String, Long, String>
{
private static final long serialVersionUID = 42l;
private final ObjectMapper mapper = new ObjectMapper();
@Override
public Tuple2<Long, String> call(String tweet)
{
try
{
JsonNode root = mapper.readValue(tweet, JsonNode.class);
long id;
String text;
if (root.get("lang") != null &&
"en".equals(root.get("lang").textValue()))
{
if (root.get("id") != null && root.get("text") != null)
{
id = root.get("id").longValue();
text = root.get("text").textValue();
return new Tuple2<Long, String>(id, text);
}
return null;
}
return null;
}
catch (IOException ex)
{
Logger LOG = Logger.getLogger(this.getClass());
LOG.error("IO error while filtering tweets", ex);
LOG.trace(null, ex);
}
return null;
}
}
| true |
7f8d61860e414447bec2e11061b3e1e18f0c6cd0 | Java | verhas/jScriptBasic | /src/main/java/com/scriptbasic/sourceproviders/AbstractSourceProvider.java | UTF-8 | 578 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | package com.scriptbasic.sourceproviders;
import com.scriptbasic.readers.SourceProvider;
import com.scriptbasic.readers.SourceReader;
import java.io.IOException;
/**
* An abstract source provider to be extended by the source provider
* implementations.
*
* @author Peter Verhas
*/
public abstract class AbstractSourceProvider implements SourceProvider {
@Override
public abstract SourceReader get(String sourceName) throws IOException;
@Override
public abstract SourceReader get(String sourceName, String referencingSource)
throws IOException;
}
| true |
b06953d56c7b827707c46e01c5a1e723e1d7fad8 | Java | PrishanM/SwyftrRider | /app/src/main/java/com/evensel/riderswyftr/deliveries/DeliveryHistoryFragment.java | UTF-8 | 6,815 | 1.890625 | 2 | [] | no_license | package com.evensel.riderswyftr.deliveries;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.evensel.riderswyftr.R;
import com.evensel.riderswyftr.util.AppController;
import com.evensel.riderswyftr.util.Constants;
import com.evensel.riderswyftr.util.Datum;
import com.evensel.riderswyftr.util.JsonRequestManager;
import com.evensel.riderswyftr.util.Notifications;
import com.evensel.riderswyftr.util.OrderHistoryResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Created by Prishan Maduka on 2/12/2017.
*/
public class DeliveryHistoryFragment extends Fragment {
private ViewPager viewPager;
private TabLayout tabLayout;
private ProgressDialog progress;
private SharedPreferences sharedPref;
private View layout;
private LayoutInflater inflate;
private String token;
private DeliveryHistoryPagerAdapter deliveryHistoryPagerAdapter;
private ArrayList<Datum> thisWeekList = new ArrayList<>();
private ArrayList<Datum> olderList = new ArrayList<>();
public DeliveryHistoryFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_delivery_history, container, false);
viewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
sharedPref = getActivity().getSharedPreferences(Constants.LOGIN_SHARED_PREF, Context.MODE_PRIVATE);
token = sharedPref.getString(Constants.LOGIN_ACCESS_TOKEN, "");
inflate = inflater;
layout = inflate.inflate(R.layout.custom_toast_layout,(ViewGroup) rootView.findViewById(R.id.toast_layout_root));
addFiles();
// Inflate the layout for this fragment
return rootView;
}
private void setupViewPager() {
ArrayList<String> titles = new ArrayList<>();
titles.add("This Week");
titles.add("Last Week");
deliveryHistoryPagerAdapter =
new DeliveryHistoryPagerAdapter(getChildFragmentManager(),titles);
viewPager.setAdapter(deliveryHistoryPagerAdapter);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
private void addFiles() {
/*progress = ProgressDialog.show(getActivity(), null,
"Loading...", true);
Log.d("xxxxxxxxxx",token);
JsonRequestManager.getInstance(getActivity()).getOrderHistoryRequest(AppURL.APPLICATION_BASE_URL+AppURL.GET_ORDER_HISTORY__URL+token,token, getOrderHistoryCallback);*/
Datum datum = new Datum();
datum.setOrderId((long) 1);
datum.setDeliveredLocation("295/2 Stanley Thilakarathna Mawatha Nugegoda");
datum.setOrderDeliveredTime("2016-10-10 10:31:00");
thisWeekList.add(datum);
Datum datum2 = new Datum();
datum2.setOrderId((long) 2);
datum2.setDeliveredLocation("295/2 Stanley Thilakarathna Mawatha Nugegoda");
datum2.setOrderDeliveredTime("2016-10-10 10:31:00");
thisWeekList.add(datum2);
Datum datum3 = new Datum();
datum3.setOrderId((long) 3);
datum3.setDeliveredLocation("295/2 Stanley Thilakarathna Mawatha Nugegoda");
datum3.setOrderDeliveredTime("2016-10-10 10:31:00");
thisWeekList.add(datum3);
Datum datum4 = new Datum();
datum4.setOrderId((long) 4);
datum4.setDeliveredLocation("295/2 Stanley Thilakarathna Mawatha Nugegoda");
datum4.setOrderDeliveredTime("2016-10-10 10:31:00");
olderList.add(datum4);
Datum datum5 = new Datum();
datum5.setOrderId((long) 5);
datum5.setDeliveredLocation("295/2 Stanley Thilakarathna Mawatha Nugegoda");
datum5.setOrderDeliveredTime("2016-10-10 10:31:00");
olderList.add(datum5);
AppController.setOlderList(olderList);
AppController.setThisWeekList(thisWeekList);
setupViewPager();
}
//Response callback for "Get Delivery History"
private final JsonRequestManager.getOrderHistory getOrderHistoryCallback = new JsonRequestManager.getOrderHistory() {
@Override
public void onSuccess(OrderHistoryResponse model) {
if(progress!=null)
progress.dismiss();
if(model.getStatus().equalsIgnoreCase("success")){
/*for (Datum datum:model.getDetails().getData()){
if(isThisWeek(datum.getOrderDeliveredTime())){
thisWeekList.add(datum);
}else{
olderList.add(datum);
}
}*/
}else{
Notifications.showToastMessage(layout,getActivity(),model.getMessage()).show();
}
}
@Override
public void onError(String status) {
if(progress!=null)
progress.dismiss();
Notifications.showToastMessage(layout,getActivity(),status).show();
}
@Override
public void onError(OrderHistoryResponse model) {
if(progress!=null)
progress.dismiss();
Notifications.showToastMessage(layout,getActivity(),model.getMessage()).show();
}
};
private boolean isThisWeek(String dateTime){
Date date = null;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
try {
date = format.parse(dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
Date monday = c.getTime();
Date nextMonday= new Date(monday.getTime()+7*24*60*60*1000);
return date.after(monday) && date.before(nextMonday);
}
}
| true |
ea1fee2da5fc963b6b587bde80ff87724a76dc0f | Java | jenneydc/CSE385-Pokedex | /workspace/Pokebase/src/PokemonDetail.java | UTF-8 | 7,139 | 2.421875 | 2 | [] | no_license |
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JDialog;
import javax.swing.table.DefaultTableModel;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Drew Jenney
*/
public class PokemonDetail extends javax.swing.JDialog {
StandardQueries std;
int pokemonID = 0;
/**
* Creates new form PokemonDetail
*/
public PokemonDetail(java.awt.Frame parent, StandardQueries std, int pokemonID) {
super(parent, true);
initComponents();
this.std = std;
this.pokemonID = pokemonID;
jTable1.setTableHeader(null);
populateDetail();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
void populateDetail() {
setTableDefaults();
populateTable();
}
void setTableDefaults() {
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt("HP:", 0, 0);
model.setValueAt("Att:", 1, 0);
model.setValueAt("Def:", 2, 0);
model.setValueAt("Sp.Att:", 3, 0);
model.setValueAt("Sp.Def:", 4, 0);
model.setValueAt("Spd:", 5, 0);
}
void populateTable() {
try {
Statement pokemon = std.conn.createStatement();
ResultSet pokemonInfo = pokemon.executeQuery("SELECT * FROM STATS WHERE PokemonID = "+pokemonID);
pokemonInfo.first();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt(pokemonInfo.getInt("HP"), 0, 1);
model.setValueAt(pokemonInfo.getInt("Att"), 1, 1);
model.setValueAt(pokemonInfo.getInt("Def"), 2, 1);
model.setValueAt(pokemonInfo.getInt("SpAtt"), 3, 1);
model.setValueAt(pokemonInfo.getInt("SpDef"), 4, 1);
model.setValueAt(pokemonInfo.getInt("Spd"), 5, 1);
} catch (Exception ex) {
System.err.print(ex.getMessage());
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Title 1", "Title 2"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setShowHorizontalLines(false);
jTable1.setShowVerticalLines(false);
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
}
jLabel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel3.setText("jLabel3");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(131, 131, 131)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| true |
4251c48ca870e83a4ae59964ca82204e88044127 | Java | Whodundid/EnhancedMC-Core | /src/main/java/com/Whodundid/core/windowLibrary/windowObjects/advancedObjects/textArea/TextAreaLine.java | UTF-8 | 17,134 | 2.03125 | 2 | [
"BSD-3-Clause"
] | permissive | package com.Whodundid.core.windowLibrary.windowObjects.advancedObjects.textArea;
import com.Whodundid.core.EnhancedMC;
import com.Whodundid.core.coreApp.EMCResources;
import com.Whodundid.core.util.EUtil;
import com.Whodundid.core.util.chatUtil.EChatUtil;
import com.Whodundid.core.util.guiUtil.GuiOpener;
import com.Whodundid.core.util.miscUtil.EMouseHelper;
import com.Whodundid.core.util.renderUtil.CursorHelper;
import com.Whodundid.core.util.renderUtil.EColors;
import com.Whodundid.core.util.renderUtil.ScreenLocation;
import com.Whodundid.core.util.storageUtil.TrippleBox;
import com.Whodundid.core.windowLibrary.windowObjects.actionObjects.WindowButton;
import com.Whodundid.core.windowLibrary.windowObjects.actionObjects.WindowTextField;
import com.Whodundid.core.windowLibrary.windowObjects.basicObjects.WindowLabel;
import com.Whodundid.core.windowLibrary.windowObjects.windows.LinkConfirmationWindow;
import com.Whodundid.core.windowLibrary.windowTypes.interfaces.IWindowObject;
import com.Whodundid.core.windowLibrary.windowTypes.interfaces.IWindowParent;
import com.Whodundid.core.windowLibrary.windowUtil.windowEvents.eventUtil.FocusType;
import com.Whodundid.core.windowLibrary.windowUtil.windowEvents.eventUtil.MouseType;
import com.Whodundid.core.windowLibrary.windowUtil.windowEvents.eventUtil.ObjectModifyType;
import com.Whodundid.core.windowLibrary.windowUtil.windowEvents.events.EventFocus;
import com.Whodundid.core.windowLibrary.windowUtil.windowEvents.events.EventMouse;
import java.io.File;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ChatAllowedCharacters;
import org.lwjgl.input.Mouse;
//Author: Hunter Bragg
public class TextAreaLine<obj> extends WindowTextField {
protected WindowTextArea parentTextArea;
protected WindowLabel numberLabel;
protected IWindowObject focusRequester;
public int lineNumberColor = 0xff555555;
protected int lineNumber = 0;
protected int drawnLineNumber = 0;
protected int lineNumberWidth = 0;
protected int maxVisibleLength = 3;
protected boolean textRecentlyEntered = false;
protected boolean deleting = false;
protected boolean creating = false;
protected boolean highlighted = false;
protected boolean lineEquals = false, drawCursor = false;
protected long startTime = 0l;
protected long doubleClickTimer = 0l;
protected long doubleClickThreshold = 500l;
protected boolean clicked = false;
protected obj storedObj;
protected String linkText = "";
protected boolean webLink;
protected Object linkObject;
//-------------------------
//TextAreaLine Constructors
//-------------------------
public TextAreaLine(WindowTextArea textAreaIn) { this(textAreaIn, "", 0xffffff, null, -1); }
public TextAreaLine(WindowTextArea textAreaIn, String textIn) { this(textAreaIn, textIn, 0xffffff, null, -1); }
public TextAreaLine(WindowTextArea textAreaIn, String textIn, int colorIn) { this(textAreaIn, textIn, colorIn, null, -1); }
public TextAreaLine(WindowTextArea textAreaIn, String textIn, obj objectIn) { this(textAreaIn, textIn, 0xffffff, objectIn, -1); }
public TextAreaLine(WindowTextArea textAreaIn, String textIn, int colorIn, obj objectIn) { this(textAreaIn, textIn, colorIn, objectIn, -1); }
public TextAreaLine(WindowTextArea textAreaIn, String textIn, int colorIn, obj objectIn, int lineNumberIn) {
init(textAreaIn, 0, 0, 0, 0);
setMaxStringLength(1500);
parent = textAreaIn;
parentTextArea = textAreaIn;
lineNumber = lineNumberIn;
setText(textIn);
textColor = colorIn;
setStoredObj(objectIn);
setDrawShadowed(false);
}
//----------------
//Object Overrides
//----------------
@Override public String toString() { return "[" + lineNumber + ": " + getText() + "]"; }
//----------------------
//WindowObject Overrides
//----------------------
@Override
public void drawObject(int mXIn, int mYIn) {
updateBeforeNextDraw(mXIn, mYIn);
updateValues();
boolean current = parentTextArea.getCurrentLine() == this;
drawText();
if (textRecentlyEntered == true) {
if (System.currentTimeMillis() - startTime >= 600) {
startTime = 0l;
textRecentlyEntered = false;
}
}
if (checkDraw()) {
for (IWindowObject o : windowObjects) {
if (o.checkDraw()) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
o.drawObject(mXIn, mYIn);
}
}
}
if (parentTextArea.isEditable()) {
if (!Mouse.isButtonDown(0)) { clickStartPos = -1; }
if (clickStartPos != -1) {
int i = mXIn - startX - parentTextArea.getLineNumberOffset() + 3;
int cursorPos = mc.fontRendererObj.trimStringToWidth(text, i).length();
setSelectionPos(cursorPos);
}
}
}
@Override
public void keyPressed(char typedChar, int keyCode) {
if (hasFocus()) {
parentTextArea.keyPressed(typedChar, keyCode);
if (GuiScreen.isKeyComboCtrlA(keyCode)) { setCursorPositionEnd(); }
else if (GuiScreen.isKeyComboCtrlC(keyCode)) { GuiScreen.setClipboardString(getSelectedText()); }
else if (GuiScreen.isKeyComboCtrlV(keyCode) && isEnabled()) { writeText(GuiScreen.getClipboardString()); }
else if (GuiScreen.isKeyComboCtrlX(keyCode)) {
GuiScreen.setClipboardString(getSelectedText());
if (isEnabled() && parentTextArea.isEditable()) {
writeText("");
}
}
else {
switch (keyCode) {
case 28: //enter
if (parentTextArea.isEditable()) {
parentTextArea.createNewLineAfter(this);
setDimensions(startX, startY, mc.fontRendererObj.getStringWidth(text), height);
}
break;
case 200: //up
parentTextArea.selectPreviousLine(this, getCursorPosition());
break;
case 208: //down
parentTextArea.selectNextLine(this, getCursorPosition());
break;
case 14: //backspace
if (parentTextArea.isEditable()) {
if (getText().isEmpty() || cursorPosition == 0) {
TextAreaLine l = parentTextArea.deleteLineAndAddPrevious(this);
if (l != null) {
l.setDimensions(l.startX, l.startY, mc.fontRendererObj.getStringWidth(l.getText()), l.height);
}
}
else if (GuiScreen.isCtrlKeyDown()) {
if (isEnabled()) {
deleteWords(-1);
setDimensions(startX, startY, mc.fontRendererObj.getStringWidth(text), height);
}
}
else if (isEnabled()) {
deleteFromCursor(-1);
setDimensions(startX, startY, mc.fontRendererObj.getStringWidth(text), height);
}
startTextTimer();
}
break;
case 199: //home
if (GuiScreen.isShiftKeyDown()) { setSelectionPos(0); }
else { setCursorPositionZero(); }
break;
case 203: //left
if (GuiScreen.isShiftKeyDown()) {
if (GuiScreen.isCtrlKeyDown()) { setSelectionPos(getNthWordFromPos(-1, getSelectionEnd())); }
else { setSelectionPos(getSelectionEnd() - 1); }
}
else if (GuiScreen.isCtrlKeyDown()) { setCursorPosition(getNthWordFromCursor(-1)); }
else { moveCursorBy(-1); }
startTextTimer();
break;
case 205: //right
if (GuiScreen.isShiftKeyDown()) {
if (GuiScreen.isCtrlKeyDown()) { setSelectionPos(getNthWordFromPos(1, getSelectionEnd())); }
else { setSelectionPos(getSelectionEnd() + 1); }
}
else if (GuiScreen.isCtrlKeyDown()) { setCursorPosition(getNthWordFromCursor(1)); }
else { moveCursorBy(1); }
startTextTimer();
break;
case 207: //end
if (GuiScreen.isShiftKeyDown()) { setSelectionPos(text.length()); }
else { setCursorPositionEnd(); }
break;
case 211: //delete
if (parentTextArea.isEditable()) {
if (GuiScreen.isCtrlKeyDown()) {
if (isEnabled()) { deleteWords(1); startTextTimer(); }
}
else if (isEnabled()) { deleteFromCursor(1); startTextTimer(); }
}
break;
default:
if (parentTextArea.isEditable()) {
if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) {
if (isEnabled()) {
writeText(Character.toString(typedChar));
setDimensions(startX, startY, mc.fontRendererObj.getStringWidth(text), height);
startTextTimer();
}
}
}
} //switch
}
}
}
@Override
public void mousePressed(int mXIn, int mYIn, int button) {
postEvent(new EventMouse(this, mX, mY, button, MouseType.Pressed));
int mX = mXIn;
int mY = mYIn;
int b = button;
if (b == -1) {
mX = EMouseHelper.getMx();
mY = EMouseHelper.getMy();
b = Mouse.getEventButton();
}
try {
if (isMouseOver(mX, mY)) { EUtil.ifNotNullDo(getWindowParent(), w -> w.bringToFront()); }
if (b == 0) {
startTextTimer();
if (isResizeable() && !getEdgeAreaMouseIsOn().equals(ScreenLocation.out)) {
getTopParent().setModifyingObject(this, ObjectModifyType.Resize);
getTopParent().setResizingDir(getEdgeAreaMouseIsOn());
getTopParent().setModifyMousePos(mX, mY);
}
if (parentTextArea.isEditable()) {
int i = mX - startX - parentTextArea.getLineNumberOffset() + 3;
int cursorPos = mc.fontRendererObj.trimStringToWidth(text, i).length();
setCursorPosition(cursorPos);
selectionEnd = cursorPosition;
if (clickStartPos == -1) { clickStartPos = cursorPos; }
}
checkLinkClick(mX, mY, b);
}
}
catch (Exception e) { e.printStackTrace(); }
}
/** Prevent cursor updates. */
@Override public void updateCursorImage() {}
@Override
public void mouseEntered(int mXIn, int mYIn) {
super.mouseEntered(mXIn, mYIn);
IWindowObject focused = getTopParent().getFocusedObject();
boolean oneOf = focused == this || parentTextArea.isChild(focused);
if (parentTextArea.isEditable() && (oneOf || !Mouse.isButtonDown(0))) {
CursorHelper.setCursor(EMCResources.cursorIBeam);
}
}
@Override
public void mouseExited(int mXIn, int mYIn) {
super.mouseExited(mXIn, mYIn);
IWindowObject over = getTopParent().getHighestZObjectUnderMouse();
boolean inside = over != parentTextArea || !parentTextArea.isChild(over);
if (parentTextArea.isEditable() && !inside) { CursorHelper.reset(); }
}
@Override
public void onFocusGained(EventFocus eventIn) {
parentTextArea.setSelectedLine(this);
int mX = eventIn.getMX();
int mY = eventIn.getMY();
int b = eventIn.getActionCode();
if (b == -1) {
mX = EMouseHelper.getMx();
mY = EMouseHelper.getMy();
b = Mouse.getEventButton();
}
if (focusRequester != null) {
focusRequester.requestFocus();
}
if (eventIn.getFocusType() == FocusType.MousePress) {
startTextTimer();
checkLinkClick(mX, mY, b);
if (mX > endX) {
setCursorPosition(text.length() + 1);
selectionEnd = cursorPosition;
if (clickStartPos == -1) { clickStartPos = text.length() + 1; }
}
else if (mX >= startX) {
int i = mX - startX - parentTextArea.getLineNumberOffset() + 3;
int cursorPos = mc.fontRendererObj.trimStringToWidth(text, i).length();
setCursorPosition(cursorPos);
selectionEnd = cursorPosition;
if (clickStartPos == -1) { clickStartPos = cursorPos; }
}
else {
setCursorPosition(0);
selectionEnd = cursorPosition;
if (clickStartPos == -1) { clickStartPos = 0; }
}
}
}
@Override
public void onFocusLost(EventFocus eventIn) {
clickStartPos = -1;
super.onFocusLost(eventIn);
}
//--------------------
//TextAreaLine Methods
//--------------------
public void startTextTimer() {
startTime = System.currentTimeMillis();
textRecentlyEntered = true;
}
public TextAreaLine incrementLineNumber() { setLineNumber(lineNumber + 1); return this; }
public TextAreaLine decrementLineNumber() { setLineNumber(lineNumber - 1); return this; }
public TextAreaLine indent() { setText(" " + getText()); return this; }
//--------------------
//TextAreaLine Getters
//--------------------
public IWindowObject getFocusRequester() { return focusRequester; }
public int getDrawnLineNumber() { return drawnLineNumber; }
public int getLineNumber() { return lineNumber; }
public obj getStoredObj() { return storedObj; }
public long getDoubleClickThreshold() { return doubleClickThreshold; }
public TrippleBox<String, Object, Boolean> getLink() { return new TrippleBox(linkText, linkObject, webLink); }
//--------------------
//TextAreaLine Setters
//--------------------
public TextAreaLine setLinkText(String textIn) { return setLinkText(textIn, null, false); }
public TextAreaLine setLinkText(String textIn, Object linkObjectIn) { return setLinkText(textIn, linkObjectIn, false); }
public TextAreaLine setLinkText(String textIn, boolean isWebLink) { return setLinkText(textIn, null, isWebLink); }
public TextAreaLine setLinkText(String textIn, Object linkObjectIn, boolean isWebLink) {
linkText = textIn;
linkObject = linkObjectIn;
webLink = isWebLink;
return this;
}
public TextAreaLine setHighlighted(boolean val) {
cursorPosition = 0;
selectionEnd = val ? text.length() : 0;
return this;
}
public TextAreaLine setStoredObj(obj objectIn) { storedObj = objectIn; return this; }
public TextAreaLine setLineNumber(int numberIn) { lineNumber = numberIn; lineNumberWidth = mc.fontRendererObj.getStringWidth(String.valueOf(lineNumber)); return this; }
public TextAreaLine setLineNumberColor(EColors colorIn) { lineNumberColor = colorIn.intVal; return this; }
public TextAreaLine setLineNumberColor(int colorIn) { lineNumberColor = colorIn; return this; }
public TextAreaLine setDrawnLineNumber(int numberIn) { drawnLineNumber = numberIn; return this; }
public TextAreaLine setDoubleClickThreshold(long timeIn) { doubleClickThreshold = timeIn; return this; }
public TextAreaLine setFocusRequester(IWindowObject obj) { focusRequester = obj; return this; }
//------------------------------
//TextAreaLine Protecetd Methods
//------------------------------
protected void updateValues() {
if (clicked && System.currentTimeMillis() - doubleClickTimer >= doubleClickThreshold) { clicked = false; doubleClickTimer = 0l; }
if (parentTextArea != null && parentTextArea.getCurrentLine() != null) {
lineEquals = parentTextArea.getCurrentLine().equals(this);
drawCursor = parentTextArea.isEditable() && lineEquals && EnhancedMC.updateCounter / 20 % 2 == 0;
}
}
protected boolean checkLinkClick(int mXIn, int mYIn, int button) {
if (linkText != null && !linkText.isEmpty()) {
String uText = EChatUtil.removeFormattingCodes(text);
String test = "";
int total = 0;
int startPos = startX;
int endPos = startX;
int linkPos = 0;
for (int i = 0; i < uText.length(); i++) {
char c = uText.charAt(i);
int cLen = mc.fontRendererObj.getCharWidth(c);
total += cLen;
if (test.equals(linkText)) {
break;
}
if (c == linkText.charAt(linkPos)) {
endPos += cLen;
linkPos++;
test += c;
}
else {
startPos = startX + total;
endPos = startPos;
linkPos = 0;
test = "";
}
}
if (mXIn >= startPos && mXIn <= endPos) {
try {
WindowButton.playPressSound();
if (webLink) {
EnhancedMC.displayWindow(new LinkConfirmationWindow((String) linkObject));
return true;
}
else if (linkObject != null) {
if (linkObject instanceof File) { EUtil.openFile((File) linkObject); return true; }
if (linkObject instanceof IWindowParent) { EnhancedMC.displayWindow((IWindowParent) linkObject); return true; }
if (linkObject instanceof GuiScreen) { GuiOpener.openGui(linkObject.getClass()); return true; }
}
}
catch (Exception e) { e.printStackTrace(); }
}
} //if null link
return false;
}
protected void drawText() {
int selStart = cursorPosition;
int selEnd = selectionEnd;
boolean hasSel = (selStart != selEnd);
//draw text
if (drawShadowed) { drawStringS(text, startX + parentTextArea.getLineNumberOffset(), startY + 2, textColor); }
else { drawString(text, startX + parentTextArea.getLineNumberOffset(), startY + 2, textColor); }
if (lineEquals && parentTextArea.isEditable()) {
if (hasSel) { //draw highlight
int start = selStart;
int end = selEnd;
//fix substring positions
if (selStart > selEnd) {
start = selEnd;
end = selStart;
}
int xStart = startX + parentTextArea.getLineNumberOffset() + mc.fontRendererObj.getStringWidth(text.substring(0, start));
int xEnd = xStart + mc.fontRendererObj.getStringWidth(text.substring(start, end));
//fix highlight selection
if (selStart > selEnd) {
//int temp = xStart;
//xStart = xEnd;
//xEnd = temp;
}
//System.out.println(xStart + " " + xEnd);
drawCursorVertical(xStart, startY + 1, xEnd - 1, startY + 1 + mc.fontRendererObj.FONT_HEIGHT);
}
else if ((textRecentlyEntered || drawCursor) && hasFocus()) { //draw vertical cursor
int textCursorPosLength = mc.fontRendererObj.getStringWidth(text.substring(0, cursorPosition));
int sX = startX + parentTextArea.getLineNumberOffset() + textCursorPosLength;
drawRect(sX - 1, startY + 1, sX, endY, 0xffffffff);
}
}
}
}
| true |
de7e6d12bebf842f65e86810fd6c44a172e4f3d6 | Java | AntonKomarov/ESystem | /src/by/epamtc/komarov/matrix/multiplication/MatrixMultiplication.java | UTF-8 | 887 | 3.15625 | 3 | [] | no_license | package by.epamtc.komarov.matrix.multiplication;
import by.epamtc.komarov.matrix.print.PrintMatrix;
public class MatrixMultiplication {
public static void main(String[] args) {
int size = 3;
int[][] firstMatrix = new int[][]
{
{1,2},
{3,4},
{5,6}
};
int[][] secondMatrix = new int[][]
{
{7,8,9},
{10,11,12}
};
int[][] resultMatrix = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < 2; k++) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
PrintMatrix.print(resultMatrix);
}
}
| true |
0a8e80180e87fcdeb50578a6d3387fe1dde03fa0 | Java | alexpeptan/ToDoApp | /src/main/java/com/example/presentation/TaskEndpoint.java | UTF-8 | 5,555 | 2.265625 | 2 | [] | no_license | package com.example.presentation;
import com.example.*;
import com.example.domain.Task;
import com.example.domain.User;
import com.example.domain.vo.TaskVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@RestController
public class TaskEndpoint {
@Autowired
private TaskService taskService;
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
static class AuthenticationException extends Exception {}
// exception handler (separate class)
// handler method
// param1=value1¶m2=value2¶m3=value3
// <form>
// <textbox name=param1>
// </form>
//@SomeSecurity("onlyRunIfAuthenticated") // throw Exception if there is no logged in user, otherwise continue
@RequestMapping(path = "/create-task", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@Transactional(Transactional.TxType.REQUIRES_NEW)
public void doCreateTask(
final @RequestParam(value = "message") String content,
HttpServletResponse response) throws Exception {
// service call
taskService.create(TaskVO.builder().message(content).build());
response.setStatus(HttpServletResponse.SC_CREATED);
}
@RequestMapping(path = "/assign-task", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public void doAssignTask(
final @RequestParam(value = "toUserName") String toUser,
final @RequestParam(value = "taskID") Long taskId,
HttpServletResponse response,
@SessionAttribute(Constants.CURRENT_USER) Optional<Long> loggedInUserId) throws Exception {
if(!loggedInUserId.isPresent()){
throw new AuthenticationException();
}
User currentUser = loggedInUserId
.map(id -> userRepository.findOne(id))
.orElseThrow(() -> new RuntimeException("No such user exists anymore!"));
// authorization - none
Task task = taskService.getTaskById(taskId); // get task by id
if(task == null){
// invalid taskId - how can I communicate to the client more details about the response error?
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
User assigneeCandidate = userService.findByUserName(toUser);
if(assigneeCandidate == null){
// invalid user - how can I communicate to the client more details about the response error?
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
currentUser = userService.getCurrentUser();
if(currentUser == null || !currentUser.equals(task.getAuthor()) || !currentUser.equals(task.getAssignee())){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
task.setAssignee(assigneeCandidate);
taskService.update(taskId, TaskVO.builder().assigneeId(assigneeCandidate.getId()).build());
response.setStatus(HttpServletResponse.SC_OK);
}
@RequestMapping(path = "/update-task", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public void doModifyTask(
final @RequestParam(value = "newMessage") String newMessage,
final @RequestParam(value = "taskId") Long taskId,
HttpServletResponse response){
Task task = taskService.getTaskById(taskId); // get task by id
if(task == null){
// invalid taskId - how can I communicate to the client more details about the response error?
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
User currentUser = userService.getCurrentUser();
if(currentUser == null || !currentUser.equals(task.getAuthor()) || !currentUser.equals(task.getAssignee())){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
task.setMessage(newMessage);
taskService.update(taskId, TaskVO.builder().message(newMessage).build());
response.setStatus(HttpServletResponse.SC_OK);
}
@RequestMapping(path = "/delete-task", method = RequestMethod.DELETE, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public void doDeleteTask(
final @RequestParam(value = "taskId") Long taskId,
HttpServletResponse response){
Task task = taskService.getTaskById(taskId); // get task by id
if(task == null){
// invalid taskId - how can I communicate to the client more details about the response error?
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
User currentUser = userService.getCurrentUser();
if(currentUser == null || !currentUser.equals(task.getAuthor())){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
taskService.delete(taskId);
response.setStatus(HttpServletResponse.SC_OK);
}
@RequestMapping(path = "/list-tasks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Task> listTasks() {
return taskService.list();
}
}
| true |
33481de9cec598618429abc102b4e18dbb6596d6 | Java | krdyial/mvn_01 | /mvn_01/src/main/java/com/firstmaven01/RadioButtonExercise.java | UTF-8 | 2,188 | 2.578125 | 3 | [] | no_license | package com.firstmaven01;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import com.github.javafaker.Faker;
import io.github.bonigarcia.wdm.WebDriverManager;
public class RadioButtonExercise {
// 1. Create a class : RadioButton
// 2. Complete the following task.
// 1.Go to https://www.facebook.com/
// 3.Click on Create an Account button
// 4.Locate the elements of radio buttons
// 5.Then click on the radio buttons for your gender if they are not selected
@Test
public void radioButtonTest() throws Exception {
WebDriverManager.edgedriver().setup();
WebDriver driver= new EdgeDriver();
driver.get("https://www.facebook.com/");
try {
driver.findElement(By.xpath("//*[text()='Alle akzeptieren']")).click();
} catch (Exception e) {
e.getMessage();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.linkText("Neues Konto erstellen")).click();
Thread.sleep(5000);
driver.findElement(By.xpath("(//input[@type='text'])[2]")).sendKeys("Ali");
Thread.sleep(2000);
//driver.findElement(By.xpath("//input[@name='lastname']")).sendKeys(faker.name().lastName());
//driver.findElement(By.xpath("//input[@name='reg_email__']")).sendKeys(faker.funnyName()+"@gmail.com");
driver.findElement(By.xpath("//input[@name='reg_passwd__']")).sendKeys("123456987");
driver.findElement(By.xpath("//select/option[@value='15']")).click();
driver.findElement(By.xpath("(//select/option[@value='12'])[2]")).click();
driver.findElement(By.xpath("//select/option[@value='1988']")).click();
//WebElement weiblichRadioButton =driver.findElement(By.id("u_2_2_Us"));
Thread.sleep(2000);
WebElement männlichButton= driver.findElement(By.xpath("(//input[@type='radio'])[2]"));
männlichButton.click();
Thread.sleep(2000);
Assert.assertTrue(männlichButton.isSelected());
}
}
| true |
86fd60357c7725b9927b94ef1c4861b7e0d06e25 | Java | nwlongnecker/MutationTestingDSL | /src/mut/mutator/MutationRunner.java | UTF-8 | 10,409 | 2.546875 | 3 | [] | no_license | package mut.mutator;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashSet;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import mut.files.InMemoryFileManager;
import mut.files.InMemoryFileSystem;
import mut.interpreter.InterpreterState;
import mut.junit.MutatorJUnitRunner;
import mut.statistics.StatisticsCollector;
import mut.statistics.Mutation;
import mut.util.Msg;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
/**
* The class in charge of doing the mutations. Extends thread so it can be started as a separate for performance reasons.
* When running tests, first compiles and tests the original source code, then attempts to do all the mutations specified.
* @author Nathan Longnecker
*/
public class MutationRunner extends Thread {
private final Collection<String> sourceFiles;
private final Collection<String> testFiles;
private final Collection<String> mutateFrom;
private final Collection<String> mutateTo;
private final JavaCompiler compiler;
private final InMemoryFileManager fileManager;
private final InMemoryFileSystem fileSystem;
private final Msg msg;
private final StatisticsCollector statistics;
/**
* Readies a new mutation thread
* @param state The state of the mutator
* @param mutateFrom A list of symbols to mutate from
* @param mutateTo A list of symbols to mutate to
* @param fileManager The file manager to use when compiling
* @param statistics The statistics object to record results in
*/
public MutationRunner(InterpreterState state, Collection<String> mutateFrom, Collection<String> mutateTo, InMemoryFileManager fileManager, StatisticsCollector statistics) {
sourceFiles = state.getSourceFiles();
testFiles = state.getTestFiles();
this.mutateFrom = mutateFrom;
this.mutateTo = mutateTo;
this.compiler = ToolProvider.getSystemJavaCompiler();
this.fileManager = fileManager;
this.fileSystem = fileManager.getFileSystem();
this.msg = state.getMsg();
this.statistics = statistics;
}
@Override
public void run() {
if (testFiles.isEmpty()) {
msg.err("No tests files!");
return;
}
print("Mutating " + getMutationStrings(true) + " to " + getMutationStrings(false) + " in files " + getShortFileNames(sourceFiles) + " with tests " + getShortFileNames(testFiles));
// Ensure the tests pass normally
Collection<String> compileFiles = new HashSet<String>();
compileFiles.addAll(sourceFiles);
compileFiles.addAll(testFiles);
if(!compile(compileFiles)) {
msg.err(getId() + ": Supplied code does not compile!");
return;
}
MutatorJUnitRunner origTestRunner = new MutatorJUnitRunner(fileManager.getClassLoader(), fileSystem, msg);
Result originalResult = null;
PrintStream stdErr = System.err;
PrintStream stdOut = System.out;
try {
// Hide error messages from running the tests
// This is not optimal, if there is a problem while running the tests it causes problems
System.setErr(new PrintStream(new ByteArrayOutputStream()));
System.setOut(new PrintStream(new ByteArrayOutputStream()));
originalResult = origTestRunner.runTests(testFiles);
} catch (Exception e) {
System.setOut(stdOut);
print("Error running tests on unmutated code");
e.printStackTrace(System.err);
return;
} finally {
// Reset standard error and standard out
System.setErr(stdErr);
System.setOut(stdOut);
}
if (originalResult.wasSuccessful()) {
if(msg.verbosity >= Msg.NORMAL) {
print("Tests pass on unmutated code: check");
}
} else {
msg.err(getId() + ": Tests do not pass on unmutated code");
if (msg.verbosity >= Msg.SPARSE) {
msg.err(getId() + originalResult.getFailureCount() + " tests failed!");
for (Failure fail : originalResult.getFailures()) {
msg.err(getId() + fail.getMessage() + " " + fail.getDescription().getDisplayName() + " " + fail.getTrace());
}
}
return;
}
// Code successfully compiled and the tests all passed, so it's safe to do mutations
// Do the mutations
for (String from : mutateFrom) {
for (String to : mutateTo) {
if (!from.equals(to)) {
if(msg.verbosity >= Msg.NORMAL) {
print("Mutating " + from + " to " + to);
}
for(String filename : sourceFiles) {
// Search for the symbol we're mutating from in each of the source files
String originalSourceContents = fileSystem.getOriginalSourceFile(filename);
int currentReplacementIndex = originalSourceContents.indexOf(from);
while (currentReplacementIndex > -1) {
// Mutate the code
String mutatedSourceContents = originalSourceContents.substring(0, currentReplacementIndex) +
originalSourceContents.substring(currentReplacementIndex).replaceFirst(escapeSpecialChars(from), to);
fileSystem.addFile(filename, mutatedSourceContents);
String line = getLocInSourceFromIndex(currentReplacementIndex, originalSourceContents);
if(compile(sourceFiles)) {
if (msg.verbosity >= Msg.VERBOSE) {
print(getShortFilename(filename) + ": Testing with " + getShortFileNames(testFiles));
}
MutatorJUnitRunner testRunner = new MutatorJUnitRunner(fileManager.getClassLoader(), fileSystem, msg);
try {
// Hide error messages from running the tests
// This is not optimal, if there is a problem while running the tests it causes problems
System.setErr(new PrintStream(new ByteArrayOutputStream()));
System.setOut(new PrintStream(new ByteArrayOutputStream()));
if (testRunner.runTests(testFiles).wasSuccessful()) {
statistics.logSurvivor(filename, new Mutation(line, from, to));
print(getShortFilename(filename) + " " + line + ": Mutant survived when mutating " + from + " to " + to);
} else {
statistics.logKilled(filename, new Mutation(line, from, to));
if(msg.verbosity >= Msg.NORMAL) {
print(getShortFilename(filename) + " " + line + ": Tests failed, mutant killed");
}
}
} catch (Exception e) {
System.setOut(stdOut);
print(getShortFilename(filename) + " " + line + ": Error running tests when mutating " + from + " to " + to);
e.printStackTrace(stdErr);
} finally {
// Reset standard error and standard out
System.setErr(stdErr);
System.setOut(stdOut);
}
} else {
statistics.logStillborn(filename, new Mutation(line, from, to));
if (msg.verbosity >= Msg.NORMAL) {
print(getShortFilename(filename) + " " + line + ": Stillborn mutant");
}
}
currentReplacementIndex = originalSourceContents.indexOf(from, currentReplacementIndex + 1);
}
// Revert to the original source
fileSystem.addFile(filename, originalSourceContents);
compile(sourceFiles);
}
}
}
}
// Finished!
print("done");
}
/**
* Escape special characters in the symbol so the replacement works as expected
* @param in The symbol to escape
* @return The escaped symbol
*/
private String escapeSpecialChars(String in) {
return in.replaceAll("(?=[]\\[+&|!(){}^\"~*?:\\\\-])", "\\\\");
}
/**
* Identifies the line number in the source file
* @param index The index to search for
* @param originalSourceContents The contents to search for the line number
* @return The line number in the source
*/
private String getLocInSourceFromIndex(int index, String originalSourceContents) {
int numLines = originalSourceContents.substring(0, index).split("\r?\n").length;
return "line " + numLines;
}
/**
* Compiles a list of filenames
* @param filenames The filenames to compile
* @return Whether the compiliation was successful
*/
private boolean compile(Collection<String> filenames) {
final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
Collection<JavaFileObject> files = null;
try {
files = fileManager.getJavaFileObjectsForInputFromStrings(filenames, JavaFileObject.Kind.SOURCE);
} catch (IOException e) {
e.printStackTrace();
}
if (msg.verbosity >= Msg.VERBOSE) {
for (String filename : filenames) {
print("Compiling " + filename);
}
}
boolean success = compiler.getTask(null, fileManager, diagnostics, null, null, files).call();
if (msg.verbosity >= Msg.VERBOSE) {
print("Compiled Successfully: " + success);
}
for(Diagnostic<? extends JavaFileObject> d: diagnostics.getDiagnostics()) {
if (msg.verbosity >= Msg.NORMAL || d.getCode().equals("compiler.err.cant.resolve.location")) {
msg.err(getId() + ": " + d.getMessage(null));
}
}
return success;
}
/**
* Prints a message with the id number of this thread
* @param message The message to print
*/
private void print(String message) {
msg.msgln(getId() + ": " + message);
}
/**
* Converts the from or the to symbols to a human readable list
* @param fromStrings Whether to print the from strings
* @return Return the human readable list
*/
private String getMutationStrings(boolean fromStrings) {
StringBuilder sb = new StringBuilder();
if (fromStrings) {
for(String mutation: mutateFrom) {
sb.append(',');
sb.append(mutation);
}
} else {
for(String mutation: mutateTo) {
sb.append(',');
sb.append(mutation);
}
}
final String ret;
if (sb.length() > 0) {
ret = sb.toString().substring(1);
} else {
ret = "";
}
return ret;
}
/**
* Gets the short names of each file
* @param names The full filenames of each file
* @return A list of just the shortened filenames
*/
private String getShortFileNames(Collection<String> names) {
StringBuilder sb = new StringBuilder();
for(String name: names) {
sb.append(", ");
sb.append(getShortFilename(name));
}
final String ret;
if (sb.length() > 0) {
ret = sb.toString().substring(2);
} else {
ret = "";
}
return ret;
}
/**
* Gets the short version of a filename
* @param name The long filename
* @return The short filename
*/
private String getShortFilename(String name) {
File f = new File(name);
return f.getName();
}
}
| true |
babb5ba62f35ca9bb400915f264eb9c82dfd785b | Java | denis554/drools | /drools-core/src/test/java/org/drools/core/util/RBTreeTest.java | UTF-8 | 9,135 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.util;
import org.drools.core.util.RBTree.Node;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
public class RBTreeTest {
@Test
public void testFindNearestNode() {
RBTree<Integer, String> tree = new RBTree<Integer, String>();
tree.insert( 10, "" + 10 );
tree.insert( 20, "" + 20 );
tree.insert( 25, "" + 25 );
tree.insert( 15, "" + 15 );
tree.insert( 5, "" + 5 );
assertEquals(5, (int)tree.findNearestNode(2, false, RBTree.Boundary.LOWER).key);
assertEquals(null, tree.findNearestNode(2, false, RBTree.Boundary.UPPER));
assertEquals(5, (int)tree.findNearestNode(2, true, RBTree.Boundary.LOWER).key);
assertEquals(null, tree.findNearestNode(2, true, RBTree.Boundary.UPPER));
assertEquals(10, (int)tree.findNearestNode(5, false, RBTree.Boundary.LOWER).key);
assertEquals(null, tree.findNearestNode(5, false, RBTree.Boundary.UPPER));
assertEquals(5, (int)tree.findNearestNode(5, true, RBTree.Boundary.LOWER).key);
assertEquals(5, (int)tree.findNearestNode(5, true, RBTree.Boundary.UPPER).key);
assertEquals(15, (int)tree.findNearestNode(12, false, RBTree.Boundary.LOWER).key);
assertEquals(10, (int)tree.findNearestNode(12, false, RBTree.Boundary.UPPER).key);
assertEquals(20, (int)tree.findNearestNode(15, false, RBTree.Boundary.LOWER).key);
assertEquals(10, (int)tree.findNearestNode(15, false, RBTree.Boundary.UPPER).key);
assertEquals(15, (int)tree.findNearestNode(15, true, RBTree.Boundary.UPPER).key);
assertEquals(15, (int)tree.findNearestNode(15, true, RBTree.Boundary.LOWER).key);
assertEquals(20, (int)tree.findNearestNode(25, false, RBTree.Boundary.UPPER).key);
assertEquals(null, tree.findNearestNode(25, false, RBTree.Boundary.LOWER));
assertEquals(25, (int)tree.findNearestNode(25, true, RBTree.Boundary.LOWER).key);
assertEquals(25, (int)tree.findNearestNode(25, true, RBTree.Boundary.UPPER).key);
assertEquals(25, (int)tree.findNearestNode(27, false, RBTree.Boundary.UPPER).key);
assertEquals(null, tree.findNearestNode(27, false, RBTree.Boundary.LOWER));
assertEquals(25, (int)tree.findNearestNode(27, true, RBTree.Boundary.UPPER).key);
assertEquals(null, tree.findNearestNode(27, true, RBTree.Boundary.LOWER));
}
@Test
public void testRange() {
RBTree<Integer, String> tree = new RBTree<Integer, String>();
tree.insert( 10, "" + 10 );
tree.insert( 20, "" + 20 );
tree.insert( 25, "" + 25 );
tree.insert( 15, "" + 15 );
tree.insert( 5, "" + 5 );
FastIterator fastIterator = tree.range(2, true, 15, false);
Node<Integer, String> node = (Node<Integer, String>)fastIterator.next(null);
assertEquals(5, (int)node.key);
node = (Node<Integer, String>)fastIterator.next(node);
assertEquals(10, (int)node.key);
node = (Node<Integer, String>)fastIterator.next(node);
assertNull(node);
fastIterator = tree.range(2, true, 5, false);
node = (Node<Integer, String>)fastIterator.next(null);
assertNull(node);
fastIterator = tree.range(5, false, 35, false);
node = (Node<Integer, String>)fastIterator.next(null);
assertEquals(10, (int)node.key);
node = (Node<Integer, String>)fastIterator.next(node);
assertEquals(15, (int)node.key);
node = (Node<Integer, String>)fastIterator.next(node);
assertEquals(20, (int)node.key);
node = (Node<Integer, String>)fastIterator.next(node);
assertEquals(25, (int)node.key);
node = (Node<Integer, String>)fastIterator.next(node);
assertNull(node);
}
@Test
public void testIterator() {
final int ITEMS = 10000;
RBTree<Integer, String> tree = new RBTree<Integer, String>();
Random random = new Random(0);
for (int i = 0; i < ITEMS; i++) {
int key = random.nextInt();
tree.insert( key, "" + key );
}
int i = 0;
FastIterator fastIterator = tree.fastIterator();
int lastKey = Integer.MIN_VALUE;
for (Node<Integer, String> node = (Node<Integer, String>)fastIterator.next(null); node != null; node = (Node<Integer, String>)fastIterator.next(node)) {
int currentKey = node.key;
if (currentKey < lastKey) {
fail(currentKey + " should be greater than " + lastKey);
}
lastKey = currentKey;
i++;
}
assertEquals(ITEMS, i);
}
@Test @Ignore
public void testLargeData() {
int range = 6000000;
for ( int i = 0; i < 10; i++ ) {
// produces duplicate entry, isolated in test1
long startTime = System.currentTimeMillis();
generateAndTest( 90000, range-90000, range, 1 );
long endTime = System.currentTimeMillis();
System.out.println( endTime - startTime );
}
}
@Test @Ignore
public void testLargeData2() {
int range = 6000000;
for ( int i = 0; i < 10; i++ ) {
// produces duplicate entry, isolated in test1
long startTime = System.currentTimeMillis();
generateAndTest2( 90000, range-90000, range, 1 );
long endTime = System.currentTimeMillis();
System.out.println( endTime - startTime );
}
}
public void generateAndTest(int start,
int end,
int range,
int increment) {
//System.out.println( "generate tree" );
RBTree<Integer, String> tree = new RBTree<Integer, String>();
for ( int i = 0; i <= range; i = i + increment ) {
tree.insert( i, "" + i );
}
//System.out.println( "test data with tree" );
checkResults( tree,
range,
start,
end,
increment );
//tree.print();
}
public void generateAndTest2(int start,
int end,
int range,
int increment) {
//System.out.println( "generate tree" );
//RBTree<Integer, String> tree = new RBTree<Integer, String>();
TreeMap<Integer, String> tree = new TreeMap<Integer, String>();
for ( int i = 0; i <= range; i = i + increment ) {
tree.put( i, "" + i );
}
//System.out.println( "test data with tree" );
checkResults2( tree,
range,
start,
end,
increment );
//tree.print();
}
public void checkResults(RBTree<Integer, String> tree,
int range,
int start,
int end,
int increment) {
FastIterator it = tree.range( start, true, end, true );
Entry entry = null;
int i = 0;
List<Integer> actual = new ArrayList<Integer>();
//System.out.println( start + ":" + end + ":" + (((end - start) / increment) + 1) );
while ( (entry = it.next( entry )) != null ) {
Node<Integer, String> node = (Node<Integer, String>) entry;
}
for ( i = 0; i < range; i = i + increment ) {
tree.delete(i);
}
}
public void checkResults2(TreeMap<Integer, String> tree,
int range,
int start,
int end,
int increment) {
//FastIterator it = tree.range( start, true, end, true );
SortedMap<Integer, String> map = tree.subMap( start, end );
int i = 0;
List<Integer> actual = new ArrayList<Integer>();
for (Iterator<java.util.Map.Entry<Integer, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
java.util.Map.Entry<Integer, String> entry = it.next();
}
for ( i = 0; i < range; i = i + increment ) {
tree.remove( i );
}
}
}
| true |
ccbbc5f1bded9f98c05a26ad1111dd93b7f4c0ce | Java | keeperlibofan/oapi-sdk-java | /larksuite-oapi/src/main/java/com/larksuite/oapi/service/calendar/v4/model/FreebusyListResult.java | UTF-8 | 453 | 1.765625 | 2 | [
"Apache-2.0"
] | permissive | // Code generated by lark suite oapi sdk gen
package com.larksuite.oapi.service.calendar.v4.model;
import com.google.gson.annotations.SerializedName;
public class FreebusyListResult {
@SerializedName("freebusy_list")
private Freebusy[] freebusyList;
public Freebusy[] getFreebusyList() {
return this.freebusyList;
}
public void setFreebusyList(Freebusy[] freebusyList) {
this.freebusyList = freebusyList;
}
}
| true |
2418e32a0ffef6f9c2455c830dfb502e9073476e | Java | MasashiSuyama/MyWebSite | /Project/src/dao/ItemDAO.java | UTF-8 | 14,109 | 2.96875 | 3 | [] | no_license | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import base.DBManager;
import beans.ItemDataBeans;
public class ItemDAO {
/**
* idが一致する商品情報を削除する
*/
public void deleteItem(int id) throws SQLException {
Connection con = null;
try {
// データベースへ接続
con = DBManager.getConnection();
// SELECT文を準備
String sql = "DELETE FROM item WHERE id = ?";
// SELECTを実行し、ユーザ情報を削除
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setInt(1, id);
pStmt.executeUpdate();
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 商品検索
*/
public ArrayList<ItemDataBeans> getItemBySearch
(String searchItemName, String lowItemCost, String highItemCost, int pageNum, int pageMaxItemCount) throws SQLException {
Connection con = null;
try {
int startItemNum = (pageNum - 1) * pageMaxItemCount;
con = DBManager.getConnection();
// SELECT文を準備
String sql = "SELECT * FROM item where name like '%" + searchItemName + "%'";
if(!lowItemCost.equals("")) {
sql += " and price >= " + lowItemCost;
}
if(!highItemCost.equals("")) {
sql += " and price <= " + highItemCost;
}
sql += " ORDER BY id ASC LIMIT "+ startItemNum + "," + pageMaxItemCount;
// SELECTを実行し、結果表を取得
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ArrayList<ItemDataBeans> itemList = new ArrayList<ItemDataBeans>();
while (rs.next()) {
ItemDataBeans idb = new ItemDataBeans();
idb.setId(rs.getInt("id"));
idb.setName(rs.getString("name"));
idb.setPrice(rs.getInt("price"));
idb.setStock(rs.getInt("stock"));
idb.setFileName(rs.getString("file_name"));
itemList.add(idb);
}
return itemList;
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 検索から商品総数を取得
*
*/
public static double getItemCount(String searchItemName, String lowItemCost, String highItemCost) throws SQLException {
Connection con = null;
try {
con = DBManager.getConnection();
// SELECT文を準備
String sql = "select count(*) as cnt from item where name like '%" + searchItemName + "%'";
if(!lowItemCost.equals("")) {
sql += " and price >= '" + lowItemCost + "'";
}
if(!highItemCost.equals("")) {
sql += " and price <= '" + highItemCost + "'";
}
// SELECTを実行し、結果表を取得
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
double itemCount = 0;
while (rs.next()) {
itemCount = Double.parseDouble(rs.getString("cnt"));
}
return itemCount;
} catch (Exception e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 販売個数順で引数指定分のItemDataBeansを取得
*/
public static ArrayList<ItemDataBeans> getPopularItem(int limit) throws SQLException {
Connection con = null;
PreparedStatement st = null;
try {
con = DBManager.getConnection();
st = con.prepareStatement("SELECT * FROM item ORDER BY buy_sum DESC,id DESC LIMIT ? ");
st.setInt(1, limit);
ResultSet rs = st.executeQuery();
ArrayList<ItemDataBeans> itemList = new ArrayList<ItemDataBeans>();
while (rs.next()) {
ItemDataBeans item = new ItemDataBeans();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setPrice(rs.getInt("price"));
item.setFileName(rs.getString("file_name"));
itemList.add(item);
}
return itemList;
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 商品マスタ総数を取得
*/
public static double getProductAll() throws SQLException {
Connection con = null;
PreparedStatement st = null;
try {
con = DBManager.getConnection();
st = con.prepareStatement("select count(*) as cnt from item");
ResultSet rs = st.executeQuery();
double productAll = 0;
while (rs.next()) {
productAll = Double.parseDouble(rs.getString("cnt"));
}
return productAll;
} catch (Exception e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 商品マスタ情報をページ表示分、取得する
*/
public ArrayList<ItemDataBeans> getProducts(int pageNum, int pageMaxUserCount) throws SQLException {
Connection con = null;
PreparedStatement st = null;
try {
int startUserNum = (pageNum - 1) * pageMaxUserCount;
con = DBManager.getConnection();
st = con.prepareStatement("SELECT * FROM item ORDER BY id ASC LIMIT ?,?");
st.setInt(1, startUserNum);
st.setInt(2, pageMaxUserCount);
ResultSet rs = st.executeQuery();
ArrayList<ItemDataBeans> productList = new ArrayList<ItemDataBeans>();
while (rs.next()) {
ItemDataBeans idb = new ItemDataBeans();
idb.setId(rs.getInt("id"));
idb.setName(rs.getString("name"));
idb.setPrice(rs.getInt("price"));
idb.setStock(rs.getInt("stock"));
productList.add(idb);
}
return productList;
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* ランダムで引数指定分のItemDataBeansを取得
*/
public static ArrayList<ItemDataBeans> getRandItem(int limit) throws SQLException {
Connection con = null;
PreparedStatement st = null;
try {
con = DBManager.getConnection();
st = con.prepareStatement("SELECT * FROM item ORDER BY RAND() LIMIT ? ");
st.setInt(1, limit);
ResultSet rs = st.executeQuery();
ArrayList<ItemDataBeans> itemList = new ArrayList<ItemDataBeans>();
while (rs.next()) {
ItemDataBeans item = new ItemDataBeans();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setPrice(rs.getInt("price"));
item.setFileName(rs.getString("file_name"));
itemList.add(item);
}
return itemList;
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* idが一致する商品情報を全て返す
*/
public static ItemDataBeans findItemInfo(int id) throws SQLException{
Connection con = null;
try {
// データベースへ接続
con = DBManager.getConnection();
// SELECT文を準備
String sql = "SELECT * FROM item WHERE id = ?";
// SELECTを実行し、結果表を取得
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setInt(1, id);
ResultSet rs = pStmt.executeQuery();
// 主キーに紐づくレコードは1件のみなので、rs.next()は1回だけ行う
if (!rs.next()) {
return null;
}
String nameData = rs.getString("name");
String detailData = rs.getString("detail");
Boolean eggAllergyData = rs.getBoolean("allergy_egg");
Boolean wheatAllergyData = rs.getBoolean("allergy_wheat");
Boolean milkAllergyData = rs.getBoolean("allergy_milk");
String allergyOtherData = rs.getString("allergy_other");
int priceData = rs.getInt("price");
String fileNameData = rs.getString("file_name");
int stockData = rs.getInt("stock");
int buySumData = rs.getInt("buy_sum");
return new ItemDataBeans(id, nameData, detailData, eggAllergyData, wheatAllergyData, milkAllergyData,
allergyOtherData, priceData, fileNameData, stockData, buySumData);
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 削除する商品情報を削除済み商品に登録する
*/
public void insertDeleteItem(ItemDataBeans idb) throws SQLException {
Connection con = null;
try {
// データベースへ接続
con = DBManager.getConnection();
//INSERT文を準備
String sql = "insert into item_delete(item_id, name, detail, file_name, allergy_egg, allergy_wheat, allergy_milk, allergy_other, price, stock, buy_sum) "
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
// INSERTを実行
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setInt(1, idb.getId());
pStmt.setString(2, idb.getName());
pStmt.setString(3, idb.getDetail());
pStmt.setString(4, idb.getFileName());
pStmt.setBoolean(5, idb.getAllergyEgg());
pStmt.setBoolean(6, idb.getAllergyWheat());
pStmt.setBoolean(7, idb.getAllergyMilk());
pStmt.setString(8, idb.getAllergyOther());
pStmt.setInt(9, idb.getPrice());
pStmt.setInt(10, idb.getStock());
pStmt.setInt(11, idb.getBuySum());
pStmt.executeUpdate();
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 同じ商品名ですでに登録されているかをbooleanで返す (true:未登録 false:登録済み)
*/
public boolean newProduct(String productName) throws SQLException {
Connection con = null;
try {
// データベースへ接続
con = DBManager.getConnection();
// SELECT文を準備
String sql = "SELECT * FROM item WHERE name = ?";
// SELECTを実行し、結果表を取得
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString(1, productName);
ResultSet rs = pStmt.executeQuery();
// レコードが0件の場合未登録
if (!rs.next()) {
return true;
}
return false;
} catch (Exception e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 商品情報を登録する
*/
public void newProduct(String name, String detail, String photo,
boolean eggAllergy, boolean wheatAllergy, boolean milkAllergy, String allergyOther, int price, int stock) throws SQLException {
Connection con = null;
try {
// データベースへ接続
con = DBManager.getConnection();
//INSERT文を準備
String sql = "insert into item(name, detail, file_name, allergy_egg, allergy_wheat, allergy_milk, allergy_other, price, stock, buy_sum) "
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
// INSERTを実行
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString(1, name);
pStmt.setString(2, detail);
pStmt.setString(3, photo);
pStmt.setBoolean(4, eggAllergy);
pStmt.setBoolean(5, wheatAllergy);
pStmt.setBoolean(6, milkAllergy);
pStmt.setString(7, allergyOther);
pStmt.setInt(8, price);
pStmt.setInt(9, stock);
pStmt.executeUpdate();
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* idの一致する商品の在庫数・総販売個数を更新する
*/
public void productCountUpdate(int id, int buyCount) throws SQLException {
Connection con = null;
try {
// データベースへ接続
con = DBManager.getConnection();
//INSERT文を準備
String sql = "UPDATE item SET stock = ?, buy_sum = ? WHERE id = ?";
// INSERTを実行
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setInt(1, ItemDAO.findItemInfo(id).getStock() - buyCount);
pStmt.setInt(2, ItemDAO.findItemInfo(id).getBuySum() + buyCount);
pStmt.setInt(3, id);
pStmt.executeUpdate();
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* 商品情報を更新する
*/
public void productUpdate(int id, String name, String detail, String photo,boolean eggAllergy,
boolean wheatAllergy, boolean milkAllergy, String allergyOther, int stock, int sellAddNum) throws SQLException {
Connection con = null;
try {
// データベースへ接続
con = DBManager.getConnection();
//INSERT文を準備
String sql = "UPDATE item SET name = ?, detail = ?, file_name = ?, allergy_egg = ?, allergy_wheat = ?"
+ ", allergy_milk = ?, allergy_other = ?, stock = ? WHERE id = ?";
// INSERTを実行
PreparedStatement pStmt = con.prepareStatement(sql);
pStmt.setString(1, name);
pStmt.setString(2, detail);
pStmt.setString(3, photo);
pStmt.setBoolean(4, eggAllergy);
pStmt.setBoolean(5, wheatAllergy);
pStmt.setBoolean(6, milkAllergy);
pStmt.setString(7, allergyOther);
pStmt.setInt(8, (stock + sellAddNum) );
pStmt.setInt(9, id);
pStmt.executeUpdate();
} catch (SQLException e) {
throw new SQLException(e);
} finally {
if (con != null) {
con.close();
}
}
}
}
| true |
6f07eb4f4148d323b393d83680dc91d6e40973e0 | Java | vikinger/de.app.hskafeteria | /HsKafeteria/src/de/app/hskafeteria/httpclient/domain/AktionenList.java | UTF-8 | 1,030 | 2.40625 | 2 | [] | no_license | package de.app.hskafeteria.httpclient.domain;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
@Root(name="aktionenlist")
public class AktionenList {
@ElementList(inline=true)
private ArrayList<Aktion> aktionenList;
public AktionenList() {
aktionenList = new ArrayList<Aktion>();
}
public AktionenList(ArrayList<Aktion> aktionenList) {
this.aktionenList = aktionenList;
}
public boolean isEmpty() {
if (aktionenList.size() == 0)
return true;
else
return false;
}
public int size() {
return aktionenList.size();
}
public void addAktion(Aktion aktion) {
aktionenList.add(aktion);
}
public void addAktionenList(List<Aktion> aktionenList) {
aktionenList.addAll(aktionenList);
}
public ArrayList<Aktion> getAktionenList() {
return aktionenList;
}
public void setAktionenList(ArrayList<Aktion> aktionenList) {
this.aktionenList = aktionenList;
}
}
| true |
b20c1d1048f8acfedae12b221febd042d57ae386 | Java | shonachen/PPPanda2 | /app/src/main/java/com/pppanda/adapter/HomeListInfoAdapter.java | UTF-8 | 3,029 | 2.390625 | 2 | [] | no_license | package com.pppanda.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.pppanda.R;
import com.pppanda.entity.HomeListInfoEntity;
import java.util.ArrayList;
/**
* Created by Administrator on 2017/5/11.
*/
public class HomeListInfoAdapter extends BaseAdapter {
Context mContext;
ArrayList<HomeListInfoEntity> mList;
public HomeListInfoAdapter(Context mContext, ArrayList<HomeListInfoEntity> mList) {
this.mContext = mContext;
this.mList = mList;
}
@Override
public int getCount(){
return mList.size();
}
@Override
public HomeListInfoEntity getItem(int position){
return mList.get(position);
}
@Override
public long getItemId(int position){
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder = null;
if (convertView==null){
if(mContext == null){
Log.e("TAG", "mContex == null");
}
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.item_home_information,parent,false);
mViewHolder = new ViewHolder();
mViewHolder.hInfoHead = (ImageView)convertView.findViewById(R.id.iv_home_info_head);
mViewHolder.hInfoName = (TextView)convertView.findViewById(R.id.tv_home_info_name);
mViewHolder.hInfoContent = (TextView)convertView.findViewById(R.id.tv_home_info_content);
mViewHolder.hInfoYear = (TextView)convertView.findViewById(R.id.tv_home_info_year);
mViewHolder.hInfo = (RelativeLayout)convertView.findViewById(R.id.home_info);
convertView.setTag(mViewHolder);
}else {
mViewHolder = (ViewHolder)convertView.getTag();
}
final HomeListInfoEntity mHomeListInfoEntity = mList.get(position);
mViewHolder.hInfoHead.setImageResource(mHomeListInfoEntity.gethInfoHead());
mViewHolder.hInfoName.setText(mHomeListInfoEntity.gethInfoName());
mViewHolder.hInfoContent.setText(mHomeListInfoEntity.gethInfoContent());
mViewHolder.hInfoYear.setText(mHomeListInfoEntity.gethInfoYear());
mViewHolder.hInfo.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(mContext,mHomeListInfoEntity.gethInfoName(),Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
class ViewHolder{
ImageView hInfoHead;
TextView hInfoName;
TextView hInfoContent;
TextView hInfoYear;
RelativeLayout hInfo;
}
}
| true |
72bcb8adedf58a675ebce8b7653ce7e20b2f0808 | Java | imbichitra/ShowAllProjectOnGit | /app/src/main/java/com/bichi/showallprojectongit/view/UserFragment.java | UTF-8 | 3,941 | 1.992188 | 2 | [] | no_license | package com.bichi.showallprojectongit.view;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.bichi.showallprojectongit.R;
import com.bichi.showallprojectongit.databinding.FragmentUserBinding;
import com.bichi.showallprojectongit.model.User;
import com.bichi.showallprojectongit.network.ApiFactory;
import com.bichi.showallprojectongit.network.Resource;
import com.bichi.showallprojectongit.network.UserApi;
import com.bichi.showallprojectongit.repository.UserRepository;
import com.bichi.showallprojectongit.viewmodel.MyViewModelFactory;
import com.bichi.showallprojectongit.viewmodel.UserViewModel;
import java.util.List;
public class UserFragment extends Fragment implements MyInterface{
UserViewModel userViewModel;
public static final String TAG = UserFragment.class.getSimpleName();
FragmentUserBinding binding;
NavController navController = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater,R.layout.fragment_user,container,false);
//return inflater.inflate(R.layout.fragment_user, container, false);
UserApi api = ApiFactory.create();
UserRepository repository = new UserRepository(api);
MyViewModelFactory factory = new MyViewModelFactory(repository);
userViewModel = new ViewModelProvider(getActivity(),factory).get(UserViewModel.class);
binding.setViewModel(userViewModel);
binding.setMyinteface(this);
//observeResponse();
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
}
/* public void observeResponse() {
userViewModel.getResponse().observe(getViewLifecycleOwner(), new Observer<Resource<List<User>>>() {
@Override
public void onChanged(Resource<List<User>> listResource) {
if (listResource != null){
switch (listResource.status){
case LOADING:{
Log.d(TAG, "onChanged: PostsFragment: LOADING...");
break;
}
case SUCCESS:{
Log.d(TAG, "onChanged: PostsFragment: got posts."+listResource.data.get(0).getFullName());
navController.navigate(R.id.action_userFragment_to_userLisFragment);
break;
}
case ERROR:{
Log.d(TAG, "onChanged: PostsFragment: ERROR... " + listResource.message);
break;
}
}
}
}
});
}*/
@Override
public void onSubmitClick() {
if (userViewModel.userName != null &&!userViewModel.userName.isEmpty()) {
navController.navigate(R.id.action_userFragment_to_userLisFragment);
}else {
Toast.makeText(getContext(), "Enter username", Toast.LENGTH_SHORT).show();
}
}
@Override
public void userClicked(User user) {
}
} | true |
1cd693beda5e68a72dcdb37acf8043952409b11a | Java | rinaykumar/Store-Project | /backend/src/main/java/DAO/ItemsDAO.java | UTF-8 | 2,993 | 2.75 | 3 | [] | no_license | package DAO;
import DTO.AddItemDTO;
import DTO.ItemsListDTO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ItemsDAO {
private static ItemsDAO instance;
Gson gson = new GsonBuilder()
.create();
private ItemsDAO(){
}
// Open connection
MongoClient mongoClient = new MongoClient("localhost", 27017);
public void addItem(String item, double price) {
// Connect to mongo
MongoDatabase db = mongoClient.getDatabase("HW3Database");
MongoCollection<Document> itemsCollection = db.getCollection("Items");
// Create new DTO and convert to JSON
AddItemDTO newItemDTO = new AddItemDTO(item, price);
String itemJSON = gson.toJson(newItemDTO);
// Create new mongo Document from JSON
Document newItem = Document.parse(itemJSON);
// Add Document to Collection
itemsCollection.insertOne(newItem);
}
public void deleteItem(String item, double price) {
// Connect to mongo
MongoDatabase db = mongoClient.getDatabase("HW3Database");
MongoCollection<Document> itemsCollection = db.getCollection("Items");
// Create new DTO and convert to JSON
AddItemDTO newItemDTO = new AddItemDTO(item, price);
String itemJSON = gson.toJson(newItemDTO);
// Create new mongo Document from JSON
Document newItem = Document.parse(itemJSON);
// Delete Document from Collections
itemsCollection.findOneAndDelete(newItem);
}
public ItemsListDTO getAllItems() {
MongoDatabase db = mongoClient.getDatabase("HW3Database");
MongoCollection<Document> itemsCollection = db.getCollection("Items");
List<String> items = itemsCollection.find().into(new ArrayList<>())
.stream()
.map(document -> {
document.remove("_id");
return document.toJson();
})
.collect(Collectors.toList());
return new ItemsListDTO(items);
}
/*
public ItemsListDTO getAllUsers() {
MongoDatabase db = mongoClient.getDatabase("HW3Database");
MongoCollection<Document> itemsCollection = db.getCollection("Users");
List<String> items = itemsCollection.find().into(new ArrayList<>())
.stream()
.map(document -> {
document.remove("_id");
return document.toJson();
})
.collect(Collectors.toList());
return new ItemsListDTO(items);
}
*/
public static ItemsDAO getInstance() {
if(instance == null) {
instance = new ItemsDAO();
}
return instance;
}
} | true |
dda67bc1a57bd17edf2888e3061019698debd43b | Java | yoosername/jira-audit-demo | /src/main/java/example/app/events/AllEventsListener.java | UTF-8 | 14,037 | 1.914063 | 2 | [] | no_license | package example.app.events;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.event.DashboardViewEvent;
import com.atlassian.jira.event.ExportEvent;
import com.atlassian.jira.event.JiraEvent;
import com.atlassian.jira.event.ProjectCreatedEvent;
import com.atlassian.jira.event.ProjectDeletedEvent;
import com.atlassian.jira.event.ProjectUpdatedEvent;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.event.issue.IssueSearchEvent;
import com.atlassian.jira.event.issue.IssueViewEvent;
import com.atlassian.jira.event.issue.MentionIssueCommentEvent;
import com.atlassian.jira.event.issue.QuickBrowseEvent;
import com.atlassian.jira.event.issue.QuickSearchEvent;
import com.atlassian.jira.event.type.EventType;
import com.atlassian.jira.event.type.EventTypeManager;
import com.atlassian.jira.event.user.LoginEvent;
import com.atlassian.jira.event.user.LogoutEvent;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.jira.web.HttpServletVariables;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import example.app.models.AuditableEvent;
import example.app.services.AuditService;
/**
* Simple JIRA listener using the atlassian-event library
*/
@Component
public class AllEventsListener {
private static final Logger log = LoggerFactory.getLogger(AllEventsListener.class);
private final EventPublisher eventPublisher;
private final AuditService auditService;
private final EventTypeManager eventTypeManager;
private HttpServletVariables servletVars;
/**
* Constructor.
* @param eventPublisher injected {@code EventPublisher} implementation.
* @param auditService injected {@code AuditService} implementation.
* @param eventTypeManager injected {@code EventTypeManager} implementation.
*/
@Autowired
public AllEventsListener(
@ComponentImport EventPublisher eventPublisher,
AuditService auditService,
@ComponentImport EventTypeManager eventTypeManager,
@ComponentImport HttpServletVariables servletVars
)
{
this.eventPublisher = eventPublisher;
this.auditService = auditService;
this.eventTypeManager = eventTypeManager;
this.servletVars = servletVars;
}
/**
* Called when the plugin has been enabled.
* @throws Exception
*/
@PostConstruct
public void onPluginEnabled() throws Exception {
// register ourselves with the EventPublisher
log.debug("======================= AUDIT PLUGIN ENABLED ========================");
eventPublisher.register(this);
}
/**
* Called when the plugin is being disabled or removed.
* @throws Exception
*/
@PreDestroy
public void onPluginDisabled() throws Exception {
// unregister ourselves with the EventPublisher
eventPublisher.unregister(this);
log.debug("======================= AUDIT PLUGIN DISABLED ========================");
}
// https://developer.atlassian.com/jiradev/jira-platform/jira-architecture/jira-technical-overview/jira-specific-atlassian-events
// DONE: Add Dashboard view event
// DONE: Add login / logout events
// DONE: Add Project create / delete / modify events
// DONE: Add Issue create / delete / modify events
// DONE: Add Issue View events
// DONE: Add Export Events
// PARTIALLY DONE: Add Issue workflow events. = currently issue event with source = workflow
// DONE: Add JQL Search Events
// TODO: Add User modification events
private String getCurrentUri(){
HttpServletRequest req = servletVars.getHttpRequest();
return req.getRequestURI();
}
private String getCurrentReferer(){
HttpServletRequest req = servletVars.getHttpRequest();
return (req.getHeader("referer")!=null)?req.getHeader("referer"):"";
}
@EventListener
// For testing - show us all the different events when they fire
public void onJiraEvent(JiraEvent event) {
log.debug("got JIRA event {}", event);
}
private String getCurrentUserId(){
JiraAuthenticationContext context = ComponentAccessor.getJiraAuthenticationContext();
ApplicationUser user = context.getLoggedInUser();
String userId = (user != null) ? user.getUsername() : "unknown";
return userId;
}
/**
* Receives any {@code MentionIssueCommentEvent}s sent by JIRA.
* @param mentionIssueCommentEvent the MentionIssueCommentEvent passed to us
*/
@EventListener
public void onExportEvent(MentionIssueCommentEvent mentionIssueCommentEvent) {
Date timestamp = new Date();
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(mentionIssueCommentEvent.getFromUser().getUsername())
.withType("User Mention")
.withTypeDescription("from:"+mentionIssueCommentEvent.getFromUser()+",to:"+mentionIssueCommentEvent.getToUsers()+",msg:"+mentionIssueCommentEvent.getMentionText())
.isContentAffectedAction(true)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Receives any {@code ExportEvent}s sent by JIRA.
* @param exportEvent the ExportEvent passed to us
*/
@EventListener
public void onExportEvent(ExportEvent exportEvent) {
Date timestamp = exportEvent.getTime();
String name = exportEvent.calculateEventName();
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(getCurrentUserId())
.withType(name)
.withTypeDescription(exportEvent.getParams().toString())
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Receives any {@code IssueViewEvent}s sent by JIRA.
* @param IssueViewEvent the IssueViewEvent passed to us
*/
@EventListener
public void onQuickBrowseEvent(QuickBrowseEvent quickBrowseEvent) {
Date timestamp = quickBrowseEvent.getTime();
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(getCurrentUserId())
.withType("Quick Browse")
.withTypeDescription(quickBrowseEvent.getIssueKey())
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Receives any {@code QuickSearchEvent}s sent by JIRA.
* @param quickSearchEvent the QuickSearchEvent passed to us
*/
@EventListener
public void onQuickSearchEvent(QuickSearchEvent quickSearchEvent) {
Date timestamp = quickSearchEvent.getTime();
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(getCurrentUserId())
.withType("Quick Search")
.withTypeDescription(quickSearchEvent.getSearchString())
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Receives any {@code IssueSearchEvent}s sent by JIRA.
* @param issueSearchEvent the IssueSearchEvent passed to us
*/
@EventListener
public void onIssueSearchEvent(IssueSearchEvent issueSearchEvent) {
String type = issueSearchEvent.getType();
Date timestamp = issueSearchEvent.getTime();
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(getCurrentUserId())
.withType(type)
.withTypeDescription(issueSearchEvent.getQuery())
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Receives any {@code IssueViewEvent}s sent by JIRA.
* @param IssueViewEvent the IssueViewEvent passed to us
*/
@EventListener
public void onIssueViewEvent(IssueViewEvent issueViewEvent) {
Long eventTypeId = issueViewEvent.getId();
EventType type = eventTypeManager.getEventType(eventTypeId);
Date timestamp = issueViewEvent.getTime();
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(getCurrentUserId())
.withType(type.getName())
.withTypeDescription(issueViewEvent.getParams().toString())
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Receives any {@code DashboardViewEvent}s sent by JIRA.
* @param dashboardViewEvent the DashboardViewEvent passed to us
*/
@EventListener
public void onDashboardViewEvent(DashboardViewEvent dashboardViewEvent) {
String typeName = "Dashboard View";
Date timestamp = dashboardViewEvent.getTime();
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(getCurrentUserId())
.withType(typeName)
.withTypeDescription(dashboardViewEvent.getId().toString())
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Receives any {@code IssueEvent}s sent by JIRA.
* @param issueEvent the IssueEvent passed to us
*/
@EventListener
public void onIssueEvent(IssueEvent issueEvent) {
Long eventTypeId = issueEvent.getEventTypeId();
EventType type = eventTypeManager.getEventType(eventTypeId);
String typeName = type.getName();
ApplicationUser user = issueEvent.getUser();
Date timestamp = issueEvent.getTime();
String typeDescription = "";
try{
typeDescription = issueEvent.getParams().get("eventsource").toString();
}catch(Exception e){}
auditService.handleEvent(
new AuditableEvent()
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withUserId(user.getUsername())
.withType(typeName)
.withTypeDescription(typeDescription)
.withContentID(issueEvent.getIssue().getId())
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction((typeName.equals("Issue Deleted")?true:false))
.at(timestamp)
);
}
/**
* User Login Event
* Receives any {@code LoginEvent}s sent by JIRA.
* @param event the LoginEvent passed to us
*/
@EventListener
public void onLoginEvent(LoginEvent event) {
ApplicationUser user = event.getUser();
Date timestamp = event.getTime();
auditService.handleEvent(
new AuditableEvent()
.withUserId(user.getUsername())
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withType("Login")
.withTypeDescription("login")
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* User Logout Event
* Receives any {@code LogoutEvent}s sent by JIRA.
* @param event the LogoutEvent passed to us
*/
@EventListener
public void logoutEvent(LogoutEvent event) {
ApplicationUser user = event.getUser();
Date timestamp = event.getTime();
auditService.handleEvent(
new AuditableEvent()
.withUserId(user.getUsername())
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withType("Logout")
.withTypeDescription("logout")
.isContentAffectedAction(false)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Project created event
* Receives any {@code ProjectCreatedEvent}s sent by JIRA.
* @param event the ProjectCreatedEvent passed to us
*/
@EventListener
public void projectCreatedEvent(ProjectCreatedEvent event) {
ApplicationUser user = event.getUser();
Date timestamp = event.getTime();
Long id = event.getProject().getId();
auditService.handleEvent(
new AuditableEvent()
.withUserId(user.getUsername())
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withType("Project Created")
.withContentID(id)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
/**
* Project deleted event
* Receives any {@code ProjectDeletedEvent}s sent by JIRA.
* @param event the ProjectDeletedEvent passed to us
*/
@EventListener
public void projectDeletedEvent(ProjectDeletedEvent event) {
ApplicationUser user = event.getUser();
Date timestamp = event.getTime();
Long id = event.getProject().getId();
auditService.handleEvent(
new AuditableEvent()
.withUserId(user.getUsername())
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withType("Project Deleted")
.withContentID(id)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(true)
.at(timestamp)
);
}
/**
* Project updated event
* Receives any {@code ProjectUpdatedEvent}s sent by JIRA.
* @param event the ProjectUpdatedEvent passed to us
*/
@EventListener
public void projectUpdatedEvent(ProjectUpdatedEvent event) {
ApplicationUser user = event.getUser();
Date timestamp = event.getTime();
Long id = event.getProject().getId();
auditService.handleEvent(
new AuditableEvent()
.withUserId(user.getUsername())
.withReferer(getCurrentReferer())
.withUrl(getCurrentUri())
.withType("Project Updated")
.withContentID(id)
.withIsAnonymousAction(false)
.withIsAdminOnly(false)
.withIsDestructiveAction(false)
.at(timestamp)
);
}
} | true |
b7c26c2df461845a15ba3161a7bb1560c7d58600 | Java | shihongwei/pergesa | /pergesa-msg/pergesa-kafka/src/main/java/com/arto/kafka/consumer/strategy/KafkaConsumerStrategyFactory.java | UTF-8 | 3,173 | 2.59375 | 3 | [] | no_license | /**
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.arto.kafka.consumer.strategy;
import com.arto.event.bootstrap.EventBusFactory;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 消费策略工厂
*
* Created by xiong.j on 2017/1/20.
*/
public class KafkaConsumerStrategyFactory {
private static volatile KafkaConsumerStrategyFactory instance;
private final ConcurrentMap<Integer, SoftReference<KafkaConsumerStrategy>> strategyMap
= new ConcurrentHashMap<Integer, SoftReference<KafkaConsumerStrategy>>(3);
public static KafkaConsumerStrategyFactory getInstance(){
if (null == instance) {
synchronized (EventBusFactory.class) {
if (null == instance) {
instance = new KafkaConsumerStrategyFactory();
}
}
}
return instance;
}
/**
* 根据消费优先级生成不同的消费策略
*
* @param priority
* @return
*/
public KafkaConsumerStrategy getStrategy(final int priority){
if (strategyMap.containsKey(priority)) {
if (strategyMap.get(priority) != null) {
return strategyMap.get(priority).get();
}
}
return createStrategy(priority);
}
private synchronized KafkaConsumerStrategy createStrategy(final int priority) {
if (strategyMap.containsKey(priority)) {
if (strategyMap.get(priority) != null) {
return strategyMap.get(priority).get();
}
}
KafkaConsumerStrategy strategy;
switch (priority) {
case 1:
// 重要消息,重试三次后入库等待重试
strategy = new KafkaConsumerDefaultStrategy();
break;
case 2:
// 普通消息,重试三次后丢弃消息
strategy = new KafkaConsumerMediumPriorityStrategy();
break;
case 3:
// 不重要消息,出错即丢弃消息
strategy = new KafkaConsumerLowPriorityStrategy();
break;
default:
strategy = new KafkaConsumerDefaultStrategy();
}
strategyMap.put(priority, new SoftReference<KafkaConsumerStrategy>(strategy));
return strategy;
}
}
| true |
d5e432c3d7282542e135e5573ebf585994248d78 | Java | DrParadox7/forgottenRelicsDeobfuscated | /com/integral/forgottenrelics/packets/TelekinesisUseMessage.java | UTF-8 | 1,718 | 1.820313 | 2 | [] | no_license | /* */ package com.integral.forgottenrelics.packets;
/* */
/* */ import com.integral.forgottenrelics.Main;
/* */ import cpw.mods.fml.common.network.simpleimpl.IMessage;
/* */ import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
/* */ import cpw.mods.fml.common.network.simpleimpl.MessageContext;
/* */ import io.netty.buffer.ByteBuf;
/* */ import net.minecraft.entity.player.EntityPlayer;
/* */ import net.minecraft.entity.player.EntityPlayerMP;
/* */ import net.minecraft.item.ItemStack;
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class TelekinesisUseMessage
/* */ implements IMessage
/* */ {
/* */ public void fromBytes(ByteBuf buf) {}
/* */
/* */ public void toBytes(ByteBuf buf) {}
/* */
/* */ public static class Handler
/* */ implements IMessageHandler<TelekinesisUseMessage, IMessage>
/* */ {
/* */ public IMessage onMessage(TelekinesisUseMessage message, MessageContext ctx) {
/* 28 */ EntityPlayerMP entityPlayerMP = (ctx.getServerHandler()).playerEntity;
/* 29 */ ItemStack stack = entityPlayerMP.getCurrentEquippedItem();
/* */
/* 31 */ if (stack != null &&
/* 32 */ stack.getItem() == Main.itemTelekinesisTome) {
/* 33 */ Main.itemTelekinesisTome.onUsingTickAlt(stack, (EntityPlayer)entityPlayerMP, 0);
/* */ }
/* */
/* */
/* 37 */ return null;
/* */ }
/* */ }
/* */ }
/* Location: C:\Users\antro\Documents\forgottenRelicsDeobfuscated.jar!\com\integral\forgottenrelics\packets\TelekinesisUseMessage.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | true |
a2d4d733a6285c0f734e1113a9f49e5a3c1e3c90 | Java | setzamora/mars-rover | /src/main/java/au/com/buenosystems/marsrover/view/TerrainView.java | UTF-8 | 443 | 2.453125 | 2 | [] | no_license | package au.com.buenosystems.marsrover.view;
import au.com.buenosystems.marsrover.rover.Rover;
import au.com.buenosystems.marsrover.terrain.Terrain;
public abstract class TerrainView {
protected Rover rover;
protected Terrain terrain;
public void setRover(Rover rover) {
this.rover = rover;
}
public void setTerrain(Terrain terrain) {
this.terrain = terrain;
}
public abstract void render();
}
| true |
70dd9d2582ca540655d8f36a74123d4a8dd547c2 | Java | saracelik/LiterarnoUdruzenje-1 | /kp/paypal-ms/src/main/java/com/example/paypalms/controller/SubscriptionController.java | UTF-8 | 5,717 | 2 | 2 | [] | no_license | package com.example.paypalms.controller;
import com.example.paypalms.domain.Subscription;
import com.example.paypalms.domain.SubscriptionPlan;
import com.example.paypalms.domain.Transaction;
import com.example.paypalms.dto.SubscriptionDto;
import com.example.paypalms.dto.SubscriptionPlanDto;
import com.example.paypalms.dto.SubscriptionRequestDto;
import com.example.paypalms.dto.TransactionDto;
import com.example.paypalms.enums.SubscriptionStatus;
import com.example.paypalms.service.PaymentService;
import com.example.paypalms.service.SubscriptionPlanService;
import com.example.paypalms.service.SubscriptionService;
import com.paypal.base.rest.PayPalRESTException;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/subscriptions")
@Log4j2
@CrossOrigin(origins = "*", allowedHeaders = "*", maxAge = 3600)
public class SubscriptionController {
private SubscriptionPlanService subscriptionPlanService;
private PaymentService paymentService;
private SubscriptionService subscriptionService;
private RestTemplate restTemplate;
public SubscriptionController(SubscriptionPlanService subscriptionPlanService, PaymentService paymentService,
SubscriptionService subscriptionService, RestTemplate restTemplate) {
this.subscriptionPlanService = subscriptionPlanService;
this.paymentService = paymentService;
this.subscriptionService = subscriptionService;
this.restTemplate = restTemplate;
}
@PostMapping
public ResponseEntity<?> createBillingPlan(@RequestBody @Valid SubscriptionRequestDto subscriptionRequest) {
//CREATE A BILLING PLAN
Long subscriptionId;
try {
subscriptionId = paymentService.createBillingPlan(subscriptionRequest);
} catch (Exception exception) {
return ResponseEntity.badRequest().body(exception.getMessage());
}
//CREATE A BILLING AGREEMENT
String redirectUrl;
try {
redirectUrl = paymentService.createBillingAgreement(subscriptionRequest, subscriptionId);
} catch (Exception e) {
log.error("CANCELED | PayPal Subscription");
return ResponseEntity.badRequest().build();
}
log.info("COMPLETED | PayPal Subscription");
//redirect user to the paypal site
return ResponseEntity.ok(redirectUrl);
}
@GetMapping("/complete")
public ResponseEntity<?> completeSubscription(@RequestParam Long subscriptionId, @RequestParam String token) {
Subscription subscription;
try {
subscription = subscriptionService.findById(subscriptionId);
} catch (Exception exception) {
log.error(exception.getMessage());
throw exception;
}
String redirectUrl = null;
try {
redirectUrl = paymentService.executeBillingAgreement(subscription, token);
} catch (PayPalRESTException exception) {
exception.printStackTrace();
}
try {
HttpEntity<SubscriptionDto> entity = new HttpEntity<>(new SubscriptionDto(subscription));
ResponseEntity<String> responseEntity = restTemplate.postForEntity(redirectUrl, entity, String.class);
HttpHeaders headersRedirect = new HttpHeaders();
headersRedirect.add("Location", responseEntity.getBody());
headersRedirect.add("Access-Control-Allow-Origin", "*");
return new ResponseEntity<byte[]>(null, headersRedirect, HttpStatus.FOUND);
} catch (Exception exception) {
exception.printStackTrace();
log.error(exception);
}
return ResponseEntity.badRequest().build();
}
@GetMapping("/cancel")
public ResponseEntity<?> cancelBillingPlan(@RequestParam Long subscriptionId) {
Subscription subscription = subscriptionService.findById(subscriptionId);
subscription.setSubscriptionStatus(SubscriptionStatus.CANCELED);
subscriptionService.save(subscription);
try {
HttpEntity<SubscriptionDto> entity = new HttpEntity<>(new SubscriptionDto(subscription));
ResponseEntity<String> responseEntity = restTemplate.postForEntity(subscription.getCancelUrl(), entity, String.class);
HttpHeaders headersRedirect = new HttpHeaders();
headersRedirect.add("Location", responseEntity.getBody());
headersRedirect.add("Access-Control-Allow-Origin", "*");
return new ResponseEntity<byte[]>(null, headersRedirect, HttpStatus.FOUND);
} catch (Exception exception) {
exception.printStackTrace();
log.error(exception);
}
return ResponseEntity.badRequest().build();
}
@GetMapping("/{sellerEmail}")
public ResponseEntity<SubscriptionPlanDto[]> getSubscriptionPlansForSeller(@PathVariable String sellerEmail) {
List<SubscriptionPlan> subscriptionPlans = (ArrayList) subscriptionPlanService.findAllBySellerEmail(sellerEmail);
List<SubscriptionPlanDto> plans = subscriptionPlans.stream().map(SubscriptionPlanDto::new).collect(Collectors.toList());
SubscriptionPlanDto[] retVal = plans.toArray(new SubscriptionPlanDto[0]);
return ResponseEntity.ok(retVal);
}
}
| true |
78ec642f53dbdbb72e58ead915e48ed7abcd998b | Java | ezhov-da/quick-notes-web-app | /src/main/java/ru/ezhov/db/CookieUserCheck.java | UTF-8 | 1,336 | 2.34375 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ru.ezhov.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import ru.ezhov.User;
/**
*
* @author deonisius
*/
public class CookieUserCheck {
private String query = "select id, name, pass from V_E_users where name=?";
private String user;
public CookieUserCheck(String user) {
this.user = user;
}
public User getUser() throws SQLException, Exception {
DataSource dataSource = ConnectionDAO.getDataSource();
User userObject = null;
try (Connection connection = dataSource.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(query);) {
preparedStatement.setString(1, user);
try (ResultSet resultSet = preparedStatement.executeQuery();) {
while (resultSet.next()) {
userObject = new User(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3));
}
}
}
}
return userObject;
}
}
| true |
ea7fd6348206caf316770851f447d97d828368e4 | Java | lakecenter/intsmaze-1 | /intsmaze-z-core/src/main/java/com/intsmaze/spring/aop/SpringTest5.java | UTF-8 | 822 | 2.125 | 2 | [] | no_license | package com.intsmaze.spring.aop;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext2.xml")
//@ContextConfiguration("classpath:applicationContext3.xml")
public class SpringTest5 {
@Autowired
@Qualifier("orderDao")
private OrderDao orderDao;
@Autowired
@Qualifier("customerDao")
private CustomerDao customerDao;
@Test
public void demo1(){
orderDao.add();
orderDao.update();
orderDao.delete();
customerDao.add();
customerDao.update();
}
}
| true |
de6d6dc9c79c831a1f630cbfdd899ce634c1bbd3 | Java | feiyuu/Theme-Pack | /src/main/java/com/xyf/common/util/R.java | UTF-8 | 961 | 2.421875 | 2 | [] | no_license | package com.xyf.common.util;
import javafx.scene.image.Image;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class R {
public static URL getLayout(@Nonnull String name) {
return R.class.getClassLoader().getResource("layout/" + name);
}
private static InputStream getDrawable(@Nonnull String name) {
return R.class.getClassLoader().getResourceAsStream("drawable/" + name);
}
@Nonnull
public static Image getImage(@Nonnull String name) throws IOException {
try (InputStream inputStream = getDrawable(name)) {
return new Image(inputStream);
}
}
@Nonnull
public static Image getImage(@Nonnull File file) throws IOException {
try (InputStream inputStream = new FileInputStream(file)) {
return new Image(inputStream);
}
}
}
| true |
818bc4f0959c1f8675a7ffa8b3ab4a84eafc2a54 | Java | conorgilmer/radiolog | /java/RadioLogSwing/com/webwayz/Config.java | UTF-8 | 3,047 | 2.78125 | 3 | [] | no_license | /**
* @author $Author: Conor Gilmer $
* @version $Revision: 1 $
*
* Generic Config file recycled
* Could read from file, use Properties or Resource Bundles
* or set statically here
*/
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Config
{
/********** PUBLIC STATIC VARIABLES **********/
/* system information */
public static String systemName = "Radio Log Book";
public static String systemVersion = systemName+" Release 0_1";
public static String authorName = "Conor Gilmer <conor.gilmer@gmail.com>";
public static String websiteAddress = "www.conorgilmer.com/radio";
/* Locale and Timezone set */
public static Locale locale = new Locale("en","IE"); //ISO
public static TimeZone zone = new SimpleTimeZone(3600000,"IRL",
Calendar.MARCH,-1,Calendar.SUNDAY,3*60*60*1000,
Calendar.OCTOBER,-1,Calendar.SUNDAY,3*60*60*1000);
static java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd",Config.locale);
/* log file */
public static String logFile = "logs/RadioLogFile.log";
/* radio codes todo import in codes/ q codes etc */
// public static Hashtable radioCodes=new Hashtable();
/* DB Properties */
// public static String dbDriver = "org.gjt.mm.mysql.Driver";
// public static String dbURL = "jdbc:mysql://localhost/dbname";
// public static String dbServer = "localhost";
// public static String dbUser = "user";
// public static String dbPass = "";
// public static String dbDB = "dbname";
/* DB Properties read from resource bundle */
// public static ResourceBundle db = ResourceBundle.getBundle("db", locale);
// public static String dbDriver = db.getString("dbDriver");
// public static String dbURL = db.getString("dbUrl");
// public static String dbServer = db.getString("dbServer");
// public static String dbUser = db.getString("dbUser");
// public static String dbPass = db.getString("dbPass");
// public static String dbDB = "opendata";
/* DB Properties read from property file
* need to call the function getDBProp to set the values
*/
public static String dbDriver = null;
public static String dbURL = null;
public static String dbServer = null;
public static String dbUser = null;
public static String dbPass = null;
public static String dbTable = null;
/* get read from file */
public static void getDBProp() {
Properties props = new Properties();
try {
props.load(new FileInputStream("db.properties"));
dbUser = props.getProperty("dbUser");
dbPass = props.getProperty("dbPass");
dbServer = props.getProperty("dbServer");
dbURL = props.getProperty("dbUrl");
dbDriver = props.getProperty("dbDriver");
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
System.out.println("File IO Error");
e.printStackTrace();
}
} /* end of getDBProp */
}
| true |
657ae25ec59a65ab3f91df3ddaee616145f9dc48 | Java | vijaygk2016/WebServices_Framework_UsingRestAssured | /src/test/java/com/projectName/testscripts/TC_001.java | UTF-8 | 1,424 | 1.953125 | 2 | [] | no_license | package com.projectName.testscripts;
import org.testng.annotations.Test;
import com.projectName.utills.EndpointURL;
import com.projectName.utills.URL;
import com.projectName.webservices.methods.Webservices;
import io.restassured.response.Response;
public class TC_001 {
Response response;
@Test
public void verifyGetLIST_USERS(){
System.out.println("-------***********---------");
String url = URL.fixURL+EndpointURL.LIST_USERS.getResourcePath();
System.out.println(url);
response=Webservices.Get(url);
System.out.println(response.getBody().asString());
System.out.println("-------***********---------");
System.out.println("");
}
@Test
public void verifyGetSINGLE_USER(){
System.out.println("-------***********---------");
String url = URL.fixURL+EndpointURL.SINGLE_USER.getResourcePath();
System.out.println(url);
response=Webservices.Get(url);
System.out.println(response.getBody().asString());
System.out.println("-------***********---------");
System.out.println("");
}
@Test
public void verifyGetLIST_USERS_PAGE_NUMBERS(){
System.out.println("-------***********---------");
String url = URL.fixURL+EndpointURL.LIST_USERS_PAGE_NUMBERS.getResourcePath("6");
System.out.println(url);
response=Webservices.Get(url);
System.out.println(response.getBody().asString());
System.out.println("-------***********---------");
System.out.println("");
}
}
| true |
47f34b2d295c2d22688c3e3bf509e7240a1355a9 | Java | cpijavagroup2/SMS2 | /src/com/dao/UserDao.java | UTF-8 | 571 | 1.75 | 2 | [] | no_license | package com.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.entity.Users;
public interface UserDao {
public String searchUser(Map<String, Object> params) throws SQLException;
void addUser(Map<String, Object> params) throws SQLException;
void updateUser(Map<String, Object> params) throws SQLException;
void changePassword(Map<String, Object> params) throws SQLException;
List<Users> getSMSUsers() throws SQLException;
List<Users> getSearchResults(Map<String, Object> params) throws SQLException;
}
| true |
25531149133af49d1dd5e53f72b0507a2db743cf | Java | prashdeep/edureka-module7-servlets | /src/main/java/com/edureka/service/serverside/ProcessingServlet.java | UTF-8 | 683 | 2.203125 | 2 | [] | no_license | package com.edureka.service.serverside;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class ProcessingServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
Cookie cookie = new Cookie("userid", "ssdsdfsdfsdfsdf");
response.addCookie(cookie);
HttpSession session = request.getSession();
String username = (String)session.getAttribute("savedUser");
writer.write("<h1>Response send from processing servlet</h1>");
writer.write("<h2>"+username+"</h2>");
}
} | true |
aca9a2bf56387893c09f61e53184a6517ba6e284 | Java | MilanSarac/ProjekatWEB | /src/logic/ApartmanLogic.java | UTF-8 | 9,119 | 2.25 | 2 | [] | no_license | package logic;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import data.AmenitiesRepository;
import data.ApartmentRepository;
import data.UserRepository;
import model.Apartment;
public class ApartmanLogic {
public ArrayList<String> Lokacija() throws IOException {
ArrayList<String> Duplicate = new ArrayList<String>();
ApartmentRepository amr = new ApartmentRepository();
JSONArray allApartmants = (JSONArray) amr.GetallApartments();
for (int i = 0; i < allApartmants.size(); i++) {
JSONObject red = (JSONObject) allApartmants.get(i);
String Place = (String) red.get("Place");
Duplicate.add(Place);
}
ArrayList<String> nonDuplicate = new ArrayList<String>();
Iterator<String> dupIter = Duplicate.iterator();
while(dupIter.hasNext())
{
String dupWord = dupIter.next();
if(nonDuplicate.contains(dupWord))
{
continue;
}else
{
nonDuplicate.add(dupWord);
}
}
return nonDuplicate;
}
public ArrayList<String> ForHost() throws IOException {
ArrayList<String> Duplicate = new ArrayList<String>();
ApartmentRepository amr = new ApartmentRepository();
JSONArray allApartmants = (JSONArray) amr.GetallApartments();
for (int i = 0; i < allApartmants.size(); i++) {
JSONObject red = (JSONObject) allApartmants.get(i);
String Host_Apartmants = (String) red.get("Host");
Duplicate.add(Host_Apartmants);
}
ArrayList<String> nonDupList = new ArrayList<String>();
Iterator<String> dupIter = Duplicate.iterator();
while(dupIter.hasNext())
{
String dupWord = dupIter.next();
if(nonDupList.contains(dupWord))
{
continue;
}else
{
nonDupList.add(dupWord);
}
}
return nonDupList;
}
public List<Apartment> TopTen() throws IOException, ParseException {
ApartmentRepository at = new ApartmentRepository();
JSONArray all = (JSONArray) at.GetallApartments();
List<Apartment> allForSort = new ArrayList<>();
for (int i = 0; i < all.size(); i++) {
JSONObject object = (JSONObject) all.get(i);
String Sadrzaj = (String) object.get("parameterName");
String Type = (String) object.get("Type");
String Date_for_Rent_Start = (String) object.get("Date_for_Rent_Start");
String Date_for_Rent_End = (String) object.get("Date_for_Rent_End");
String ID_Apartman = (String) object.get("ID_Apartman");
String Host = (String) object.get("Host");
String Check_out_time = (String) object.get("Check_out_time");
String Check_in_time = (String) object.get("Check_in_time");
// String Active = (String) object.get("Active");
String Latitude = (String) object.get("Latitude");
String Longitude = (String) object.get("Longitude");
String Street = (String) object.get("Street");
String Streetnumber = (String) object.get("Streetnumber");
String Place = (String) object.get("Place");
String Zip_post = (String) object.get("Zip_post");
String Customer = (String) object.get("Customer");
//UUID uuid1 = UUID.randomUUID();
double Number_Rooms = Double.valueOf(String.valueOf(object.get("Number_Rooms")));
double Number_Guests = Double.valueOf(String.valueOf(object.get("Number_Guests")));
double Price_per_night = Double.valueOf(String.valueOf(object.get("Price_per_night")));
int Positive = Integer.valueOf(String.valueOf(object.get("Positive")));
String Photo = (String) object.get("Photo");
Apartment apartman = new Apartment(null, Type, Number_Rooms, Number_Guests,ID_Apartman, Date_for_Rent_End,
Price_per_night,Check_in_time, Check_out_time, true,Latitude, Longitude,Street,Streetnumber,Place, Zip_post,Host, Positive,Customer, Date_for_Rent_End);
allForSort.add(apartman);
}
Collections.sort(allForSort,
(apartman1, apartman2) -> apartman2.getPositive()
- apartman1.getPositive());
List<Apartment> contestWinners = allForSort.subList(0, 1);
return contestWinners;
}
public JSONObject ApartmansInfo(String Type) throws IOException {
System.out.println(Type);
UserRepository ur = new UserRepository();
JSONArray allUsers = new JSONArray();
allUsers = (JSONArray) ur.GetUsers();
JSONObject user = new JSONObject();
for (int i = 0; i < allUsers.size(); i++) {
JSONObject result = (JSONObject) allUsers.get(i);
String type = (String) result.get("Type");
if(Type.equals(type) )
{
user = (JSONObject) allUsers.get(i);
}
}
System.out.println(user);
return user;
}
public String Apartmans(String ID_Apartman) throws IOException {
JSONObject allApartmans = new JSONObject();
allApartmans = ApartmanById(ID_Apartman);
String apartments = null;
for (int i=0;i<allApartmans.size();i++) {
apartments = (String) allApartmans.get("Apartmans");
}
return apartments;
}
public JSONArray ActiveApartmansTest() throws IOException {
AmenitiesRepository ar= new AmenitiesRepository();
JSONArray jAr = ar.ActiveAmenities();
ArrayList<String> activeAm = new ArrayList<>();
for (int i=0;i<jAr.size();i++) {
JSONObject result = (JSONObject) jAr.get(i);
boolean active = (boolean) result.get("Active");
activeAm.add((String) result.get("Name_Amenities"));
}
JSONArray allApartman;
JSONArray returnApartmans = new JSONArray();
allApartman = ActiveApartmans();
for (int i=0;i<allApartman.size();i++) {
JSONObject apartman = new JSONObject();
JSONObject result = (JSONObject) allApartman.get(i);
JSONArray sadrzajiArr = (JSONArray) result.get("Sadrzaj");
JSONArray sadrzajZaPrikaz = new JSONArray();
for (int j=0;j<sadrzajiArr.size();j++) {
String sadrzaj = (String) sadrzajiArr.get(j);
if(activeAm.contains(sadrzaj)) {
sadrzajZaPrikaz.add(sadrzaj);
}
}
result.remove("Sadrzaj");
result.put("Sadrzaj", sadrzajZaPrikaz);
apartman = result;
returnApartmans.add(apartman);
}
return returnApartmans;
}
//ovde lepo radi izlistavanje svih AKTIVNIH apartmana i cao!
public JSONArray ActiveApartmans() throws IOException {
ApartmentRepository ar = new ApartmentRepository();
JSONArray allApartments = new JSONArray();
JSONArray allActiveApartments = new JSONArray();
allApartments = (JSONArray) ar.GetallApartments();
for (int i = 0; i < allApartments.size(); i++) {
JSONObject result = (JSONObject) allApartments.get(i);
boolean active = (boolean) result.get("Active");
if (active == true) {
allActiveApartments.add(result);
}
}
return allActiveApartments;
}
public JSONArray ActiveNOApartmans() throws IOException {
ApartmentRepository ar = new ApartmentRepository();
JSONArray allApartments = new JSONArray();
JSONArray allActiveApartments = new JSONArray();
allApartments = (JSONArray) ar.GetallApartments();
for (int i = 0; i < allApartments.size(); i++) {
JSONObject result = (JSONObject) allApartments.get(i);
boolean active = (boolean) result.get("Active");
if (active == false) {
allActiveApartments.add(result);
}
}
return allActiveApartments;
}
//ovde lepo radi izlistavanje svih apartmana i cao!
public JSONArray ApartmansAN() throws IOException {
ApartmentRepository ar = new ApartmentRepository();
JSONArray allApartments = new JSONArray();
JSONArray allANApartments = new JSONArray();
allApartments = (JSONArray) ar.GetallApartments();
for (int i = 0; i < allApartments.size(); i++) {
JSONObject result = (JSONObject) allApartments.get(i);
{
allANApartments.add(result);
}
}
return allANApartments;
}
public JSONObject ApartmanById(String ID_Apartman) throws IOException {
AmenitiesRepository ar= new AmenitiesRepository();
JSONArray jAr = ar.ActiveAmenities();
ArrayList<String> activeAm = new ArrayList<>();
for (int i=0;i<jAr.size();i++) {
JSONObject result = (JSONObject) jAr.get(i);
boolean active = (boolean) result.get("Active");
activeAm.add((String) result.get("Name_Amenities"));
}
JSONArray allApartman = new JSONArray();
allApartman = ActiveApartmans();
JSONObject apartman = new JSONObject();
for (int i=0;i<allApartman.size();i++) {
JSONObject result = (JSONObject) allApartman.get(i);
String id = (String) result.get("ID_Apartman");
if(id.equals(ID_Apartman)) {
JSONArray sadrzajiArr = (JSONArray) result.get("Sadrzaj");
JSONArray sadrzajZaPrikaz = new JSONArray();
for (int j=0;j<sadrzajiArr.size();j++) {
String sadrzaj = (String) sadrzajiArr.get(j);
if(activeAm.contains(sadrzaj)) {
sadrzajZaPrikaz.add(sadrzaj);
}
}
result.remove("Sadrzaj");
result.put("Sadrzaj", sadrzajZaPrikaz);
apartman = result;
//apartman=(JSONObject) allApartman.get(i);
}
}
return apartman;
}
}
| true |
29b931e40a5dfc8949f6e108c71160838e56a8cd | Java | NikitaKharitonov/ESAPracticalWork2 | /src/main/java/org/example/esapracticalwork2/model/Group.java | UTF-8 | 1,355 | 2.5625 | 3 | [] | no_license | package org.example.esapracticalwork2.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "_group")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator", sequenceName = "_group_id_seq", allocationSize = 1)
private Long id;
private Integer year;
@OneToMany(mappedBy = "group", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Student> students = new HashSet<>();
@OneToMany(mappedBy = "group", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Course> courses = new HashSet<>();
public Group() {
}
public Group(Integer year) {
this.year = year;
}
public Long getId() {
return id;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
| true |
492959f4118a32baa2ec7f9ce3f332995697838d | Java | AadityaDev/Tracker | /app/src/main/java/com/skybee/tracker/receiver/PeriodicTaskReceiver.java | UTF-8 | 4,766 | 1.898438 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.skybee.tracker.receiver;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.common.base.Strings;
import com.skybee.tracker.GPSTracker;
import com.skybee.tracker.Utility;
import com.skybee.tracker.activities.HomeActivity;
import com.skybee.tracker.constants.Constants;
import com.skybee.tracker.model.AttendancePojo;
import com.skybee.tracker.preferences.LocationServiceStore;
import com.skybee.tracker.preferences.UserStore;
public class PeriodicTaskReceiver extends BroadcastReceiver {
private final String TAG = this.getClass().getSimpleName();
private GPSTracker gpsTracker;
private UserStore userStore;
@Override
public void onReceive(@NonNull Context context,@NonNull Intent intent) {
if (!Strings.isNullOrEmpty(intent.getAction())) {
LocationServiceStore sharedPreferences = new LocationServiceStore(context);
HomeActivity homeActivity = new HomeActivity();
// if (intent.getAction().equals("android.intent.action.BATTERY_LOW")) {
// sharedPreferences.saveIsBatteryOk(false);
// stopPeriodicTaskHeartBeat(context);
// } else if (intent.getAction().equals("android.intent.action.BATTERY_OKAY")) {
// sharedPreferences.saveIsBatteryOk(true);
// restartPeriodicTaskHeartBeat(context);
// } else if (intent.getAction().equals(Constants.INTENT_ACTION)) {
doPeriodicTask(context, homeActivity);
// }
}
}
private void doPeriodicTask(@NonNull Context context,@NonNull HomeActivity myApplication) {
Log.d(TAG, "Repeat period task");
userStore = new UserStore(context);
gpsTracker = new GPSTracker(context);
if (gpsTracker.getLatitude() != 0 && gpsTracker.getLongitude() != 0) {
userStore.saveLatitude(gpsTracker.getLatitude());
userStore.saveLongitude(gpsTracker.getLongitude());
}
if (userStore.getUserDetails() != null) {
float[] results = new float[1];
Location.distanceBetween(userStore.getUserDetails().getCompanyLatitude(), userStore.getUserDetails().getCompanyLongitude(),
userStore.getUserDetails().getUserLatitude(), userStore.getUserDetails().getUserLongitude(), results);
float distanceInMeters = results[0];
boolean isWithinRange = distanceInMeters < userStore.getUserDetails().getCompanyRadius();
AttendancePojo attendancePojo = new AttendancePojo();
attendancePojo.setLongitude(userStore.getUserDetails().getUserLongitude());
attendancePojo.setLattitude(userStore.getUserDetails().getUserLatitude());
attendancePojo.setCustomer_site_id(userStore.getCompanyId());
attendancePojo.setLoginStatus(Constants.LOGIN_STATUS.ABSENT);
attendancePojo.setRoster_id(userStore.getUserDetails().getRoster_id());
attendancePojo.setImei_in(Utility.getIMEINumber(context));
attendancePojo.setIp_in(Utility.getIPAddress(context));
Utility.saveNotPresent(context, attendancePojo);
}
}
public void restartPeriodicTaskHeartBeat(@NonNull Context context) {
LocationServiceStore locationServiceStore = new LocationServiceStore(context);
boolean isBatteryOk = locationServiceStore.getBatteryStatus();
Intent alarmIntent = new Intent(context, PeriodicTaskReceiver.class);
boolean isAlarmUp = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_NO_CREATE) != null;
if (!isAlarmUp) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmIntent.setAction(Constants.INTENT_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), Constants.UPDATE_TIME_MILLISECONDS, pendingIntent);
}
}
public void stopPeriodicTaskHeartBeat(@NonNull Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, PeriodicTaskReceiver.class);
alarmIntent.setAction(Constants.INTENT_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
alarmManager.cancel(pendingIntent);
}
}
| true |
bc3d6476826d2a0e38ce539ce53aa3824a89f055 | Java | Yamidor/BackendColegio | /src/main/java/com/example/colegio/dto/EnrollmentDto.java | UTF-8 | 467 | 1.914063 | 2 | [] | no_license | package com.example.colegio.dto;
import com.example.colegio.model.Course;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@Data
@NoArgsConstructor
public class EnrollmentDto {
public static final String _IDENTIFICATION= "student";
private Long id;
private String state;
private CourseDto course;
private StudentDto student;
private ParentDto parent;
}
| true |
331211f4253b883d708f0c6b2711c102438992c0 | Java | ahibiv60/Databases_lab4 | /DB_lab4/src/main/java/com/rak/passive/controller/area/AreaImpl.java | UTF-8 | 5,310 | 2.609375 | 3 | [] | no_license | package com.rak.passive.controller.area;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.sql.*;
public class AreaImpl implements Area {
private static final String DATABASE = "irrigation_system";
private static final String USERNAME = "iotuser";
private static final String PASSWORD = "iotuser";
public void add(String new_location, int new_irrigation_system_id) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/" + DATABASE +
"?user=" + USERNAME + "&password=" + PASSWORD + "&serverTimezone=UTC");
Statement stmt = null;
if (!conn.isClosed()) {
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO area (location, irrigation_system_id) VALUES (\'" + new_location + "\'," + new_irrigation_system_id + ")");
}
} catch (SQLException e) {
throw new Error("Problem", e);
}
}
public JSONArray getAll() {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/" + DATABASE +
"?user=" + USERNAME + "&password=" + PASSWORD + "&serverTimezone=UTC");
Statement stmt = null;
String query = "select * from area";
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
JSONArray jsonArray = new JSONArray();
while (rs.next()) {
JSONObject area = new JSONObject();
//System.out.println(rs.getInt("id"));
area.put("id", rs.getString("id"));
area.put("location", rs.getString("location"));
area.put("irrigationSystemId", rs.getString("irrigation_system_id"));
jsonArray.add(area);
}
return jsonArray;
} catch (SQLException e) {
throw new Error("Problem", e);
} finally {
if (stmt != null) {
stmt.close();
}
}
} catch (SQLException e) {
throw new Error("Problem", e);
}
}
public JSONArray getById(int paramId) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/" + DATABASE +
"?user=" + USERNAME + "&password=" + PASSWORD + "&serverTimezone=UTC");
Statement stmt = null;
String query = "select * from area where id =\'" + paramId + " \';";
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
JSONArray jsonArray = new JSONArray();
while (rs.next()) {
JSONObject area = new JSONObject();
area.put("id", rs.getString("id"));
area.put("location", rs.getString("location"));
area.put("irrigationSystemId", rs.getString("irrigation_system_id"));
jsonArray.add(area);
}
return jsonArray;
} catch (SQLException e) {
throw new Error("Problem", e);
} finally {
if (stmt != null) {
stmt.close();
}
}
} catch (SQLException e) {
throw new Error("Problem", e);
}
}
public void updateById(int paramId, String newLocation, int newIrrigationSysteamId) {
Connection conn = null;
try {
String url = "jdbc:sqlite:path-to-db-file/chinook/chinook.db";
conn = DriverManager.getConnection("jdbc:mysql://localhost/" + DATABASE +
"?user=" + USERNAME + "&password=" + PASSWORD + "&serverTimezone=UTC");
String query = "UPDATE area SET location = ?, irrigation_system_id= ? WHERE id = ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, newLocation);
preparedStmt.setInt(2, newIrrigationSysteamId);
preparedStmt.setInt(3, paramId);
// execute the java preparedstatement
preparedStmt.executeUpdate();
} catch (SQLException e) {
throw new Error("Problem", e);
}
}
public void deleteById(int paramId) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/" + DATABASE +
"?user=" + USERNAME + "&password=" + PASSWORD + "&serverTimezone=UTC");
Statement stmt = null;
String sql = "delete from area where id =\'" + paramId + " \';";
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
throw new Error("Problem", e);
} finally {
if (stmt != null) {
stmt.close();
}
}
} catch (SQLException e) {
throw new Error("Problem", e);
}
}
}
| true |
8492a8c2d545904ce11b1a033ebd9afae6b0c58f | Java | chengtech/Application1 | /道路养护/src/main/java/com/chengtech/chengtechmt/activity/integratequery/routequery/RouteQueryActivity.java | UTF-8 | 4,250 | 1.96875 | 2 | [] | no_license | package com.chengtech.chengtechmt.activity.integratequery.routequery;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.chengtech.chengtechmt.BaseActivity;
import com.chengtech.chengtechmt.R;
import com.chengtech.chengtechmt.entity.Route;
import java.util.ArrayList;
import java.util.List;
public class RouteQueryActivity extends BaseActivity {
public TabLayout tabLayout;
public ViewPager viewPager;
public Route route;
public String deptId;
public List<Fragment> fragmentList;
public String[] mTitle = new String[]{"路线卡片", "历史保养","历史小修","历史小额"
,"历史项目","历史评定","交通量汇总"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addContentView(R.layout.activity_route_query);
Intent intent = getIntent();
route = (Route) intent.getSerializableExtra("data");
deptId = intent.getStringExtra("deptId");
tabLayout = (TabLayout) findViewById(R.id.id_tabLayout);
initData();
initView();
setNavigationIcon(true);
hidePagerNavigation(true);
setAppBarLayoutScroll(false);
toolbar.setTitle(route.name);
}
private void initData() {
fragmentList = new ArrayList<>();
Bundle bundle = new Bundle();
//路线信息卡片
RouteFragment routeFragment = new RouteFragment();
if (route!=null) {
bundle.putString("routeId",route.id);
bundle.putSerializable("data",route);
bundle.putString("deptId",deptId);
}
routeFragment.setArguments(bundle);
//历史病害
// HistoryDiseaseFragment historyDiseaseFragment = new HistoryDiseaseFragment();
// historyDiseaseFragment.setArguments(bundle);
// TaskFragment taskFragment = new TaskFragment();
// taskFragment.setArguments(bundle);
//历史保养
MaintainTaskFragment maintainTaskFragment = new MaintainTaskFragment();
maintainTaskFragment.setArguments(bundle);
//历史小修
MinorRepairFragment minorRepairFragment = new MinorRepairFragment();
minorRepairFragment.setArguments(bundle);
//历史小额专项维修
MediumPlanprogressFragment mediumPlanprogressFragment = new MediumPlanprogressFragment();
mediumPlanprogressFragment.setArguments(bundle);
//历史项目
ProjectManagementFragment projectManagementFragment = new ProjectManagementFragment();
projectManagementFragment.setArguments(bundle);
//评定明细
EvaluationFragment evaluationFragment = new EvaluationFragment();
evaluationFragment.setArguments(bundle);
//交通量汇总
TrafficVolumeFragment trafficVolumeFragment = new TrafficVolumeFragment();
trafficVolumeFragment.setArguments(bundle);
fragmentList.add(routeFragment);
fragmentList.add(maintainTaskFragment);
// fragmentList.add(taskFragment);
fragmentList.add(minorRepairFragment);
fragmentList.add(mediumPlanprogressFragment);
fragmentList.add(projectManagementFragment);
fragmentList.add(evaluationFragment);
fragmentList.add(trafficVolumeFragment);
}
private void initView() {
viewPager = (ViewPager) findViewById(R.id.id_viewPager);
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
// Toast.makeText(RouteQueryActivity.this, ""+position, Toast.LENGTH_SHORT).show();
return fragmentList.get(position);
}
@Override
public int getCount() {
return mTitle.length;
}
@Override
public CharSequence getPageTitle(int position) {
return mTitle[position];
}
});
tabLayout.setupWithViewPager(viewPager);
}
}
| true |
30164de5ab3903d38f2614edc8ccaf716e9685b6 | Java | wahrwolf/Aufgaben-SE2-Block-1 | /04/Mediathek_Vorlage_Blatt04-05/Mediathek_Vorlage_Blatt04-05/src/mediathek/medien/AbstractVideospiel.java | UTF-8 | 1,675 | 3.046875 | 3 | [] | no_license | package mediathek.medien;
import mediathek.fachwerte.Geldbetrag;
/**
* {@link AbstractVideospiel} ist ein {@link Medium} mit einer zusätzlichen
* Informationen zum kompatiblen System.
*
* @author SE2-Team
* @version SoSe 2012
*/
public abstract class AbstractVideospiel extends AbstractMedium {
/**
* Das System, auf dem das Spiel lauffähig ist
*/
private String _system;
/**
* Initialisiert ein neues Videospiel.
*
* @param titel
* Der Titel des Spiels
* @param kommentar
* Ein Kommentar zum Spiel
* @param system
* Die Bezeichnung des System
*
* @require titel != null
* @require kommentar != null
* @require system != null
*
* @ensure getTitel() == titel
* @ensure getKommentar() == kommentar
* @ensure getSystem() == system
*/
public AbstractVideospiel(String titel, String kommentar, String system) {
super(titel, kommentar);
assert system != null : "Vorbedingung verletzt: system != null";
_system = system;
_medienBezeichner = "Videospiel";
_leihgebuehrTaeglich = 0;
_leihgebuehrAufschlag =200;
}
abstract int getPreisNachTagen(int tage);
/**
* Gibt das System zurück, auf dem das Spiel lauffähig ist.
*
* @return Das System, auf dem das Spiel ausgeführt werden kann.
*
* @ensure result != null
*/
public String getSystem() {
return _system;
}
@Override
public String getFormatiertenString() {
return super.getFormatiertenString() + " " +"System: " + _system + "\n";
}
@Override
public Geldbetrag berechneMietgebuehr(int mietTage)
{
return new Geldbetrag(getPreisNachTagen(mietTage)+_leihgebuehrAufschlag);
}
}
| true |
0e154c01c19ab944b4ea1ca3c5c3f9349dbbedf6 | Java | Garrit/java-common | /src/main/java/org/garrit/common/messages/Execution.java | UTF-8 | 615 | 2.234375 | 2 | [] | no_license | package org.garrit.common.messages;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* A submission which has passed through execution.
*
* @author Samuel Coleman <samuel@seenet.ca>
* @since 1.0.0
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class Execution extends RegisteredSubmission
{
/**
* Cases evaluated during the execution.
*/
private List<ExecutionCase> cases = new ArrayList<>();
public Execution()
{
super();
}
public Execution(RegisteredSubmission submission)
{
super(submission);
}
} | true |
6a76ed7e3c8cc1c1f11e14986492e941d1e654d6 | Java | Skwardlow/AppointmentSystem | /src/main/java/ru/eltex/project/simpleappointer/controllers/AdminController.java | UTF-8 | 4,044 | 2.421875 | 2 | [] | no_license | package ru.eltex.project.simpleappointer.controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.eltex.project.simpleappointer.services.AdminService;
import ru.eltex.project.simpleappointer.services.DateService;
import ru.eltex.project.simpleappointer.utils.SplitURL;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
/**
* An REST-controller for mapping POST admin requests to the server
*
* @author Aaaaa988, skwardlow
* @version 1.0
* @see RestController
*/
@RestController
public class AdminController {
/**
* Wiring Admin service for DAO interaction
*/
@Autowired
AdminService adminService;
/**
* Wiring Date service for DAO interaction
*/
@Autowired
DateService dateService;
/**
* Deleting specialist from DB method
*
* @param object url not splitted body, coming to spliturl util, contains username of spec
* @return 0, success ans for checking connection between server and client
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/delete_spec", produces = MediaType.APPLICATION_JSON_VALUE)
public Integer delete_spec(@RequestBody String object) throws UnsupportedEncodingException {
ArrayList<String> req = SplitURL.split(object);
adminService.deleteByUsername(req.get(0));
return 0;
}
/**
* Deleting day with appointments from DB method
*
* @param object url not splitted body, coming to spliturl util, contains spec uname and day in format '30/02/19'
* @return 0, success ans for checking connection between server and client
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/delete_day", produces = MediaType.APPLICATION_JSON_VALUE)
public Integer delete_day(@RequestBody String object) throws UnsupportedEncodingException {
ArrayList<String> req = SplitURL.split(object);
dateService.dayWithAppointmentsDelete(req.get(0), req.get(1));
return 0;
}
/**
* Invites resetting method, deleting all unused invites in DB
*
* @return 0, success ans for checking connection between server and client
*/
@RequestMapping(value = "/invite_reset", produces = MediaType.APPLICATION_JSON_VALUE)
public Integer invite_reset() {
adminService.resetInvites();
return 0;
}
/**
* Creating new invite(s) method, inserting new invites in db
*
* @param object url not splitted body, contains invite identifies
* @return 0, success ans for checking connection between server and client
* @throws UnsupportedEncodingException
* @see ru.eltex.project.simpleappointer.entities.Invite
*/
@RequestMapping(value = "/invite_create", produces = MediaType.APPLICATION_JSON_VALUE)
public Integer invite_create(@RequestBody String object) throws UnsupportedEncodingException {
ArrayList<String> req = SplitURL.split(object);
for (String iteration : req) {
adminService.inviteCreate(iteration);
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
return 0;
}
/**
* Request fot all specialist method
*
* @return json formed specialist objects from DB
* @throws JsonProcessingException
*/
@RequestMapping(value = "/users_get", produces = MediaType.APPLICATION_JSON_VALUE)
public String users_get() throws JsonProcessingException {
return adminService.findAllSpecialists();
}
}
| true |
f8a10b06b03a3855c07b3ffb8e75c3e1e13cd82c | Java | Topology/ALM-Compiler | /src/main/java/edu/ttu/krlab/alm/datastruct/sig/IntegerRangeSortEntry.java | UTF-8 | 733 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.ttu.krlab.alm.datastruct.sig;
import edu.ttu.krlab.alm.datastruct.Location;
/**
*
* @author Topology
*/
public class IntegerRangeSortEntry extends SortEntry {
private int low;
private int high;
public IntegerRangeSortEntry(String sortname, int low, int high, Location loc) {
super(sortname, loc);
this.low = low;
this.high = high;
}
public int getLow() {
return low;
}
public int getHigh() {
return high;
}
}
| true |
ab4bd2168f9a74ece86ceb93bab6f9406fe00bb0 | Java | 20162430413/agile | /agile/src/main/java/com/order/mapper/EmployeeMapper.java | UTF-8 | 616 | 2.046875 | 2 | [] | no_license | package com.order.mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.order.entity.Employee;
@Repository
public interface EmployeeMapper {
int deleteByPrimaryKey(Integer employeeId);
int insert(Employee record);
int insertSelective(Employee record);
Employee selectByPrimaryKey(Integer employeeId);
int updateByPrimaryKeySelective(Employee record);
int updateByPrimaryKey(Employee record);
Employee selectByUsernameAndPassword(@Param("account") String account,@Param("pwd")String password);
} | true |
531be9c9a404f3e4fbdca0ab8289386b58705c87 | Java | ognelis/compiler-language | /gen/MyLangParser.java | UTF-8 | 40,354 | 1.695313 | 2 | [] | no_license | // Generated from C:/Users/Admin/IdeaProjects/language/src\MyLang.g4 by ANTLR 4.5.1
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class MyLangParser extends Parser {
static { RuntimeMetaData.checkVersion("4.5.1", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9,
T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17,
T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, T__22=23, T__23=24,
T__24=25, T__25=26, T__26=27, T__27=28, T__28=29, T__29=30, T__30=31,
T__31=32, T__32=33, T__33=34, T__34=35, INT=36, FLOAT=37, CHAR=38, BOOL=39,
ID=40, DIGIT=41, WS=42, SL_COMMENT=43;
public static final int
RULE_file = 0, RULE_declaration = 1, RULE_varDeclaration = 2, RULE_valDeclaration = 3,
RULE_typeDeclaration = 4, RULE_funDeclaration = 5, RULE_formalParameters = 6,
RULE_formalParameter = 7, RULE_block = 8, RULE_statement = 9, RULE_expression = 10,
RULE_expressionList = 11;
public static final String[] ruleNames = {
"file", "declaration", "varDeclaration", "valDeclaration", "typeDeclaration",
"funDeclaration", "formalParameters", "formalParameter", "block", "statement",
"expression", "expressionList"
};
private static final String[] _LITERAL_NAMES = {
null, "'val'", "'var'", "':'", "'='", "';'", "'['", "']'", "'bool'", "'char'",
"'float'", "'int'", "'void'", "'def'", "'('", "')'", "','", "'{'", "'}'",
"'if'", "'else'", "'while'", "'return'", "'=='", "'!='", "'<'", "'<='",
"'>'", "'>='", "'-'", "'!'", "'&&'", "'||'", "'*'", "'/'", "'+'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null,
"INT", "FLOAT", "CHAR", "BOOL", "ID", "DIGIT", "WS", "SL_COMMENT"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "MyLang.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public MyLangParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class FileContext extends ParserRuleContext {
public List<DeclarationContext> declaration() {
return getRuleContexts(DeclarationContext.class);
}
public DeclarationContext declaration(int i) {
return getRuleContext(DeclarationContext.class,i);
}
public List<FunDeclarationContext> funDeclaration() {
return getRuleContexts(FunDeclarationContext.class);
}
public FunDeclarationContext funDeclaration(int i) {
return getRuleContext(FunDeclarationContext.class,i);
}
public FileContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_file; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterFile(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitFile(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitFile(this);
else return visitor.visitChildren(this);
}
}
public final FileContext file() throws RecognitionException {
FileContext _localctx = new FileContext(_ctx, getState());
enterRule(_localctx, 0, RULE_file);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(26);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
setState(26);
switch (_input.LA(1)) {
case T__0:
case T__1:
{
setState(24);
declaration();
}
break;
case T__12:
{
setState(25);
funDeclaration();
}
break;
default:
throw new NoViableAltException(this);
}
}
setState(28);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__12))) != 0) );
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class DeclarationContext extends ParserRuleContext {
public ValDeclarationContext valDeclaration() {
return getRuleContext(ValDeclarationContext.class,0);
}
public VarDeclarationContext varDeclaration() {
return getRuleContext(VarDeclarationContext.class,0);
}
public DeclarationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_declaration; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterDeclaration(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitDeclaration(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitDeclaration(this);
else return visitor.visitChildren(this);
}
}
public final DeclarationContext declaration() throws RecognitionException {
DeclarationContext _localctx = new DeclarationContext(_ctx, getState());
enterRule(_localctx, 2, RULE_declaration);
try {
setState(34);
switch (_input.LA(1)) {
case T__0:
enterOuterAlt(_localctx, 1);
{
setState(30);
match(T__0);
setState(31);
valDeclaration();
}
break;
case T__1:
enterOuterAlt(_localctx, 2);
{
setState(32);
match(T__1);
setState(33);
varDeclaration();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class VarDeclarationContext extends ParserRuleContext {
public TerminalNode ID() { return getToken(MyLangParser.ID, 0); }
public TypeDeclarationContext typeDeclaration() {
return getRuleContext(TypeDeclarationContext.class,0);
}
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class,0);
}
public VarDeclarationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_varDeclaration; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterVarDeclaration(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitVarDeclaration(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitVarDeclaration(this);
else return visitor.visitChildren(this);
}
}
public final VarDeclarationContext varDeclaration() throws RecognitionException {
VarDeclarationContext _localctx = new VarDeclarationContext(_ctx, getState());
enterRule(_localctx, 4, RULE_varDeclaration);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(36);
match(ID);
setState(37);
match(T__2);
setState(38);
typeDeclaration(0);
setState(41);
_la = _input.LA(1);
if (_la==T__3) {
{
setState(39);
match(T__3);
setState(40);
expression(0);
}
}
setState(43);
match(T__4);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ValDeclarationContext extends ParserRuleContext {
public TerminalNode ID() { return getToken(MyLangParser.ID, 0); }
public TypeDeclarationContext typeDeclaration() {
return getRuleContext(TypeDeclarationContext.class,0);
}
public ExpressionContext expression() {
return getRuleContext(ExpressionContext.class,0);
}
public ValDeclarationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_valDeclaration; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterValDeclaration(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitValDeclaration(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitValDeclaration(this);
else return visitor.visitChildren(this);
}
}
public final ValDeclarationContext valDeclaration() throws RecognitionException {
ValDeclarationContext _localctx = new ValDeclarationContext(_ctx, getState());
enterRule(_localctx, 6, RULE_valDeclaration);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(45);
match(ID);
setState(46);
match(T__2);
setState(47);
typeDeclaration(0);
setState(50);
_la = _input.LA(1);
if (_la==T__3) {
{
setState(48);
match(T__3);
setState(49);
expression(0);
}
}
setState(52);
match(T__4);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class TypeDeclarationContext extends ParserRuleContext {
public TypeDeclarationContext typeDeclaration() {
return getRuleContext(TypeDeclarationContext.class,0);
}
public TerminalNode INT() { return getToken(MyLangParser.INT, 0); }
public TypeDeclarationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_typeDeclaration; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterTypeDeclaration(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitTypeDeclaration(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitTypeDeclaration(this);
else return visitor.visitChildren(this);
}
}
public final TypeDeclarationContext typeDeclaration() throws RecognitionException {
return typeDeclaration(0);
}
private TypeDeclarationContext typeDeclaration(int _p) throws RecognitionException {
ParserRuleContext _parentctx = _ctx;
int _parentState = getState();
TypeDeclarationContext _localctx = new TypeDeclarationContext(_ctx, _parentState);
TypeDeclarationContext _prevctx = _localctx;
int _startState = 8;
enterRecursionRule(_localctx, 8, RULE_typeDeclaration, _p);
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(60);
switch (_input.LA(1)) {
case T__7:
{
setState(55);
match(T__7);
}
break;
case T__8:
{
setState(56);
match(T__8);
}
break;
case T__9:
{
setState(57);
match(T__9);
}
break;
case T__10:
{
setState(58);
match(T__10);
}
break;
case T__11:
{
setState(59);
match(T__11);
}
break;
default:
throw new NoViableAltException(this);
}
_ctx.stop = _input.LT(-1);
setState(68);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,6,_ctx);
while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) {
if ( _alt==1 ) {
if ( _parseListeners!=null ) triggerExitRuleEvent();
_prevctx = _localctx;
{
{
_localctx = new TypeDeclarationContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_typeDeclaration);
setState(62);
if (!(precpred(_ctx, 6))) throw new FailedPredicateException(this, "precpred(_ctx, 6)");
setState(63);
match(T__5);
setState(64);
match(INT);
setState(65);
match(T__6);
}
}
}
setState(70);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,6,_ctx);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
unrollRecursionContexts(_parentctx);
}
return _localctx;
}
public static class FunDeclarationContext extends ParserRuleContext {
public TerminalNode ID() { return getToken(MyLangParser.ID, 0); }
public FormalParametersContext formalParameters() {
return getRuleContext(FormalParametersContext.class,0);
}
public TypeDeclarationContext typeDeclaration() {
return getRuleContext(TypeDeclarationContext.class,0);
}
public BlockContext block() {
return getRuleContext(BlockContext.class,0);
}
public FunDeclarationContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_funDeclaration; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterFunDeclaration(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitFunDeclaration(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitFunDeclaration(this);
else return visitor.visitChildren(this);
}
}
public final FunDeclarationContext funDeclaration() throws RecognitionException {
FunDeclarationContext _localctx = new FunDeclarationContext(_ctx, getState());
enterRule(_localctx, 10, RULE_funDeclaration);
try {
enterOuterAlt(_localctx, 1);
{
setState(71);
match(T__12);
setState(72);
match(ID);
setState(73);
match(T__13);
setState(74);
formalParameters();
setState(75);
match(T__14);
setState(76);
match(T__2);
setState(77);
typeDeclaration(0);
setState(78);
block();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FormalParametersContext extends ParserRuleContext {
public List<FormalParameterContext> formalParameter() {
return getRuleContexts(FormalParameterContext.class);
}
public FormalParameterContext formalParameter(int i) {
return getRuleContext(FormalParameterContext.class,i);
}
public FormalParametersContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_formalParameters; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterFormalParameters(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitFormalParameters(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitFormalParameters(this);
else return visitor.visitChildren(this);
}
}
public final FormalParametersContext formalParameters() throws RecognitionException {
FormalParametersContext _localctx = new FormalParametersContext(_ctx, getState());
enterRule(_localctx, 12, RULE_formalParameters);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(80);
formalParameter();
setState(85);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__15) {
{
{
setState(81);
match(T__15);
setState(82);
formalParameter();
}
}
setState(87);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class FormalParameterContext extends ParserRuleContext {
public TerminalNode ID() { return getToken(MyLangParser.ID, 0); }
public TypeDeclarationContext typeDeclaration() {
return getRuleContext(TypeDeclarationContext.class,0);
}
public FormalParameterContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_formalParameter; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterFormalParameter(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitFormalParameter(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitFormalParameter(this);
else return visitor.visitChildren(this);
}
}
public final FormalParameterContext formalParameter() throws RecognitionException {
FormalParameterContext _localctx = new FormalParameterContext(_ctx, getState());
enterRule(_localctx, 14, RULE_formalParameter);
try {
enterOuterAlt(_localctx, 1);
{
setState(88);
match(ID);
setState(89);
match(T__2);
setState(90);
typeDeclaration(0);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class BlockContext extends ParserRuleContext {
public List<StatementContext> statement() {
return getRuleContexts(StatementContext.class);
}
public StatementContext statement(int i) {
return getRuleContext(StatementContext.class,i);
}
public BlockContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_block; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterBlock(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitBlock(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitBlock(this);
else return visitor.visitChildren(this);
}
}
public final BlockContext block() throws RecognitionException {
BlockContext _localctx = new BlockContext(_ctx, getState());
enterRule(_localctx, 16, RULE_block);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(92);
match(T__16);
setState(96);
_errHandler.sync(this);
_la = _input.LA(1);
while ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__0) | (1L << T__1) | (1L << T__13) | (1L << T__16) | (1L << T__18) | (1L << T__20) | (1L << T__21) | (1L << T__28) | (1L << T__29) | (1L << INT) | (1L << FLOAT) | (1L << CHAR) | (1L << BOOL) | (1L << ID))) != 0)) {
{
{
setState(93);
statement();
}
}
setState(98);
_errHandler.sync(this);
_la = _input.LA(1);
}
setState(99);
match(T__17);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class StatementContext extends ParserRuleContext {
public BlockContext block() {
return getRuleContext(BlockContext.class,0);
}
public DeclarationContext declaration() {
return getRuleContext(DeclarationContext.class,0);
}
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public List<StatementContext> statement() {
return getRuleContexts(StatementContext.class);
}
public StatementContext statement(int i) {
return getRuleContext(StatementContext.class,i);
}
public StatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_statement; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterStatement(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitStatement(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitStatement(this);
else return visitor.visitChildren(this);
}
}
public final StatementContext statement() throws RecognitionException {
StatementContext _localctx = new StatementContext(_ctx, getState());
enterRule(_localctx, 18, RULE_statement);
int _la;
try {
setState(131);
switch ( getInterpreter().adaptivePredict(_input,11,_ctx) ) {
case 1:
enterOuterAlt(_localctx, 1);
{
setState(101);
block();
}
break;
case 2:
enterOuterAlt(_localctx, 2);
{
setState(102);
declaration();
}
break;
case 3:
enterOuterAlt(_localctx, 3);
{
setState(103);
match(T__18);
setState(104);
match(T__13);
setState(105);
expression(0);
setState(106);
match(T__14);
setState(107);
statement();
setState(110);
switch ( getInterpreter().adaptivePredict(_input,9,_ctx) ) {
case 1:
{
setState(108);
match(T__19);
setState(109);
statement();
}
break;
}
}
break;
case 4:
enterOuterAlt(_localctx, 4);
{
setState(112);
match(T__20);
setState(113);
match(T__13);
setState(114);
expression(0);
setState(115);
match(T__14);
setState(116);
statement();
}
break;
case 5:
enterOuterAlt(_localctx, 5);
{
setState(118);
match(T__21);
setState(120);
_la = _input.LA(1);
if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__13) | (1L << T__28) | (1L << T__29) | (1L << INT) | (1L << FLOAT) | (1L << CHAR) | (1L << BOOL) | (1L << ID))) != 0)) {
{
setState(119);
expression(0);
}
}
setState(122);
match(T__4);
}
break;
case 6:
enterOuterAlt(_localctx, 6);
{
setState(123);
expression(0);
setState(124);
match(T__3);
setState(125);
expression(0);
setState(126);
match(T__4);
}
break;
case 7:
enterOuterAlt(_localctx, 7);
{
setState(128);
expression(0);
setState(129);
match(T__4);
}
break;
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ExpressionContext extends ParserRuleContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public TerminalNode ID() { return getToken(MyLangParser.ID, 0); }
public ExpressionListContext expressionList() {
return getRuleContext(ExpressionListContext.class,0);
}
public TerminalNode INT() { return getToken(MyLangParser.INT, 0); }
public TerminalNode FLOAT() { return getToken(MyLangParser.FLOAT, 0); }
public TerminalNode CHAR() { return getToken(MyLangParser.CHAR, 0); }
public TerminalNode BOOL() { return getToken(MyLangParser.BOOL, 0); }
public ExpressionContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_expression; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterExpression(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitExpression(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitExpression(this);
else return visitor.visitChildren(this);
}
}
public final ExpressionContext expression() throws RecognitionException {
return expression(0);
}
private ExpressionContext expression(int _p) throws RecognitionException {
ParserRuleContext _parentctx = _ctx;
int _parentState = getState();
ExpressionContext _localctx = new ExpressionContext(_ctx, _parentState);
ExpressionContext _prevctx = _localctx;
int _startState = 20;
enterRecursionRule(_localctx, 20, RULE_expression, _p);
int _la;
try {
int _alt;
enterOuterAlt(_localctx, 1);
{
setState(153);
switch ( getInterpreter().adaptivePredict(_input,13,_ctx) ) {
case 1:
{
setState(134);
match(T__28);
setState(135);
expression(12);
}
break;
case 2:
{
setState(136);
match(T__29);
setState(137);
expression(11);
}
break;
case 3:
{
setState(138);
match(ID);
setState(139);
match(T__13);
setState(141);
_la = _input.LA(1);
if ((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__13) | (1L << T__28) | (1L << T__29) | (1L << INT) | (1L << FLOAT) | (1L << CHAR) | (1L << BOOL) | (1L << ID))) != 0)) {
{
setState(140);
expressionList();
}
}
setState(143);
match(T__14);
}
break;
case 4:
{
setState(144);
match(ID);
}
break;
case 5:
{
setState(145);
match(INT);
}
break;
case 6:
{
setState(146);
match(FLOAT);
}
break;
case 7:
{
setState(147);
match(CHAR);
}
break;
case 8:
{
setState(148);
match(BOOL);
}
break;
case 9:
{
setState(149);
match(T__13);
setState(150);
expression(0);
setState(151);
match(T__14);
}
break;
}
_ctx.stop = _input.LT(-1);
setState(180);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,15,_ctx);
while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) {
if ( _alt==1 ) {
if ( _parseListeners!=null ) triggerExitRuleEvent();
_prevctx = _localctx;
{
setState(178);
switch ( getInterpreter().adaptivePredict(_input,14,_ctx) ) {
case 1:
{
_localctx = new ExpressionContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(155);
if (!(precpred(_ctx, 14))) throw new FailedPredicateException(this, "precpred(_ctx, 14)");
setState(156);
_la = _input.LA(1);
if ( !(_la==T__22 || _la==T__23) ) {
_errHandler.recoverInline(this);
} else {
consume();
}
setState(157);
expression(15);
}
break;
case 2:
{
_localctx = new ExpressionContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(158);
if (!(precpred(_ctx, 13))) throw new FailedPredicateException(this, "precpred(_ctx, 13)");
setState(159);
_la = _input.LA(1);
if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << T__24) | (1L << T__25) | (1L << T__26) | (1L << T__27))) != 0)) ) {
_errHandler.recoverInline(this);
} else {
consume();
}
setState(160);
expression(14);
}
break;
case 3:
{
_localctx = new ExpressionContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(161);
if (!(precpred(_ctx, 10))) throw new FailedPredicateException(this, "precpred(_ctx, 10)");
setState(162);
match(T__30);
setState(163);
expression(11);
}
break;
case 4:
{
_localctx = new ExpressionContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(164);
if (!(precpred(_ctx, 9))) throw new FailedPredicateException(this, "precpred(_ctx, 9)");
setState(165);
match(T__31);
setState(166);
expression(10);
}
break;
case 5:
{
_localctx = new ExpressionContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(167);
if (!(precpred(_ctx, 8))) throw new FailedPredicateException(this, "precpred(_ctx, 8)");
setState(168);
_la = _input.LA(1);
if ( !(_la==T__32 || _la==T__33) ) {
_errHandler.recoverInline(this);
} else {
consume();
}
setState(169);
expression(9);
}
break;
case 6:
{
_localctx = new ExpressionContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(170);
if (!(precpred(_ctx, 7))) throw new FailedPredicateException(this, "precpred(_ctx, 7)");
setState(171);
_la = _input.LA(1);
if ( !(_la==T__28 || _la==T__34) ) {
_errHandler.recoverInline(this);
} else {
consume();
}
setState(172);
expression(8);
}
break;
case 7:
{
_localctx = new ExpressionContext(_parentctx, _parentState);
pushNewRecursionContext(_localctx, _startState, RULE_expression);
setState(173);
if (!(precpred(_ctx, 15))) throw new FailedPredicateException(this, "precpred(_ctx, 15)");
setState(174);
match(T__5);
setState(175);
expression(0);
setState(176);
match(T__6);
}
break;
}
}
}
setState(182);
_errHandler.sync(this);
_alt = getInterpreter().adaptivePredict(_input,15,_ctx);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
unrollRecursionContexts(_parentctx);
}
return _localctx;
}
public static class ExpressionListContext extends ParserRuleContext {
public List<ExpressionContext> expression() {
return getRuleContexts(ExpressionContext.class);
}
public ExpressionContext expression(int i) {
return getRuleContext(ExpressionContext.class,i);
}
public ExpressionListContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_expressionList; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).enterExpressionList(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof MyLangListener ) ((MyLangListener)listener).exitExpressionList(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof MyLangVisitor ) return ((MyLangVisitor<? extends T>)visitor).visitExpressionList(this);
else return visitor.visitChildren(this);
}
}
public final ExpressionListContext expressionList() throws RecognitionException {
ExpressionListContext _localctx = new ExpressionListContext(_ctx, getState());
enterRule(_localctx, 22, RULE_expressionList);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(183);
expression(0);
setState(188);
_errHandler.sync(this);
_la = _input.LA(1);
while (_la==T__15) {
{
{
setState(184);
match(T__15);
setState(185);
expression(0);
}
}
setState(190);
_errHandler.sync(this);
_la = _input.LA(1);
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public boolean sempred(RuleContext _localctx, int ruleIndex, int predIndex) {
switch (ruleIndex) {
case 4:
return typeDeclaration_sempred((TypeDeclarationContext)_localctx, predIndex);
case 10:
return expression_sempred((ExpressionContext)_localctx, predIndex);
}
return true;
}
private boolean typeDeclaration_sempred(TypeDeclarationContext _localctx, int predIndex) {
switch (predIndex) {
case 0:
return precpred(_ctx, 6);
}
return true;
}
private boolean expression_sempred(ExpressionContext _localctx, int predIndex) {
switch (predIndex) {
case 1:
return precpred(_ctx, 14);
case 2:
return precpred(_ctx, 13);
case 3:
return precpred(_ctx, 10);
case 4:
return precpred(_ctx, 9);
case 5:
return precpred(_ctx, 8);
case 6:
return precpred(_ctx, 7);
case 7:
return precpred(_ctx, 15);
}
return true;
}
public static final String _serializedATN =
"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3-\u00c2\4\2\t\2\4"+
"\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t"+
"\13\4\f\t\f\4\r\t\r\3\2\3\2\6\2\35\n\2\r\2\16\2\36\3\3\3\3\3\3\3\3\5\3"+
"%\n\3\3\4\3\4\3\4\3\4\3\4\5\4,\n\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5\5\5\65"+
"\n\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\5\6?\n\6\3\6\3\6\3\6\3\6\7\6E\n\6"+
"\f\6\16\6H\13\6\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\7\bV\n"+
"\b\f\b\16\bY\13\b\3\t\3\t\3\t\3\t\3\n\3\n\7\na\n\n\f\n\16\nd\13\n\3\n"+
"\3\n\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\5\13q\n\13\3\13\3\13"+
"\3\13\3\13\3\13\3\13\3\13\3\13\5\13{\n\13\3\13\3\13\3\13\3\13\3\13\3\13"+
"\3\13\3\13\3\13\5\13\u0086\n\13\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\5\f\u0090"+
"\n\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\5\f\u009c\n\f\3\f\3\f\3\f"+
"\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3"+
"\f\3\f\3\f\7\f\u00b5\n\f\f\f\16\f\u00b8\13\f\3\r\3\r\3\r\7\r\u00bd\n\r"+
"\f\r\16\r\u00c0\13\r\3\r\2\4\n\26\16\2\4\6\b\n\f\16\20\22\24\26\30\2\6"+
"\3\2\31\32\3\2\33\36\3\2#$\4\2\37\37%%\u00da\2\34\3\2\2\2\4$\3\2\2\2\6"+
"&\3\2\2\2\b/\3\2\2\2\n>\3\2\2\2\fI\3\2\2\2\16R\3\2\2\2\20Z\3\2\2\2\22"+
"^\3\2\2\2\24\u0085\3\2\2\2\26\u009b\3\2\2\2\30\u00b9\3\2\2\2\32\35\5\4"+
"\3\2\33\35\5\f\7\2\34\32\3\2\2\2\34\33\3\2\2\2\35\36\3\2\2\2\36\34\3\2"+
"\2\2\36\37\3\2\2\2\37\3\3\2\2\2 !\7\3\2\2!%\5\b\5\2\"#\7\4\2\2#%\5\6\4"+
"\2$ \3\2\2\2$\"\3\2\2\2%\5\3\2\2\2&\'\7*\2\2\'(\7\5\2\2(+\5\n\6\2)*\7"+
"\6\2\2*,\5\26\f\2+)\3\2\2\2+,\3\2\2\2,-\3\2\2\2-.\7\7\2\2.\7\3\2\2\2/"+
"\60\7*\2\2\60\61\7\5\2\2\61\64\5\n\6\2\62\63\7\6\2\2\63\65\5\26\f\2\64"+
"\62\3\2\2\2\64\65\3\2\2\2\65\66\3\2\2\2\66\67\7\7\2\2\67\t\3\2\2\289\b"+
"\6\1\29?\7\n\2\2:?\7\13\2\2;?\7\f\2\2<?\7\r\2\2=?\7\16\2\2>8\3\2\2\2>"+
":\3\2\2\2>;\3\2\2\2><\3\2\2\2>=\3\2\2\2?F\3\2\2\2@A\f\b\2\2AB\7\b\2\2"+
"BC\7&\2\2CE\7\t\2\2D@\3\2\2\2EH\3\2\2\2FD\3\2\2\2FG\3\2\2\2G\13\3\2\2"+
"\2HF\3\2\2\2IJ\7\17\2\2JK\7*\2\2KL\7\20\2\2LM\5\16\b\2MN\7\21\2\2NO\7"+
"\5\2\2OP\5\n\6\2PQ\5\22\n\2Q\r\3\2\2\2RW\5\20\t\2ST\7\22\2\2TV\5\20\t"+
"\2US\3\2\2\2VY\3\2\2\2WU\3\2\2\2WX\3\2\2\2X\17\3\2\2\2YW\3\2\2\2Z[\7*"+
"\2\2[\\\7\5\2\2\\]\5\n\6\2]\21\3\2\2\2^b\7\23\2\2_a\5\24\13\2`_\3\2\2"+
"\2ad\3\2\2\2b`\3\2\2\2bc\3\2\2\2ce\3\2\2\2db\3\2\2\2ef\7\24\2\2f\23\3"+
"\2\2\2g\u0086\5\22\n\2h\u0086\5\4\3\2ij\7\25\2\2jk\7\20\2\2kl\5\26\f\2"+
"lm\7\21\2\2mp\5\24\13\2no\7\26\2\2oq\5\24\13\2pn\3\2\2\2pq\3\2\2\2q\u0086"+
"\3\2\2\2rs\7\27\2\2st\7\20\2\2tu\5\26\f\2uv\7\21\2\2vw\5\24\13\2w\u0086"+
"\3\2\2\2xz\7\30\2\2y{\5\26\f\2zy\3\2\2\2z{\3\2\2\2{|\3\2\2\2|\u0086\7"+
"\7\2\2}~\5\26\f\2~\177\7\6\2\2\177\u0080\5\26\f\2\u0080\u0081\7\7\2\2"+
"\u0081\u0086\3\2\2\2\u0082\u0083\5\26\f\2\u0083\u0084\7\7\2\2\u0084\u0086"+
"\3\2\2\2\u0085g\3\2\2\2\u0085h\3\2\2\2\u0085i\3\2\2\2\u0085r\3\2\2\2\u0085"+
"x\3\2\2\2\u0085}\3\2\2\2\u0085\u0082\3\2\2\2\u0086\25\3\2\2\2\u0087\u0088"+
"\b\f\1\2\u0088\u0089\7\37\2\2\u0089\u009c\5\26\f\16\u008a\u008b\7 \2\2"+
"\u008b\u009c\5\26\f\r\u008c\u008d\7*\2\2\u008d\u008f\7\20\2\2\u008e\u0090"+
"\5\30\r\2\u008f\u008e\3\2\2\2\u008f\u0090\3\2\2\2\u0090\u0091\3\2\2\2"+
"\u0091\u009c\7\21\2\2\u0092\u009c\7*\2\2\u0093\u009c\7&\2\2\u0094\u009c"+
"\7\'\2\2\u0095\u009c\7(\2\2\u0096\u009c\7)\2\2\u0097\u0098\7\20\2\2\u0098"+
"\u0099\5\26\f\2\u0099\u009a\7\21\2\2\u009a\u009c\3\2\2\2\u009b\u0087\3"+
"\2\2\2\u009b\u008a\3\2\2\2\u009b\u008c\3\2\2\2\u009b\u0092\3\2\2\2\u009b"+
"\u0093\3\2\2\2\u009b\u0094\3\2\2\2\u009b\u0095\3\2\2\2\u009b\u0096\3\2"+
"\2\2\u009b\u0097\3\2\2\2\u009c\u00b6\3\2\2\2\u009d\u009e\f\20\2\2\u009e"+
"\u009f\t\2\2\2\u009f\u00b5\5\26\f\21\u00a0\u00a1\f\17\2\2\u00a1\u00a2"+
"\t\3\2\2\u00a2\u00b5\5\26\f\20\u00a3\u00a4\f\f\2\2\u00a4\u00a5\7!\2\2"+
"\u00a5\u00b5\5\26\f\r\u00a6\u00a7\f\13\2\2\u00a7\u00a8\7\"\2\2\u00a8\u00b5"+
"\5\26\f\f\u00a9\u00aa\f\n\2\2\u00aa\u00ab\t\4\2\2\u00ab\u00b5\5\26\f\13"+
"\u00ac\u00ad\f\t\2\2\u00ad\u00ae\t\5\2\2\u00ae\u00b5\5\26\f\n\u00af\u00b0"+
"\f\21\2\2\u00b0\u00b1\7\b\2\2\u00b1\u00b2\5\26\f\2\u00b2\u00b3\7\t\2\2"+
"\u00b3\u00b5\3\2\2\2\u00b4\u009d\3\2\2\2\u00b4\u00a0\3\2\2\2\u00b4\u00a3"+
"\3\2\2\2\u00b4\u00a6\3\2\2\2\u00b4\u00a9\3\2\2\2\u00b4\u00ac\3\2\2\2\u00b4"+
"\u00af\3\2\2\2\u00b5\u00b8\3\2\2\2\u00b6\u00b4\3\2\2\2\u00b6\u00b7\3\2"+
"\2\2\u00b7\27\3\2\2\2\u00b8\u00b6\3\2\2\2\u00b9\u00be\5\26\f\2\u00ba\u00bb"+
"\7\22\2\2\u00bb\u00bd\5\26\f\2\u00bc\u00ba\3\2\2\2\u00bd\u00c0\3\2\2\2"+
"\u00be\u00bc\3\2\2\2\u00be\u00bf\3\2\2\2\u00bf\31\3\2\2\2\u00c0\u00be"+
"\3\2\2\2\23\34\36$+\64>FWbpz\u0085\u008f\u009b\u00b4\u00b6\u00be";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} | true |
17bb005e88c5e6b5f16d294c00aca3772025d912 | Java | llkey221/javaweb | /springstudy/src/com/study/jdbc/TestJdbc.java | UTF-8 | 584 | 1.929688 | 2 | [
"MIT"
] | permissive | package com.study.jdbc;
import java.util.Scanner;
public class TestJdbc {
public static void main(String[] args) {
// JdbcCRUDStatement.Insert();
//
// JdbcCRUDStatement.Query();
//
// JdbcCRUDStatement.Update();
//
// JdbcCRUDStatement.Query();
//
// JdbcCRUDStatement.Delete();
// JdbcCURDByPreparedStatement.Insert();
//
// JdbcCURDByPreparedStatement.Query();
/* JdbcCURDByPreparedStatement.BatchSql();
JdbcCRUDStatement.BatchSql();*/
JdbcTransaction trans=new JdbcTransaction();
trans.SavaRollbackPoint();
trans.TransferAccount();
}
}
| true |
33f4dd87319319f865ea7f06cf21b3227df2fa13 | Java | dxysun/mini-server | /src/main/java/com/mini10/miniserver/model/ConditionTag.java | UTF-8 | 2,311 | 2.3125 | 2 | [] | no_license | package com.mini10.miniserver.model;
import java.util.Date;
import javax.persistence.*;
@Table(name = "condition_tag")
public class ConditionTag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String openId;
/**
* 自身标签名称
*/
@Column(name = "condition_tag_name")
private String conditionTagName;
/**
* 自身标签ID
*/
@Column(name = "condition_tag_id")
private Integer conditionTagId;
/**
* 用户添加该条件的时间
*/
@Column(name = "create_time")
private Date createTime;
/**
* @return id
*/
public Integer getId() {
return id;
}
/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return openId
*/
public String getOpenId() {
return openId;
}
/**
* @param openId
*/
public void setOpenId(String openId) {
this.openId = openId == null ? null : openId.trim();
}
/**
* 获取自身标签名称
*
* @return condition_tag_name - 自身标签名称
*/
public String getConditionTagName() {
return conditionTagName;
}
/**
* 设置自身标签名称
*
* @param conditionTagName 自身标签名称
*/
public void setConditionTagName(String conditionTagName) {
this.conditionTagName = conditionTagName == null ? null : conditionTagName.trim();
}
/**
* 获取自身标签ID
*
* @return condition_tag_id - 自身标签ID
*/
public Integer getConditionTagId() {
return conditionTagId;
}
/**
* 设置自身标签ID
*
* @param conditionTagId 自身标签ID
*/
public void setConditionTagId(Integer conditionTagId) {
this.conditionTagId = conditionTagId;
}
/**
* 获取用户添加该条件的时间
*
* @return create_time - 用户添加该条件的时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置用户添加该条件的时间
*
* @param createTime 用户添加该条件的时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
} | true |
53b2d5d8b0d76c8cbfd7ce206274332ce0bc8517 | Java | jagssonawane/nmonvisualizer | /src/com/ibm/nmon/parser/gc/GCParserContext.java | UTF-8 | 6,596 | 2.15625 | 2 | [
"Apache-2.0",
"MIT",
"CC-BY-2.5",
"LGPL-2.0-or-later"
] | permissive | package com.ibm.nmon.parser.gc;
import java.util.Map;
import java.util.TimeZone;
import org.slf4j.Logger;
import com.ibm.nmon.data.BasicDataSet;
import com.ibm.nmon.data.DataRecord;
import com.ibm.nmon.data.DataType;
import com.ibm.nmon.data.SubDataType;
import com.ibm.nmon.parser.util.XMLParserHelper;
/**
* Data holder for an in-progress GC parse session. Also contains various utility functions for
* setting values on the current DataRecord and logging errors.
*/
public final class GCParserContext {
private final Logger logger;
private final BasicDataSet data;
private DataRecord currentRecord;
private final TimeZone timeZone;
private int lineNumber;
private Map<String, String> attributes;
private boolean isGencon;
// verbose GC does not log a count of compactions
private int compactionCount;
GCParserContext(BasicDataSet data, Logger logger, TimeZone timeZone) {
this.data = data;
this.logger = logger;
this.timeZone = timeZone;
reset();
}
public void reset() {
currentRecord = null;
attributes = null;
lineNumber = 0;
isGencon = false;
compactionCount = 0;
}
public int getLineNumber() {
return lineNumber;
}
void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public BasicDataSet getData() {
return data;
}
public TimeZone getTimeZone() {
return timeZone;
}
public DataRecord getCurrentRecord() {
return currentRecord;
}
public void setCurrentRecord(DataRecord currentRecord) {
this.currentRecord = currentRecord;
}
public void saveRecord() {
data.addRecord(currentRecord);
}
public void setGencon(boolean isGencon) {
this.isGencon = isGencon;
}
public boolean isGencon() {
return isGencon;
}
public int incrementCompactionCount() {
return ++compactionCount;
}
public void resetCompactionCount() {
compactionCount = 0;
}
public void setValue(String typeId, String field, String attribute) {
String value = attributes.get(attribute);
if (value == null) {
logMissingAttribute(attribute);
return;
}
currentRecord.setValue(getDataType(typeId), field, parseDouble(attribute));
}
public void setValue(String typeId, String field, double value) {
currentRecord.setValue(getDataType(typeId), field, value);
}
public void setValueDiv1000(String typeId, String field, String name) {
String value = attributes.get(name);
if (value == null) {
logMissingAttribute(name);
return;
}
currentRecord.setValue(getDataType(typeId), field, parseDouble(name) / 1000);
}
public void parseAttributes(String unparsedAttributes) {
this.attributes = XMLParserHelper.parseAttributes(unparsedAttributes);
}
public String getAttribute(String name) {
return attributes.get(name);
}
public double parseDouble(String name) {
String value = attributes.get(name);
if (value == null) {
logMissingAttribute(name);
return Double.NaN;
}
double toReturn;
try {
toReturn = Double.parseDouble(value);
}
catch (NumberFormatException nfe) {
logger.warn("attribute '{}' with value '{}', defined at line {}, is not a number", new Object[] { name,
value, getLineNumber(), });
toReturn = Double.NaN;
}
return toReturn;
}
public void logMissingAttribute(String attribute) {
logger.warn("no attribute named {} defined at line {}", attribute, getLineNumber());
}
public void logUnrecognizedElement(String elementName) {
logger.warn("unrecogized element '{}' at line {}", elementName, getLineNumber());
}
public void logInvalidValue(String attribute, String value) {
logger.warn("attribute '{}' with value '{}', defined at line {}, is not a valid value", new Object[] {
attribute, value, getLineNumber() });
}
public DataType getDataType(String typeId) {
String jvmName = data.getMetadata("jvm_name");
SubDataType type = (SubDataType) data.getType(SubDataType.buildId(typeId, jvmName));
if (type != null) {
return type;
}
else if ("GCMEM".equals(typeId)) {
type = new SubDataType("GCMEM", jvmName, "GC Memory Stats", "requested", "total_freed", "nursery_freed",
"tenured_freed", "flipped", "flipped_bytes", "tenured", "tenured_bytes", "moved", "moved_bytes");
}
else if ("GCSTAT".equals(typeId)) {
type = new SubDataType("GCSTAT", jvmName, "GC Memory References", "finalizers", "soft", "weak", "phantom",
"tiltratio");
}
else if ("GCTIME".equals(typeId)) {
type = new SubDataType("GCTIME", jvmName, "GC Times (ms)", "total_ms", "nursery_ms", "tenured_ms",
"mark_ms", "sweep_ms", "compact_ms", "exclusive_ms");
}
else if ("GCSINCE".equals(typeId)) {
type = new SubDataType("GCSINCE", jvmName, "Time Since Last", "af_nursery", "af_tenured", "gc_scavenger",
"gc_global", "gc_system", "con_mark");
}
else if ("GCBEF".equals(typeId)) {
type = new SubDataType("GCBEF", jvmName, "Sizes Before GC", "total", "free", "used", "total_nursery",
"free_nursery", "used_nursery", "total_tenured", "free_tenured", "used_tenured");
}
else if ("GCAFT".equals(typeId)) {
type = new SubDataType("GCAFT", jvmName, "Sizes After GC", "total", "free", "used", "total_nursery",
"free_nursery", "used_nursery", "total_tenured", "free_tenured", "used_tenured");
}
else if ("GCCOUNT".equals(typeId)) {
type = new SubDataType("GCCOUNT", jvmName, "GC Counts", "total_count", "nursery_count", "tenured_count",
"compaction_count", "system_count");
}
else {
throw new IllegalArgumentException("invalid type " + typeId);
}
data.addType(type);
return type;
}
}
| true |
ee3f0eb7f1c6ceab195e84ce9b13b7da0cc0501c | Java | ytadavarthi/codeforgood-team6 | /gardN-android/app/src/main/java/gardn/codeforgood/com/gardn_android/helper/HttpsCertAuth.java | UTF-8 | 4,642 | 2.25 | 2 | [] | no_license | package gardn.codeforgood.com.gardn_android.helper;
import android.content.Context;
import com.loopj.android.http.MySSLSocketFactory;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManagerFactory;
import gardn.codeforgood.com.gardn_android.exception.MyRuntimeException;
public class HttpsCertAuth {
private static HttpsCertAuth ourInstance = new HttpsCertAuth();
private KeyStore keyStore;
private HttpsCertAuth(){
}
public static HttpsCertAuth getInstance() {
return ourInstance;
}
private Certificate loadCAFromInputStream(InputStream caInput){
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
throw new MyRuntimeException(e);
}
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca="+((X509Certificate) ca).getSubjectDN());
} catch (CertificateException e) {
throw new MyRuntimeException(e);
} finally {
try {
caInput.close();
} catch (IOException e) {
throw new MyRuntimeException(e);
}
}
return ca;
}
private KeyStore createKeystore(Certificate ca){
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
} catch (KeyStoreException e) {
throw new MyRuntimeException(e);
}
try {
keyStore.load(null, null);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
try {
keyStore.setCertificateEntry("ca", ca);
} catch (KeyStoreException e) {
e.printStackTrace();
}
return keyStore;
}
private TrustManagerFactory getTrustManagerFactory(){
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = null;
try {
tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
} catch (NoSuchAlgorithmException e) {
throw new MyRuntimeException(e);
}
return tmf;
}
public KeyStore initKeyStore(Context context, String fileName){
InputStream caInput = null;
try {
caInput = new BufferedInputStream(context.getAssets().open(fileName));
} catch (IOException e) {
throw new MyRuntimeException(e);
}
Certificate ca = loadCAFromInputStream(caInput);
keyStore = createKeystore(ca);
return keyStore;
}
public DefaultHttpClient getHttpsClient(){
try {
SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https",sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
}
| true |
520b74b70d587e214ab639382f7ddac2db11a88a | Java | yangbin-dl/logistics | /mf-item/mf-item-interface/src/main/java/com/mallfe/item/pojo/Pl.java | UTF-8 | 216 | 1.5 | 2 | [] | no_license | package com.mallfe.item.pojo;
import lombok.Data;
/**
* 描述
*
* @author yangbin
* @since 2019-08-13
*/
@Data
public class Pl {
private String plbm;
private String plmc;
private Integer level;
}
| true |
b25b4e8b5cbe147c98892757e4eda236135e1550 | Java | zjlasisi/yun | /src/main/java/com/technology/yun/controller/UserController.java | UTF-8 | 860 | 1.984375 | 2 | [] | no_license | package com.technology.yun.controller;
import com.technology.yun.db.model.User;
import com.technology.yun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Description TODO
* @Date 2020/09/01 18:27
* @Created by 陈康钟(15967160657@163.com)
*/
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUserById/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@RequestMapping("/getUserList")
public List<User> getUserList() {
return userService.getUserList();
}
}
| true |
b77e8869b94762a73e65e601233199b76d50233d | Java | skye66/graduation | /src/main/java/com/gdut/graduation/dao/OrderItemMapper.java | UTF-8 | 1,811 | 1.984375 | 2 | [] | no_license | package com.gdut.graduation.dao;
import com.gdut.graduation.pojo.OrderItem;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface OrderItemMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table graduation_order_item
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table graduation_order_item
*
* @mbggenerated
*/
int insert(OrderItem record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table graduation_order_item
*
* @mbggenerated
*/
OrderItem selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table graduation_order_item
*
* @mbggenerated
*/
List<OrderItem> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table graduation_order_item
*
* @mbggenerated
*/
int updateByPrimaryKey(OrderItem record);
/**
* 批量插入orderItem
* @param orderItemList
* @return
*/
int batchInsert(@Param("orderItemList") List<OrderItem> orderItemList);
/**
* 通过用户id和订单号查询详情
* @param userId
* @param orderNo
* @return
*/
List<OrderItem> selectByUserIdOrderNo(@Param("userId") Integer userId,@Param("orderNo") String orderNo);
/**
* 管理员查询某一订单
* @param orderNo
* @return
*/
List<OrderItem> selectByOrderNo(@Param("orderNo") String orderNo);
} | true |
6f487787b6082815e792fcac368275dc8ceaaf0f | Java | 710330668/MoreCharge | /app/src/main/java/com/example/hdd/morecharge/release/main/ui/activity/SearchAddressActivity.java | UTF-8 | 623 | 1.703125 | 2 | [] | no_license | package com.example.hdd.morecharge.release.main.ui.activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.hdd.common.BaseActivity;
import com.example.hdd.morecharge.R;
public class SearchAddressActivity extends BaseActivity {
@Override
public int bindLayout() {
return R.layout.activity_search_address;
}
@Override
public void initParams(Bundle params) {
}
@Override
public void setView(Bundle savedInstanceState) {
}
@Override
public void doBusiness(Context mContext) {
}
}
| true |
d3fc5b6e9a2150146ab99e93820aa4e80e26f3a9 | Java | Bekir-gy/arizatespit | /src/arizatespit/onarimbildir.java | UTF-8 | 574 | 1.898438 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arizatespit;
/**
*
* @author Acer
*/
class onarimbildir extends onarim{
/*public static void main(String[] args) {
onarim myonarim=new onarim();
onarim myekran=new ekranonarim();
onarim mychip=new chipsetonarim();
myekran.onarildi();
mychip.onarildi();
myonarim.onarildi();
}*/
}
| true |
a18f795e5c660669c7b2ae67026d2eb70383ff3a | Java | TaiwoOso/SimpleLeague | /app/src/main/java/com/example/simpleleague/fragments/CreateFragment.java | UTF-8 | 2,135 | 2.234375 | 2 | [] | no_license | package com.example.simpleleague.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.example.simpleleague.R;
import com.google.android.material.tabs.TabLayout;
public class CreateFragment extends Fragment {
public static final String TAG = "CreateFragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_create, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TabLayout tlCreate = view.findViewById(R.id.tlCreate);
FragmentManager fragmentManager = getChildFragmentManager();
Fragment textFragment = new CreateTextFragment();
Fragment imageFragment = new CreateImageFragment();
Fragment videoFragment = new CreateVideoFragment();
tlCreate.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
String text = tab.getText().toString();
Fragment fragment;
if (text.equals("Text")) {
fragment = textFragment;
} else if (text.equals("Image")) {
fragment = imageFragment;
} else {
fragment = videoFragment;
}
fragmentManager.beginTransaction().replace(R.id.flContainer, fragment).commit();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {}
@Override
public void onTabReselected(TabLayout.Tab tab) {}
});
fragmentManager.beginTransaction().replace(R.id.flContainer, textFragment).commit();
}
} | true |
2fadd25fb1f0c04f2d26741effa9c40260d21eff | Java | dewey00/RedRidingHood | /app/src/main/java/linhao/redridinghood/presenter/contract/NewsData.java | UTF-8 | 180 | 1.679688 | 2 | [] | no_license | package linhao.redridinghood.presenter.contract;
/**
* Created by linhao on 2016/9/3.
*/
public interface NewsData {
void getNewData();
void pageLoadMore(int page);
}
| true |
01d585ad1fe885397b6edcda16c5f1f477ba78e6 | Java | Zwiterrion/solitaire | /src/Projet/Pion/PionRectangulaire.java | UTF-8 | 797 | 2.984375 | 3 | [] | no_license | package Projet.Pion;
import Projet.Fenetre.FenetreGrille;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
public class PionRectangulaire extends PionBicolore {
public PionRectangulaire(FenetreGrille fenetreGrille, int posX, int posY) {
super(fenetreGrille, posX, posY);
}
@Override
public void definirPosition(Graphics2D g) {
int x = (int)(g.getClipBounds().getWidth() * 0.05);
int y = (int)(g.getClipBounds().getHeight() * 0.05);
((Rectangle2D.Float)pion).setRect(x, y,
(int) (g.getClipBounds().getWidth()) - x*2,
(int) (g.getClipBounds().getHeight()) - y*2);
}
@Override
public void construirePion() {
pion = new Rectangle2D.Float(0,0,0,0);
}
}
| true |
c78c0266817eabbcd92df09380a8bcd0f0a1cbb6 | Java | parkjaewon1/JavaClass | /JavaClass/src/ch03/If02.java | UHC | 441 | 3.390625 | 3 | [] | no_license | package ch03;
public class If02 {
public static void main(String[] args) {
//int i1 = 10 ;
//int i1 = Integer.parseInt(args[0]); ڸ ٲٴ°.
int i1 = Integer.parseInt(args[0]);
if(i1>0) {
System.out.println("Դϴ.");
System.out.println("ڴ"+i1+"Դϴ.");
}
else {
System.out.println("Դϴ.");
System.out.println("밪"+-i1+"Դϴ.");
}
}
}
| true |
9490e05017f571201a70bcc060292d0840a0c6ca | Java | cckmit/azz-porject | /azz-client-parent/azz-client-web/src/main/java/com/azz/controller/PermissionController.java | UTF-8 | 3,276 | 1.734375 | 2 | [] | no_license | /*******************************************************************************
* Project Key : CPPII
* Create on 2018年10月15日 下午3:05:46
* Copyright (c) 2018. 爱智造.
* 注意:本内容仅限于爱智造内部传阅,禁止外泄以及用于其他的商业目的
******************************************************************************/
package com.azz.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.azz.client.pojo.bo.AddRoleParam;
import com.azz.client.pojo.bo.DelRoleParam;
import com.azz.client.pojo.bo.EditRoleParam;
import com.azz.client.pojo.bo.SearchRoleParam;
import com.azz.client.pojo.bo.SetRolePermissionParam;
import com.azz.client.pojo.vo.Permission;
import com.azz.client.pojo.vo.RoleInfo;
import com.azz.client.user.api.PermissionService;
import com.azz.controller.utils.WebUtils;
import com.azz.core.common.JsonResult;
/**
*
* <P>
* 登录控制器
* </P>
*
* @version 1.0
* @author 黄智聪 2018年10月17日 下午1:42:55
*/
@RestController
@RequestMapping("/azz/api/client/permission")
public class PermissionController {
@Autowired
private PermissionService permissionService;
@RequestMapping("/getPermissionList")
public JsonResult<List<Permission>> getPermissionList(String roleCode) {
return permissionService.getPermissionList(WebUtils.getLoginClientUser().getClientUserInfo().getCompanyCode(), roleCode);
}
@RequestMapping("/addRole")
public JsonResult<String> addRole(AddRoleParam param) {
param.setCompanyCode(WebUtils.getLoginClientUser().getClientUserInfo().getCompanyCode());
param.setCreator(WebUtils.getLoginClientUser().getClientUserInfo().getClientUserCode());
return permissionService.addRole(param);
}
@RequestMapping("/editRole")
public JsonResult<String> editRole(EditRoleParam param) {
param.setCompanyCode(WebUtils.getLoginClientUser().getClientUserInfo().getCompanyCode());
param.setModifier(WebUtils.getLoginClientUser().getClientUserInfo().getClientUserCode());
return permissionService.editRole(param);
}
@RequestMapping("/delRole")
public JsonResult<String> delRole(DelRoleParam param) {
param.setModifier(WebUtils.getLoginClientUser().getClientUserInfo().getClientUserCode());
return permissionService.delRole(param);
}
@RequestMapping("/getRoleList")
public JsonResult<List<RoleInfo>> getRoleList(SearchRoleParam param) {
param.setCompanyCode(WebUtils.getLoginClientUser().getClientUserInfo().getCompanyCode());
return permissionService.getRoleList(param);
}
@RequestMapping("/getRolePermissions")
public JsonResult<List<String>> getRolePermissions(String roleCode) {
return permissionService.getRolePermissions(WebUtils.getLoginClientUser().getClientUserInfo().getCompanyCode(), roleCode);
}
@RequestMapping("/setRolePermissions")
public JsonResult<String> setRolePermissions(SetRolePermissionParam param) {
param.setCreator(WebUtils.getLoginClientUser().getClientUserInfo().getClientUserCode());
return permissionService.setRolePermissions(param);
}
}
| true |
9d40cece567bd8b835b2390b2190dc53d51f6253 | Java | lemuelhmgs/nd035-c3-data-stores-and-persistence-project-starter-master | /starter/critter/src/main/java/com/udacity/jdnd/course3/critter/service/ScheduleService.java | UTF-8 | 1,454 | 2.203125 | 2 | [
"MIT"
] | permissive | package com.udacity.jdnd.course3.critter.service;
import com.udacity.jdnd.course3.critter.entity.Schedule;
import com.udacity.jdnd.course3.critter.repository.CustomerRepository;
import com.udacity.jdnd.course3.critter.repository.EmployeeRepository;
import com.udacity.jdnd.course3.critter.repository.PetRepository;
import com.udacity.jdnd.course3.critter.repository.ScheduleRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ScheduleService {
@Autowired
ScheduleRepository scheduleRepository;
@Autowired
EmployeeRepository employeeRepository;
@Autowired
CustomerRepository customerRepository;
@Autowired
PetRepository petRepository;
public Schedule saveSchedule(Schedule schedule){
return scheduleRepository.save(schedule);
}
public List<Schedule> getAllSchedule(){
return scheduleRepository.findAll();
}
public List<Schedule> getScheduleForPet(Long petId){
return scheduleRepository.getDetailsByPet(petRepository.getOne(petId));
}
public List<Schedule> getScheduleForEmployee(Long employeeId){
return scheduleRepository.getDetailsByEmployee(employeeRepository.getOne(employeeId));
}
public List<Schedule> getScheduleForCustomer(Long petId){
return scheduleRepository.findByPet_Id(petId);
}
}
| true |
9510a4e9ceebd72ad644d9840339ca2ac95b891a | Java | verooonnika/MainTask2 | /src/by/epam/javatraining/veronikakhlopava/maintask02/model/entity/RootVegetable.java | UTF-8 | 426 | 2.46875 | 2 | [] | no_license | package by.epam.javatraining.veronikakhlopava.maintask02.model.entity;
public class RootVegetable extends Vegetable {
private static final String TYPE_OF_VEGETABLE = "Root Vegetable";
public RootVegetable() {
setType(TYPE_OF_VEGETABLE);
}
public RootVegetable(double caloriesPerHundredGrams, double weight) {
super(TYPE_OF_VEGETABLE, caloriesPerHundredGrams, weight);
}
}
| true |
2b9ab534689098cffe977c7923738cf7f0593474 | Java | SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018 | /Corpus/eclipse.jdt.debug/125.java | UTF-8 | 117,617 | 2.203125 | 2 | [
"MIT"
] | permissive | /*******************************************************************************
* Copyright (c) 2002, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.debug.tests.eval;
import org.eclipse.debug.core.model.IValue;
import org.eclipse.jdt.debug.core.IJavaPrimitiveValue;
import org.eclipse.jdt.internal.debug.core.model.JDIObjectValue;
public class LongOperatorsTests extends Tests {
public LongOperatorsTests(String arg) {
super(arg);
}
protected void init() throws Exception {
initializeFrame("EvalSimpleTests", 15, 1);
}
protected void end() throws Exception {
destroyFrame();
}
// long + {byte, char, short, int, long, float, double}
public void testLongPlusByte() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long plus byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus byte : wrong result : ", xLongValue + yByteValue, longValue);
value = eval(yLong + plusOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long plus byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus byte : wrong result : ", yLongValue + xByteValue, longValue);
} finally {
end();
}
}
public void testLongPlusChar() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long plus char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus char : wrong result : ", xLongValue + yCharValue, longValue);
value = eval(yLong + plusOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long plus char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus char : wrong result : ", yLongValue + xCharValue, longValue);
} finally {
end();
}
}
public void testLongPlusShort() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long plus short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus short : wrong result : ", xLongValue + yShortValue, longValue);
value = eval(yLong + plusOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long plus short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus short : wrong result : ", yLongValue + xShortValue, longValue);
} finally {
end();
}
}
public void testLongPlusInt() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long plus int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus int : wrong result : ", xLongValue + yIntValue, longValue);
value = eval(yLong + plusOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long plus int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus int : wrong result : ", yLongValue + xIntValue, longValue);
} finally {
end();
}
}
public void testLongPlusLong() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long plus long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus long : wrong result : ", xLongValue + yLongValue, longValue);
value = eval(yLong + plusOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long plus long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long plus long : wrong result : ", yLongValue + xLongValue, longValue);
} finally {
end();
}
}
public void testLongPlusFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long plus float : wrong type : ", "float", typeName);
float floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long plus float : wrong result : ", xLongValue + yFloatValue, floatValue, 0);
value = eval(yLong + plusOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long plus float : wrong type : ", "float", typeName);
floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long plus float : wrong result : ", yLongValue + xFloatValue, floatValue, 0);
} finally {
end();
}
}
public void testLongPlusDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long plus double : wrong type : ", "double", typeName);
double doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long plus double : wrong result : ", xLongValue + yDoubleValue, doubleValue, 0);
value = eval(yLong + plusOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long plus double : wrong type : ", "double", typeName);
doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long plus double : wrong result : ", yLongValue + xDoubleValue, doubleValue, 0);
} finally {
end();
}
}
public void testLongPlusString() throws Throwable {
try {
init();
IValue value = eval(xLong + plusOp + yString);
String typeName = value.getReferenceTypeName();
assertEquals("long plus java.lang.String : wrong type : ", "java.lang.String", typeName);
String stringValue = ((JDIObjectValue) value).getValueString();
assertEquals("long plus java.lang.String : wrong result : ", xLongValue + yStringValue, stringValue);
value = eval(yLong + plusOp + xString);
typeName = value.getReferenceTypeName();
assertEquals("long plus java.lang.String : wrong type : ", "java.lang.String", typeName);
stringValue = ((JDIObjectValue) value).getValueString();
assertEquals("long plus java.lang.String : wrong result : ", yLongValue + xStringValue, stringValue);
} finally {
end();
}
}
// long - {byte, char, short, int, long, float, double}
public void testLongMinusByte() throws Throwable {
try {
init();
IValue value = eval(xLong + minusOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long minus byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus byte : wrong result : ", xLongValue - yByteValue, longValue);
value = eval(yLong + minusOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long minus byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus byte : wrong result : ", yLongValue - xByteValue, longValue);
} finally {
end();
}
}
public void testLongMinusChar() throws Throwable {
try {
init();
IValue value = eval(xLong + minusOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long minus char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus char : wrong result : ", xLongValue - yCharValue, longValue);
value = eval(yLong + minusOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long minus char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus char : wrong result : ", yLongValue - xCharValue, longValue);
} finally {
end();
}
}
public void testLongMinusShort() throws Throwable {
try {
init();
IValue value = eval(xLong + minusOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long minus short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus short : wrong result : ", xLongValue - yShortValue, longValue);
value = eval(yLong + minusOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long minus short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus short : wrong result : ", yLongValue - xShortValue, longValue);
} finally {
end();
}
}
public void testLongMinusInt() throws Throwable {
try {
init();
IValue value = eval(xLong + minusOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long minus int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus int : wrong result : ", xLongValue - yIntValue, longValue);
value = eval(yLong + minusOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long minus int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus int : wrong result : ", yLongValue - xIntValue, longValue);
} finally {
end();
}
}
public void testLongMinusLong() throws Throwable {
try {
init();
IValue value = eval(xLong + minusOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long minus long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus long : wrong result : ", xLongValue - yLongValue, longValue);
value = eval(yLong + minusOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long minus long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long minus long : wrong result : ", yLongValue - xLongValue, longValue);
} finally {
end();
}
}
public void testLongMinusFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + minusOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long minus float : wrong type : ", "float", typeName);
float floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long minus float : wrong result : ", xLongValue - yFloatValue, floatValue, 0);
value = eval(yLong + minusOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long minus float : wrong type : ", "float", typeName);
floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long minus float : wrong result : ", yLongValue - xFloatValue, floatValue, 0);
} finally {
end();
}
}
public void testLongMinusDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + minusOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long minus double : wrong type : ", "double", typeName);
double doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long minus double : wrong result : ", xLongValue - yDoubleValue, doubleValue, 0);
value = eval(yLong + minusOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long minus double : wrong type : ", "double", typeName);
doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long minus double : wrong result : ", yLongValue - xDoubleValue, doubleValue, 0);
} finally {
end();
}
}
// long * {byte, char, short, int, long, float, double}
public void testLongMultiplyByte() throws Throwable {
try {
init();
IValue value = eval(xLong + multiplyOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long multiply byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply byte : wrong result : ", xLongValue * yByteValue, longValue);
value = eval(yLong + multiplyOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long multiply byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply byte : wrong result : ", yLongValue * xByteValue, longValue);
} finally {
end();
}
}
public void testLongMultiplyChar() throws Throwable {
try {
init();
IValue value = eval(xLong + multiplyOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long multiply char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply char : wrong result : ", xLongValue * yCharValue, longValue);
value = eval(yLong + multiplyOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long multiply char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply char : wrong result : ", yLongValue * xCharValue, longValue);
} finally {
end();
}
}
public void testLongMultiplyShort() throws Throwable {
try {
init();
IValue value = eval(xLong + multiplyOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long multiply short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply short : wrong result : ", xLongValue * yShortValue, longValue);
value = eval(yLong + multiplyOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long multiply short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply short : wrong result : ", yLongValue * xShortValue, longValue);
} finally {
end();
}
}
public void testLongMultiplyInt() throws Throwable {
try {
init();
IValue value = eval(xLong + multiplyOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long multiply int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply int : wrong result : ", xLongValue * yIntValue, longValue);
value = eval(yLong + multiplyOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long multiply int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply int : wrong result : ", yLongValue * xIntValue, longValue);
} finally {
end();
}
}
public void testLongMultiplyLong() throws Throwable {
try {
init();
IValue value = eval(xLong + multiplyOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long multiply long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply long : wrong result : ", xLongValue * yLongValue, longValue);
value = eval(yLong + multiplyOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long multiply long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long multiply long : wrong result : ", yLongValue * xLongValue, longValue);
} finally {
end();
}
}
public void testLongMultiplyFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + multiplyOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long multiply float : wrong type : ", "float", typeName);
float floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long multiply float : wrong result : ", xLongValue * yFloatValue, floatValue, 0);
value = eval(yLong + multiplyOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long multiply float : wrong type : ", "float", typeName);
floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long multiply float : wrong result : ", yLongValue * xFloatValue, floatValue, 0);
} finally {
end();
}
}
public void testLongMultiplyDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + multiplyOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long multiply double : wrong type : ", "double", typeName);
double doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long multiply double : wrong result : ", xLongValue * yDoubleValue, doubleValue, 0);
value = eval(yLong + multiplyOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long multiply double : wrong type : ", "double", typeName);
doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long multiply double : wrong result : ", yLongValue * xDoubleValue, doubleValue, 0);
} finally {
end();
}
}
// long / {byte, char, short, int, long, float, double}
public void testLongDivideByte() throws Throwable {
try {
init();
IValue value = eval(xLong + divideOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long divide byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide byte : wrong result : ", xLongValue / yByteValue, longValue);
value = eval(yLong + divideOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long divide byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide byte : wrong result : ", yLongValue / xByteValue, longValue);
} finally {
end();
}
}
public void testLongDivideChar() throws Throwable {
try {
init();
IValue value = eval(xLong + divideOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long divide char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide char : wrong result : ", xLongValue / yCharValue, longValue);
value = eval(yLong + divideOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long divide char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide char : wrong result : ", yLongValue / xCharValue, longValue);
} finally {
end();
}
}
public void testLongDivideShort() throws Throwable {
try {
init();
IValue value = eval(xLong + divideOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long divide short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide short : wrong result : ", xLongValue / yShortValue, longValue);
value = eval(yLong + divideOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long divide short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide short : wrong result : ", yLongValue / xShortValue, longValue);
} finally {
end();
}
}
public void testLongDivideInt() throws Throwable {
try {
init();
IValue value = eval(xLong + divideOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long divide int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide int : wrong result : ", xLongValue / yIntValue, longValue);
value = eval(yLong + divideOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long divide int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide int : wrong result : ", yLongValue / xIntValue, longValue);
} finally {
end();
}
}
public void testLongDivideLong() throws Throwable {
try {
init();
IValue value = eval(xLong + divideOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long divide long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide long : wrong result : ", xLongValue / yLongValue, longValue);
value = eval(yLong + divideOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long divide long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long divide long : wrong result : ", yLongValue / xLongValue, longValue);
} finally {
end();
}
}
public void testLongDivideFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + divideOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long divide float : wrong type : ", "float", typeName);
float floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long divide float : wrong result : ", xLongValue / yFloatValue, floatValue, 0);
value = eval(yLong + divideOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long divide float : wrong type : ", "float", typeName);
floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long divide float : wrong result : ", yLongValue / xFloatValue, floatValue, 0);
} finally {
end();
}
}
public void testLongDivideDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + divideOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long divide double : wrong type : ", "double", typeName);
double doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long divide double : wrong result : ", xLongValue / yDoubleValue, doubleValue, 0);
value = eval(yLong + divideOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long divide double : wrong type : ", "double", typeName);
doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long divide double : wrong result : ", yLongValue / xDoubleValue, doubleValue, 0);
} finally {
end();
}
}
// long % {byte, char, short, int, long, float, double}
public void testLongRemainderByte() throws Throwable {
try {
init();
IValue value = eval(xLong + remainderOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long remainder byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder byte : wrong result : ", xLongValue % yByteValue, longValue);
value = eval(yLong + remainderOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long remainder byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder byte : wrong result : ", yLongValue % xByteValue, longValue);
} finally {
end();
}
}
public void testLongRemainderChar() throws Throwable {
try {
init();
IValue value = eval(xLong + remainderOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long remainder char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder char : wrong result : ", xLongValue % yCharValue, longValue);
value = eval(yLong + remainderOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long remainder char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder char : wrong result : ", yLongValue % xCharValue, longValue);
} finally {
end();
}
}
public void testLongRemainderShort() throws Throwable {
try {
init();
IValue value = eval(xLong + remainderOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long remainder short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder short : wrong result : ", xLongValue % yShortValue, longValue);
value = eval(yLong + remainderOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long remainder short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder short : wrong result : ", yLongValue % xShortValue, longValue);
} finally {
end();
}
}
public void testLongRemainderInt() throws Throwable {
try {
init();
IValue value = eval(xLong + remainderOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long remainder int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder int : wrong result : ", xLongValue % yIntValue, longValue);
value = eval(yLong + remainderOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long remainder int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder int : wrong result : ", yLongValue % xIntValue, longValue);
} finally {
end();
}
}
public void testLongRemainderLong() throws Throwable {
try {
init();
IValue value = eval(xLong + remainderOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long remainder long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder long : wrong result : ", xLongValue % yLongValue, longValue);
value = eval(yLong + remainderOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long remainder long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long remainder long : wrong result : ", yLongValue % xLongValue, longValue);
} finally {
end();
}
}
public void testLongRemainderFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + remainderOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long remainder float : wrong type : ", "float", typeName);
float floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long remainder float : wrong result : ", xLongValue % yFloatValue, floatValue, 0);
value = eval(yLong + remainderOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long remainder float : wrong type : ", "float", typeName);
floatValue = ((IJavaPrimitiveValue) value).getFloatValue();
assertEquals("long remainder float : wrong result : ", yLongValue % xFloatValue, floatValue, 0);
} finally {
end();
}
}
public void testLongRemainderDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + remainderOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long remainder double : wrong type : ", "double", typeName);
double doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long remainder double : wrong result : ", xLongValue % yDoubleValue, doubleValue, 0);
value = eval(yLong + remainderOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long remainder double : wrong type : ", "double", typeName);
doubleValue = ((IJavaPrimitiveValue) value).getDoubleValue();
assertEquals("long remainder double : wrong result : ", yLongValue % xDoubleValue, doubleValue, 0);
} finally {
end();
}
}
// long > {byte, char, short, int, long, float, double}
public void testLongGreaterByte() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long greater byte : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater byte : wrong result : ", xLongValue > yByteValue, booleanValue);
value = eval(yLong + greaterOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long greater byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater byte : wrong result : ", yLongValue > xByteValue, booleanValue);
value = eval(xLong + greaterOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long greater byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater byte : wrong result : ", xLongValue > xByteValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterChar() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long greater char : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater char : wrong result : ", xLongValue > yCharValue, booleanValue);
value = eval(yLong + greaterOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long greater char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater char : wrong result : ", yLongValue > xCharValue, booleanValue);
value = eval(xLong + greaterOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long greater char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater char : wrong result : ", xLongValue > xCharValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterShort() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long greater short : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater short : wrong result : ", xLongValue > yShortValue, booleanValue);
value = eval(yLong + greaterOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long greater short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater short : wrong result : ", yLongValue > xShortValue, booleanValue);
value = eval(xLong + greaterOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long greater short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater short : wrong result : ", xLongValue > xShortValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterInt() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long greater int : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater int : wrong result : ", xLongValue > yIntValue, booleanValue);
value = eval(yLong + greaterOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long greater int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater int : wrong result : ", yLongValue > xIntValue, booleanValue);
value = eval(xLong + greaterOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long greater int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater int : wrong result : ", xLongValue > xIntValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterLong() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long greater long : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater long : wrong result : ", xLongValue > yLongValue, booleanValue);
value = eval(yLong + greaterOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long greater long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater long : wrong result : ", yLongValue > xLongValue, booleanValue);
value = eval(xLong + greaterOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long greater long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater long : wrong result : ", xLongValue > xLongValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long greater float : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater float : wrong result : ", xLongValue > yFloatValue, booleanValue);
value = eval(yLong + greaterOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long greater float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater float : wrong result : ", yLongValue > xFloatValue, booleanValue);
value = eval(xLong + greaterOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long greater float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater float : wrong result : ", xLongValue > xFloatValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long greater double : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater double : wrong result : ", xLongValue > yDoubleValue, booleanValue);
value = eval(yLong + greaterOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long greater double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater double : wrong result : ", yLongValue > xDoubleValue, booleanValue);
value = eval(xLong + greaterOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long greater double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greater double : wrong result : ", xLongValue > xDoubleValue, booleanValue);
} finally {
end();
}
}
// long >= {byte, char, short, int, long, float, double}
public void testLongGreaterEqualByte() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterEqualOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual byte : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual byte : wrong result : ", xLongValue >= yByteValue, booleanValue);
value = eval(yLong + greaterEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual byte : wrong result : ", yLongValue >= xByteValue, booleanValue);
value = eval(xLong + greaterEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual byte : wrong result : ", xLongValue >= xByteValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterEqualChar() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterEqualOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual char : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual char : wrong result : ", xLongValue >= yCharValue, booleanValue);
value = eval(yLong + greaterEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual char : wrong result : ", yLongValue >= xCharValue, booleanValue);
value = eval(xLong + greaterEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual char : wrong result : ", xLongValue >= xCharValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterEqualShort() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterEqualOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual short : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual short : wrong result : ", xLongValue >= yShortValue, booleanValue);
value = eval(yLong + greaterEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual short : wrong result : ", yLongValue >= xShortValue, booleanValue);
value = eval(xLong + greaterEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual short : wrong result : ", xLongValue >= xShortValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterEqualInt() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterEqualOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual int : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual int : wrong result : ", xLongValue >= yIntValue, booleanValue);
value = eval(yLong + greaterEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual int : wrong result : ", yLongValue >= xIntValue, booleanValue);
value = eval(xLong + greaterEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual int : wrong result : ", xLongValue >= xIntValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterEqualLong() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterEqualOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual long : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual long : wrong result : ", xLongValue >= yLongValue, booleanValue);
value = eval(yLong + greaterEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual long : wrong result : ", yLongValue >= xLongValue, booleanValue);
value = eval(xLong + greaterEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual long : wrong result : ", xLongValue >= xLongValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterEqualFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterEqualOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual float : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual float : wrong result : ", xLongValue >= yFloatValue, booleanValue);
value = eval(yLong + greaterEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual float : wrong result : ", yLongValue >= xFloatValue, booleanValue);
value = eval(xLong + greaterEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual float : wrong result : ", xLongValue >= xFloatValue, booleanValue);
} finally {
end();
}
}
public void testLongGreaterEqualDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + greaterEqualOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual double : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual double : wrong result : ", xLongValue >= yDoubleValue, booleanValue);
value = eval(yLong + greaterEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual double : wrong result : ", yLongValue >= xDoubleValue, booleanValue);
value = eval(xLong + greaterEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long greaterEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long greaterEqual double : wrong result : ", xLongValue >= xDoubleValue, booleanValue);
} finally {
end();
}
}
// long < {byte, char, short, int, long, float, double}
public void testLongLessByte() throws Throwable {
try {
init();
IValue value = eval(xLong + lessOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long less byte : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less byte : wrong result : ", xLongValue < yByteValue, booleanValue);
value = eval(yLong + lessOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long less byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less byte : wrong result : ", yLongValue < xByteValue, booleanValue);
value = eval(xLong + lessOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long less byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less byte : wrong result : ", xLongValue < xByteValue, booleanValue);
} finally {
end();
}
}
public void testLongLessChar() throws Throwable {
try {
init();
IValue value = eval(xLong + lessOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long less char : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less char : wrong result : ", xLongValue < yCharValue, booleanValue);
value = eval(yLong + lessOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long less char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less char : wrong result : ", yLongValue < xCharValue, booleanValue);
value = eval(xLong + lessOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long less char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less char : wrong result : ", xLongValue < xCharValue, booleanValue);
} finally {
end();
}
}
public void testLongLessShort() throws Throwable {
try {
init();
IValue value = eval(xLong + lessOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long less short : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less short : wrong result : ", xLongValue < yShortValue, booleanValue);
value = eval(yLong + lessOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long less short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less short : wrong result : ", yLongValue < xShortValue, booleanValue);
value = eval(xLong + lessOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long less short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less short : wrong result : ", xLongValue < xShortValue, booleanValue);
} finally {
end();
}
}
public void testLongLessInt() throws Throwable {
try {
init();
IValue value = eval(xLong + lessOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long less int : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less int : wrong result : ", xLongValue < yIntValue, booleanValue);
value = eval(yLong + lessOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long less int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less int : wrong result : ", yLongValue < xIntValue, booleanValue);
value = eval(xLong + lessOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long less int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less int : wrong result : ", xLongValue < xIntValue, booleanValue);
} finally {
end();
}
}
public void testLongLessLong() throws Throwable {
try {
init();
IValue value = eval(xLong + lessOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long less long : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less long : wrong result : ", xLongValue < yLongValue, booleanValue);
value = eval(yLong + lessOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long less long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less long : wrong result : ", yLongValue < xLongValue, booleanValue);
value = eval(xLong + lessOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long less long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less long : wrong result : ", xLongValue < xLongValue, booleanValue);
} finally {
end();
}
}
public void testLongLessFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + lessOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long less float : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less float : wrong result : ", xLongValue < yFloatValue, booleanValue);
value = eval(yLong + lessOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long less float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less float : wrong result : ", yLongValue < xFloatValue, booleanValue);
value = eval(xLong + lessOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long less float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less float : wrong result : ", xLongValue < xFloatValue, booleanValue);
} finally {
end();
}
}
public void testLongLessDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + lessOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long less double : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less double : wrong result : ", xLongValue < yDoubleValue, booleanValue);
value = eval(yLong + lessOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long less double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less double : wrong result : ", yLongValue < xDoubleValue, booleanValue);
value = eval(xLong + lessOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long less double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long less double : wrong result : ", xLongValue < xDoubleValue, booleanValue);
} finally {
end();
}
}
// long <= {byte, char, short, int, long, float, double}
public void testLongLessEqualByte() throws Throwable {
try {
init();
IValue value = eval(xLong + lessEqualOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long lessEqual byte : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual byte : wrong result : ", xLongValue <= yByteValue, booleanValue);
value = eval(yLong + lessEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual byte : wrong result : ", yLongValue <= xByteValue, booleanValue);
value = eval(xLong + lessEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual byte : wrong result : ", xLongValue <= xByteValue, booleanValue);
} finally {
end();
}
}
public void testLongLessEqualChar() throws Throwable {
try {
init();
IValue value = eval(xLong + lessEqualOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long lessEqual char : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual char : wrong result : ", xLongValue <= yCharValue, booleanValue);
value = eval(yLong + lessEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual char : wrong result : ", yLongValue <= xCharValue, booleanValue);
value = eval(xLong + lessEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual char : wrong result : ", xLongValue <= xCharValue, booleanValue);
} finally {
end();
}
}
public void testLongLessEqualShort() throws Throwable {
try {
init();
IValue value = eval(xLong + lessEqualOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long lessEqual short : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual short : wrong result : ", xLongValue <= yShortValue, booleanValue);
value = eval(yLong + lessEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual short : wrong result : ", yLongValue <= xShortValue, booleanValue);
value = eval(xLong + lessEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual short : wrong result : ", xLongValue <= xShortValue, booleanValue);
} finally {
end();
}
}
public void testLongLessEqualInt() throws Throwable {
try {
init();
IValue value = eval(xLong + lessEqualOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long lessEqual int : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual int : wrong result : ", xLongValue <= yIntValue, booleanValue);
value = eval(yLong + lessEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual int : wrong result : ", yLongValue <= xIntValue, booleanValue);
value = eval(xLong + lessEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual int : wrong result : ", xLongValue <= xIntValue, booleanValue);
} finally {
end();
}
}
public void testLongLessEqualLong() throws Throwable {
try {
init();
IValue value = eval(xLong + lessEqualOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long lessEqual long : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual long : wrong result : ", xLongValue <= yLongValue, booleanValue);
value = eval(yLong + lessEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual long : wrong result : ", yLongValue <= xLongValue, booleanValue);
value = eval(xLong + lessEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual long : wrong result : ", xLongValue <= xLongValue, booleanValue);
} finally {
end();
}
}
public void testLongLessEqualFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + lessEqualOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long lessEqual float : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual float : wrong result : ", xLongValue <= yFloatValue, booleanValue);
value = eval(yLong + lessEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual float : wrong result : ", yLongValue <= xFloatValue, booleanValue);
value = eval(xLong + lessEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual float : wrong result : ", xLongValue <= xFloatValue, booleanValue);
} finally {
end();
}
}
public void testLongLessEqualDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + lessEqualOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long lessEqual double : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual double : wrong result : ", xLongValue <= yDoubleValue, booleanValue);
value = eval(yLong + lessEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual double : wrong result : ", yLongValue <= xDoubleValue, booleanValue);
value = eval(xLong + lessEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long lessEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long lessEqual double : wrong result : ", xLongValue <= xDoubleValue, booleanValue);
} finally {
end();
}
}
// long == {byte, char, short, int, long, float, double}
public void testLongEqualEqualByte() throws Throwable {
try {
init();
IValue value = eval(xLong + equalEqualOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long equalEqual byte : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual byte : wrong result : ", xLongValue == yByteValue, booleanValue);
value = eval(yLong + equalEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual byte : wrong result : ", yLongValue == xByteValue, booleanValue);
value = eval(xLong + equalEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual byte : wrong result : ", xLongValue == xByteValue, booleanValue);
} finally {
end();
}
}
public void testLongEqualEqualChar() throws Throwable {
try {
init();
IValue value = eval(xLong + equalEqualOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long equalEqual char : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual char : wrong result : ", xLongValue == yCharValue, booleanValue);
value = eval(yLong + equalEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual char : wrong result : ", yLongValue == xCharValue, booleanValue);
value = eval(xLong + equalEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual char : wrong result : ", xLongValue == xCharValue, booleanValue);
} finally {
end();
}
}
public void testLongEqualEqualShort() throws Throwable {
try {
init();
IValue value = eval(xLong + equalEqualOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long equalEqual short : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual short : wrong result : ", xLongValue == yShortValue, booleanValue);
value = eval(yLong + equalEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual short : wrong result : ", yLongValue == xShortValue, booleanValue);
value = eval(xLong + equalEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual short : wrong result : ", xLongValue == xShortValue, booleanValue);
} finally {
end();
}
}
public void testLongEqualEqualInt() throws Throwable {
try {
init();
IValue value = eval(xLong + equalEqualOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long equalEqual int : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual int : wrong result : ", xLongValue == yIntValue, booleanValue);
value = eval(yLong + equalEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual int : wrong result : ", yLongValue == xIntValue, booleanValue);
value = eval(xLong + equalEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual int : wrong result : ", xLongValue == xIntValue, booleanValue);
} finally {
end();
}
}
public void testLongEqualEqualLong() throws Throwable {
try {
init();
IValue value = eval(xLong + equalEqualOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long equalEqual long : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual long : wrong result : ", xLongValue == yLongValue, booleanValue);
value = eval(yLong + equalEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual long : wrong result : ", yLongValue == xLongValue, booleanValue);
value = eval(xLong + equalEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual long : wrong result : ", true, booleanValue);
} finally {
end();
}
}
public void testLongEqualEqualFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + equalEqualOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long equalEqual float : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual float : wrong result : ", xLongValue == yFloatValue, booleanValue);
value = eval(yLong + equalEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual float : wrong result : ", yLongValue == xFloatValue, booleanValue);
value = eval(xLong + equalEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual float : wrong result : ", xLongValue == xFloatValue, booleanValue);
} finally {
end();
}
}
public void testLongEqualEqualDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + equalEqualOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long equalEqual double : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual double : wrong result : ", xLongValue == yDoubleValue, booleanValue);
value = eval(yLong + equalEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual double : wrong result : ", yLongValue == xDoubleValue, booleanValue);
value = eval(xLong + equalEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long equalEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long equalEqual double : wrong result : ", xLongValue == xDoubleValue, booleanValue);
} finally {
end();
}
}
// long != {byte, char, short, int, long, float, double}
public void testLongNotEqualByte() throws Throwable {
try {
init();
IValue value = eval(xLong + notEqualOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long notEqual byte : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual byte : wrong result : ", xLongValue != yByteValue, booleanValue);
value = eval(yLong + notEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual byte : wrong result : ", yLongValue != xByteValue, booleanValue);
value = eval(xLong + notEqualOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual byte : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual byte : wrong result : ", xLongValue != xByteValue, booleanValue);
} finally {
end();
}
}
public void testLongNotEqualChar() throws Throwable {
try {
init();
IValue value = eval(xLong + notEqualOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long notEqual char : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual char : wrong result : ", xLongValue != yCharValue, booleanValue);
value = eval(yLong + notEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual char : wrong result : ", yLongValue != xCharValue, booleanValue);
value = eval(xLong + notEqualOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual char : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual char : wrong result : ", xLongValue != xCharValue, booleanValue);
} finally {
end();
}
}
public void testLongNotEqualShort() throws Throwable {
try {
init();
IValue value = eval(xLong + notEqualOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long notEqual short : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual short : wrong result : ", xLongValue != yShortValue, booleanValue);
value = eval(yLong + notEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual short : wrong result : ", yLongValue != xShortValue, booleanValue);
value = eval(xLong + notEqualOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual short : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual short : wrong result : ", xLongValue != xShortValue, booleanValue);
} finally {
end();
}
}
public void testLongNotEqualInt() throws Throwable {
try {
init();
IValue value = eval(xLong + notEqualOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long notEqual int : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual int : wrong result : ", xLongValue != yIntValue, booleanValue);
value = eval(yLong + notEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual int : wrong result : ", yLongValue != xIntValue, booleanValue);
value = eval(xLong + notEqualOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual int : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual int : wrong result : ", xLongValue != xIntValue, booleanValue);
} finally {
end();
}
}
public void testLongNotEqualLong() throws Throwable {
try {
init();
IValue value = eval(xLong + notEqualOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long notEqual long : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual long : wrong result : ", xLongValue != yLongValue, booleanValue);
value = eval(yLong + notEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual long : wrong result : ", yLongValue != xLongValue, booleanValue);
value = eval(xLong + notEqualOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual long : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual long : wrong result : ", false, booleanValue);
} finally {
end();
}
}
public void testLongNotEqualFloat() throws Throwable {
try {
init();
IValue value = eval(xLong + notEqualOp + yFloat);
String typeName = value.getReferenceTypeName();
assertEquals("long notEqual float : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual float : wrong result : ", xLongValue != yFloatValue, booleanValue);
value = eval(yLong + notEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual float : wrong result : ", yLongValue != xFloatValue, booleanValue);
value = eval(xLong + notEqualOp + xFloat);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual float : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual float : wrong result : ", xLongValue != xFloatValue, booleanValue);
} finally {
end();
}
}
public void testLongNotEqualDouble() throws Throwable {
try {
init();
IValue value = eval(xLong + notEqualOp + yDouble);
String typeName = value.getReferenceTypeName();
assertEquals("long notEqual double : wrong type : ", "boolean", typeName);
boolean booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual double : wrong result : ", xLongValue != yDoubleValue, booleanValue);
value = eval(yLong + notEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual double : wrong result : ", yLongValue != xDoubleValue, booleanValue);
value = eval(xLong + notEqualOp + xDouble);
typeName = value.getReferenceTypeName();
assertEquals("long notEqual double : wrong type : ", "boolean", typeName);
booleanValue = ((IJavaPrimitiveValue) value).getBooleanValue();
assertEquals("long notEqual double : wrong result : ", xLongValue != xDoubleValue, booleanValue);
} finally {
end();
}
}
// long << {byte, char, short, int, long}
public void testLongLeftShiftByte() throws Throwable {
try {
init();
IValue value = eval(xLong + leftShiftOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long leftShift byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift byte : wrong result : ", xLongValue << yByteValue, longValue);
value = eval(yLong + leftShiftOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long leftShift byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift byte : wrong result : ", yLongValue << xByteValue, longValue);
} finally {
end();
}
}
public void testLongLeftShiftChar() throws Throwable {
try {
init();
IValue value = eval(xLong + leftShiftOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long leftShift char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift char : wrong result : ", xLongValue << yCharValue, longValue);
value = eval(yLong + leftShiftOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long leftShift char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift char : wrong result : ", yLongValue << xCharValue, longValue);
} finally {
end();
}
}
public void testLongLeftShiftShort() throws Throwable {
try {
init();
IValue value = eval(xLong + leftShiftOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long leftShift short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift short : wrong result : ", xLongValue << yShortValue, longValue);
value = eval(yLong + leftShiftOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long leftShift short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift short : wrong result : ", yLongValue << xShortValue, longValue);
} finally {
end();
}
}
public void testLongLeftShiftInt() throws Throwable {
try {
init();
IValue value = eval(xLong + leftShiftOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long leftShift int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift int : wrong result : ", xLongValue << yIntValue, longValue);
value = eval(yLong + leftShiftOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long leftShift int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift int : wrong result : ", yLongValue << xIntValue, longValue);
} finally {
end();
}
}
public void testLongLeftShiftLong() throws Throwable {
try {
init();
IValue value = eval(xLong + leftShiftOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long leftShift long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift long : wrong result : ", xLongValue << yLongValue, longValue);
value = eval(yLong + leftShiftOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long leftShift long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long leftShift long : wrong result : ", yLongValue << xLongValue, longValue);
} finally {
end();
}
}
// long >> {byte, char, short, int, long}
public void testLongRightShiftByte() throws Throwable {
try {
init();
IValue value = eval(xLong + rightShiftOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long rightShift byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift byte : wrong result : ", xLongValue >> yByteValue, longValue);
value = eval(yLong + rightShiftOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long rightShift byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift byte : wrong result : ", yLongValue >> xByteValue, longValue);
} finally {
end();
}
}
public void testLongRightShiftChar() throws Throwable {
try {
init();
IValue value = eval(xLong + rightShiftOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long rightShift char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift char : wrong result : ", xLongValue >> yCharValue, longValue);
value = eval(yLong + rightShiftOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long rightShift char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift char : wrong result : ", yLongValue >> xCharValue, longValue);
} finally {
end();
}
}
public void testLongRightShiftShort() throws Throwable {
try {
init();
IValue value = eval(xLong + rightShiftOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long rightShift short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift short : wrong result : ", xLongValue >> yShortValue, longValue);
value = eval(yLong + rightShiftOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long rightShift short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift short : wrong result : ", yLongValue >> xShortValue, longValue);
} finally {
end();
}
}
public void testLongRightShiftInt() throws Throwable {
try {
init();
IValue value = eval(xLong + rightShiftOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long rightShift int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift int : wrong result : ", xLongValue >> yIntValue, longValue);
value = eval(yLong + rightShiftOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long rightShift int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift int : wrong result : ", yLongValue >> xIntValue, longValue);
} finally {
end();
}
}
public void testLongRightShiftLong() throws Throwable {
try {
init();
IValue value = eval(xLong + rightShiftOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long rightShift long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift long : wrong result : ", xLongValue >> yLongValue, longValue);
value = eval(yLong + rightShiftOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long rightShift long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long rightShift long : wrong result : ", yLongValue >> xLongValue, longValue);
} finally {
end();
}
}
// long >>> {byte, char, short, int, long}
public void testLongUnsignedRightShiftByte() throws Throwable {
try {
init();
IValue value = eval(xLong + unsignedRightShiftOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift byte : wrong result : ", xLongValue >>> yByteValue, longValue);
value = eval(yLong + unsignedRightShiftOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift byte : wrong result : ", yLongValue >>> xByteValue, longValue);
} finally {
end();
}
}
public void testLongUnsignedRightShiftChar() throws Throwable {
try {
init();
IValue value = eval(xLong + unsignedRightShiftOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift char : wrong result : ", xLongValue >>> yCharValue, longValue);
value = eval(yLong + unsignedRightShiftOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift char : wrong result : ", yLongValue >>> xCharValue, longValue);
} finally {
end();
}
}
public void testLongUnsignedRightShiftShort() throws Throwable {
try {
init();
IValue value = eval(xLong + unsignedRightShiftOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift short : wrong result : ", xLongValue >>> yShortValue, longValue);
value = eval(yLong + unsignedRightShiftOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift short : wrong result : ", yLongValue >>> xShortValue, longValue);
} finally {
end();
}
}
public void testLongUnsignedRightShiftInt() throws Throwable {
try {
init();
IValue value = eval(xLong + unsignedRightShiftOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift int : wrong result : ", xLongValue >>> yIntValue, longValue);
value = eval(yLong + unsignedRightShiftOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift int : wrong result : ", yLongValue >>> xIntValue, longValue);
} finally {
end();
}
}
public void testLongUnsignedRightShiftLong() throws Throwable {
try {
init();
IValue value = eval(xLong + unsignedRightShiftOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift long : wrong result : ", xLongValue >>> yLongValue, longValue);
value = eval(yLong + unsignedRightShiftOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long unsignedRightShift long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long unsignedRightShift long : wrong result : ", yLongValue >>> xLongValue, longValue);
} finally {
end();
}
}
// long | {byte, char, short, int, long}
public void testLongOrByte() throws Throwable {
try {
init();
IValue value = eval(xLong + orOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long or byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or byte : wrong result : ", xLongValue | yByteValue, longValue);
value = eval(yLong + orOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long or byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or byte : wrong result : ", yLongValue | xByteValue, longValue);
} finally {
end();
}
}
public void testLongOrChar() throws Throwable {
try {
init();
IValue value = eval(xLong + orOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long or char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or char : wrong result : ", xLongValue | yCharValue, longValue);
value = eval(yLong + orOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long or char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or char : wrong result : ", yLongValue | xCharValue, longValue);
} finally {
end();
}
}
public void testLongOrShort() throws Throwable {
try {
init();
IValue value = eval(xLong + orOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long or short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or short : wrong result : ", xLongValue | yShortValue, longValue);
value = eval(yLong + orOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long or short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or short : wrong result : ", yLongValue | xShortValue, longValue);
} finally {
end();
}
}
public void testLongOrInt() throws Throwable {
try {
init();
IValue value = eval(xLong + orOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long or int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or int : wrong result : ", xLongValue | yIntValue, longValue);
value = eval(yLong + orOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long or int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or int : wrong result : ", yLongValue | xIntValue, longValue);
} finally {
end();
}
}
public void testLongOrLong() throws Throwable {
try {
init();
IValue value = eval(xLong + orOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long or long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or long : wrong result : ", xLongValue | yLongValue, longValue);
value = eval(yLong + orOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long or long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long or long : wrong result : ", yLongValue | xLongValue, longValue);
} finally {
end();
}
}
// long & {byte, char, short, int, long}
public void testLongAndByte() throws Throwable {
try {
init();
IValue value = eval(xLong + andOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long and byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and byte : wrong result : ", xLongValue & yByteValue, longValue);
value = eval(yLong + andOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long and byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and byte : wrong result : ", yLongValue & xByteValue, longValue);
} finally {
end();
}
}
public void testLongAndChar() throws Throwable {
try {
init();
IValue value = eval(xLong + andOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long and char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and char : wrong result : ", xLongValue & yCharValue, longValue);
value = eval(yLong + andOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long and char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and char : wrong result : ", yLongValue & xCharValue, longValue);
} finally {
end();
}
}
public void testLongAndShort() throws Throwable {
try {
init();
IValue value = eval(xLong + andOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long and short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and short : wrong result : ", xLongValue & yShortValue, longValue);
value = eval(yLong + andOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long and short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and short : wrong result : ", yLongValue & xShortValue, longValue);
} finally {
end();
}
}
public void testLongAndInt() throws Throwable {
try {
init();
IValue value = eval(xLong + andOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long and int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and int : wrong result : ", xLongValue & yIntValue, longValue);
value = eval(yLong + andOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long and int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and int : wrong result : ", yLongValue & xIntValue, longValue);
} finally {
end();
}
}
public void testLongAndLong() throws Throwable {
try {
init();
IValue value = eval(xLong + andOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long and long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and long : wrong result : ", xLongValue & yLongValue, longValue);
value = eval(yLong + andOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long and long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long and long : wrong result : ", yLongValue & xLongValue, longValue);
} finally {
end();
}
}
// long ^ {byte, char, short, int, long}
public void testLongXorByte() throws Throwable {
try {
init();
IValue value = eval(xLong + xorOp + yByte);
String typeName = value.getReferenceTypeName();
assertEquals("long xor byte : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor byte : wrong result : ", xLongValue ^ yByteValue, longValue);
value = eval(yLong + xorOp + xByte);
typeName = value.getReferenceTypeName();
assertEquals("long xor byte : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor byte : wrong result : ", yLongValue ^ xByteValue, longValue);
} finally {
end();
}
}
public void testLongXorChar() throws Throwable {
try {
init();
IValue value = eval(xLong + xorOp + yChar);
String typeName = value.getReferenceTypeName();
assertEquals("long xor char : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor char : wrong result : ", xLongValue ^ yCharValue, longValue);
value = eval(yLong + xorOp + xChar);
typeName = value.getReferenceTypeName();
assertEquals("long xor char : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor char : wrong result : ", yLongValue ^ xCharValue, longValue);
} finally {
end();
}
}
public void testLongXorShort() throws Throwable {
try {
init();
IValue value = eval(xLong + xorOp + yShort);
String typeName = value.getReferenceTypeName();
assertEquals("long xor short : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor short : wrong result : ", xLongValue ^ yShortValue, longValue);
value = eval(yLong + xorOp + xShort);
typeName = value.getReferenceTypeName();
assertEquals("long xor short : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor short : wrong result : ", yLongValue ^ xShortValue, longValue);
} finally {
end();
}
}
public void testLongXorInt() throws Throwable {
try {
init();
IValue value = eval(xLong + xorOp + yInt);
String typeName = value.getReferenceTypeName();
assertEquals("long xor int : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor int : wrong result : ", xLongValue ^ yIntValue, longValue);
value = eval(yLong + xorOp + xInt);
typeName = value.getReferenceTypeName();
assertEquals("long xor int : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor int : wrong result : ", yLongValue ^ xIntValue, longValue);
} finally {
end();
}
}
public void testLongXorLong() throws Throwable {
try {
init();
IValue value = eval(xLong + xorOp + yLong);
String typeName = value.getReferenceTypeName();
assertEquals("long xor long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor long : wrong result : ", xLongValue ^ yLongValue, longValue);
value = eval(yLong + xorOp + xLong);
typeName = value.getReferenceTypeName();
assertEquals("long xor long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("long xor long : wrong result : ", yLongValue ^ xLongValue, longValue);
} finally {
end();
}
}
// + long
public void testPlusLong() throws Throwable {
try {
init();
IValue value = eval(plusOp + xLong);
String typeName = value.getReferenceTypeName();
assertEquals("plus long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("plus long : wrong result : ", +xLongValue, longValue);
value = eval(plusOp + yLong);
typeName = value.getReferenceTypeName();
assertEquals("plus long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("plus long : wrong result : ", +yLongValue, longValue);
} finally {
end();
}
}
// - long
public void testMinusLong() throws Throwable {
try {
init();
IValue value = eval(minusOp + xLong);
String typeName = value.getReferenceTypeName();
assertEquals("minus long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("minus long : wrong result : ", -xLongValue, longValue);
value = eval(minusOp + yLong);
typeName = value.getReferenceTypeName();
assertEquals("minus long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("minus long : wrong result : ", -yLongValue, longValue);
} finally {
end();
}
}
// ~ long
public void testTwiddleLong() throws Throwable {
try {
init();
IValue value = eval(twiddleOp + xLong);
String typeName = value.getReferenceTypeName();
assertEquals("twiddle long : wrong type : ", "long", typeName);
long longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("twiddle long : wrong result : ", ~xLongValue, longValue);
value = eval(twiddleOp + yLong);
typeName = value.getReferenceTypeName();
assertEquals("twiddle long : wrong type : ", "long", typeName);
longValue = ((IJavaPrimitiveValue) value).getLongValue();
assertEquals("twiddle long : wrong result : ", ~yLongValue, longValue);
} finally {
end();
}
}
}
| true |
2af7ef981db9733a660c1c968bb7d1125d61a60c | Java | shreekulkarni/conglomerate-public | /server/src/test/java/com/conglomerate/dev/integration/users/TestLinkGoogle.java | UTF-8 | 908 | 2.078125 | 2 | [] | no_license | package com.conglomerate.dev.integration.users;
import com.conglomerate.dev.integration.TestingUtils;
import org.junit.Test;
public class TestLinkGoogle {
@Test
public void linkGoogleSuccess() throws Exception {
// CREATE USER AND LOGIN
String authToken = TestingUtils.createUserAndLoginSuccess("linkGoogleSuccess",
"linkGoogleSuccess@email.com",
"linkGoogleSuccess");
// LINK GOOGLE (200 success)
int userId = TestingUtils.linkGoogleAndExpect(authToken, "id", "refresh", 200);
}
@Test
public void linkGoogleBadAuth() throws Exception {
// CREATE USER AND LOGIN
TestingUtils.createUserAndLoginSuccess("linkGoogleBadAuth",
"linkGoogleBadAuth@email.com",
"linkGoogleBadAuth");
// LINK GOOGLE (400 ERROR)
int userId = TestingUtils.linkGoogleAndExpect("bad auth", "id", "refresh", 400);
}
}
| true |
3db6ad97605e6826a492696cdb9c2fd439e30078 | Java | sadia123-del/test | /src/main/java/com/crud/demo/Domain/Course.java | UTF-8 | 1,195 | 2.53125 | 3 | [] | no_license | package com.crud.demo.Domain;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.persistence.*;
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int courseId;
private int course_code;
private String course_title;
@ManyToOne
@JsonBackReference
private Semester semester;
public Course() {
}
public Course(int course_code, String course_title) {
this.course_code = course_code;
this.course_title = course_title;
}
public Semester getSemester() {
return semester;
}
public void setSemester(Semester semester) {
this.semester = semester;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public int getCourse_code() {
return course_code;
}
public void setCourse_code(int course_code) {
this.course_code = course_code;
}
public String getCourse_title() {
return course_title;
}
public void setCourse_title(String course_title) {
this.course_title = course_title;
}
}
| true |
a249c973a726be340a49446c79dd1d0705d8ba52 | Java | KansaraDarshan/IBM_JAVA_FSD_REPO | /Spider/src/com/ibm/streaming/Subscription.java | UTF-8 | 1,277 | 2.84375 | 3 | [] | no_license | package com.ibm.streaming;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Subscription {
private User user;
private String plan;
private LocalDate expiry;
private static final int MONTHLY=100;
private static final int YEARLY=1000;
public Subscription() {
// TODO Auto-generated constructor stub
}
public String getPlan() {
return plan;
}
public void setPlan(String plan) {
this.plan = plan;
}
public LocalDate getExpiry() {
return expiry;
}
public void setExpiry(LocalDate expiry) {
this.expiry = expiry;
}
public void subscribe(String plan, User user) throws SubscriptionException
{
if(plan.equalsIgnoreCase("Monthly") && user.getBalance()>=MONTHLY)
{
user.setBalance(user.getBalance()-MONTHLY);
user.setSubscription(this);
expiry=LocalDate.now().plus(1,ChronoUnit.MONTHS);
this.plan=plan;
}
else if(plan.equalsIgnoreCase("Yearly") && user.getBalance()>=YEARLY)
{
System.out.println("user getBal: "+user.getBalance());
user.setBalance(user.getBalance()-YEARLY);
user.setSubscription(this);
expiry=LocalDate.now().plus(1,ChronoUnit.YEARS);
this.plan=plan;
}
else
throw new SubscriptionException("Insuff balance against the subscription");
}
}
| true |
a8ee509bcfc9d7b35163640fc5218c0278799930 | Java | Meeelz/KomeijiMod | /java/Thmod/Cards/DeriveCards/WeatherTest.java | UTF-8 | 2,567 | 1.6875 | 2 | [] | no_license | package Thmod.Cards.DeriveCards;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.MathUtils;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.common.ApplyPowerAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import com.megacrit.cardcrawl.powers.FadingPower;
import com.megacrit.cardcrawl.unlock.UnlockTracker;
import java.util.ArrayList;
import Thmod.Actions.Special.MusouFuuyinAction;
import Thmod.Actions.common.TenseiAttackAction;
import Thmod.Power.MusouTenseiPower;
import Thmod.Power.TimeLockPower;
import Thmod.Power.Weather.Fuuu;
import Thmod.Power.Weather.Haku;
import Thmod.Power.Weather.KawaGiri;
import Thmod.Power.Weather.KiriSame;
import Thmod.Power.Weather.KyoKkou;
import Thmod.Power.Weather.Nagi;
import Thmod.Power.Weather.NouMu;
import Thmod.Power.Weather.Soyuki;
import Thmod.Power.Weather.TenkiYume;
import Thmod.Power.WocchiPower;
import Thmod.vfx.JyouchiEffect;
import Thmod.vfx.JyouchiReiEffect;
import Thmod.vfx.MusouFuuinEffect;
import basemod.DevConsole;
public class WeatherTest extends AbstractDeriveCards {
public static final String ID = "WeatherTest";
private static final CardStrings cardStrings;
public static final String NAME;
public static final String DESCRIPTION;
private static final int COST = 0;
private ArrayList<AbstractCreature> target = new ArrayList<>();
public WeatherTest() {
super("WeatherTest", WeatherTest.NAME, 0, WeatherTest.DESCRIPTION, CardType.SKILL, CardRarity.SPECIAL, CardTarget.ENEMY);
}
public void use(final AbstractPlayer p, final AbstractMonster m) {
AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(p, p, new Nagi(p)));
//AbstractDungeon.actionManager.addToBottom(new TenseiAttackAction(1, p.hb));
}
public AbstractCard makeCopy() {
return new WeatherTest();
}
public void upgrade() {
}
static {
cardStrings = CardCrawlGame.languagePack.getCardStrings("WeatherTest");
NAME = WeatherTest.cardStrings.NAME;
DESCRIPTION = WeatherTest.cardStrings.DESCRIPTION;
}
}
| true |
aaf32f93269469719ab71ad816992a05e9d9f88e | Java | aliyun/aliyun-openapi-java-sdk | /aliyun-java-sdk-sas/src/main/java/com/aliyuncs/sas/transform/v20181203/DescribeStrategyExecDetailResponseUnmarshaller.java | UTF-8 | 3,008 | 1.757813 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.sas.transform.v20181203;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.sas.model.v20181203.DescribeStrategyExecDetailResponse;
import com.aliyuncs.sas.model.v20181203.DescribeStrategyExecDetailResponse.FailedEcs;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeStrategyExecDetailResponseUnmarshaller {
public static DescribeStrategyExecDetailResponse unmarshall(DescribeStrategyExecDetailResponse describeStrategyExecDetailResponse, UnmarshallerContext _ctx) {
describeStrategyExecDetailResponse.setRequestId(_ctx.stringValue("DescribeStrategyExecDetailResponse.RequestId"));
describeStrategyExecDetailResponse.setInProcessCount(_ctx.integerValue("DescribeStrategyExecDetailResponse.InProcessCount"));
describeStrategyExecDetailResponse.setEndTime(_ctx.stringValue("DescribeStrategyExecDetailResponse.EndTime"));
describeStrategyExecDetailResponse.setStartTime(_ctx.stringValue("DescribeStrategyExecDetailResponse.StartTime"));
describeStrategyExecDetailResponse.setPercent(_ctx.stringValue("DescribeStrategyExecDetailResponse.Percent"));
describeStrategyExecDetailResponse.setFailCount(_ctx.integerValue("DescribeStrategyExecDetailResponse.FailCount"));
describeStrategyExecDetailResponse.setSource(_ctx.stringValue("DescribeStrategyExecDetailResponse.Source"));
describeStrategyExecDetailResponse.setSuccessCount(_ctx.integerValue("DescribeStrategyExecDetailResponse.SuccessCount"));
List<FailedEcs> failedEcsList = new ArrayList<FailedEcs>();
for (int i = 0; i < _ctx.lengthValue("DescribeStrategyExecDetailResponse.FailedEcsList.Length"); i++) {
FailedEcs failedEcs = new FailedEcs();
failedEcs.setIP(_ctx.stringValue("DescribeStrategyExecDetailResponse.FailedEcsList["+ i +"].IP"));
failedEcs.setInternetIp(_ctx.stringValue("DescribeStrategyExecDetailResponse.FailedEcsList["+ i +"].InternetIp"));
failedEcs.setIntranetIp(_ctx.stringValue("DescribeStrategyExecDetailResponse.FailedEcsList["+ i +"].IntranetIp"));
failedEcs.setReason(_ctx.stringValue("DescribeStrategyExecDetailResponse.FailedEcsList["+ i +"].Reason"));
failedEcs.setInstanceName(_ctx.stringValue("DescribeStrategyExecDetailResponse.FailedEcsList["+ i +"].InstanceName"));
failedEcsList.add(failedEcs);
}
describeStrategyExecDetailResponse.setFailedEcsList(failedEcsList);
return describeStrategyExecDetailResponse;
}
} | true |
c762398e8b9bf9b4d7250b01b7b5d17b33fc3a64 | Java | jxxchallenger/SpringMVCTutorial | /src/main/java/app02a/controller/SaveProductController.java | UTF-8 | 1,176 | 2.53125 | 3 | [] | no_license | package app02a.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import app02a.domain.Product;
import app02a.form.ProductForm;
import app02a.validator.ProductValidator;
public class SaveProductController implements Controller {
@Override
public String handleRequest(HttpServletRequest request, HttpServletResponse response) {
ProductForm form = new ProductForm();
form.setName(request.getParameter("name"));
form.setDescription(request.getParameter("description"));
form.setPrice(request.getParameter("price"));
ProductValidator validator = new ProductValidator();
List<String> errors = validator.validate(form);
if(errors.isEmpty()){
Product product = new Product();
product.setName(form.getName());
product.setDescription(form.getDescription());
product.setPrice(Float.parseFloat(form.getPrice()));
request.setAttribute("product", product);
return "/WEB-INF/jsp/ch02/ProductDetials.jsp";
}
else{
request.setAttribute("errors", errors);
request.setAttribute("form", form);
return "/WEB-INF/jsp/ch02/ProductForm.jsp";
}
}
}
| true |
f8335d4a31208516141003d6296859629a7ce0b8 | Java | Rey86/Proyecto_Bases_2 | /HouseOfTrade/src/front_end/ListGender.java | UTF-8 | 9,279 | 2.46875 | 2 | [] | no_license | package front_end;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class ListGender extends javax.swing.JDialog {
public ListGender(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setLocationRelativeTo(null);
try{
GenderList();
}
catch (SQLException e){
JOptionPane.showMessageDialog(this, e.toString(), "Watch out", JOptionPane.ERROR_MESSAGE);
}
}
public void GenderList() throws SQLException{
ResultSet r = logic_connection.DataBaseConnection.getGenders();
DefaultTableModel dtb = (DefaultTableModel) jTableGenders.getModel();
while(r.next()){
dtb.addRow(new Object[]{r.getInt("ID_GENDER"), r.getString("NAME")});
}
}
public void GenderCleanList(){
DefaultTableModel dtb = (DefaultTableModel) jTableGenders.getModel();
for (int i = dtb.getRowCount()-1;i>=0;i--) dtb.removeRow(i);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButtonClose = new javax.swing.JButton();
jButtonEdit = new javax.swing.JButton();
jButtonInsert = new javax.swing.JButton();
jButtonDelete = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTableGenders = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jButtonClose.setText("Exit");
jButtonClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCloseActionPerformed(evt);
}
});
jButtonEdit.setText("Update");
jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEditActionPerformed(evt);
}
});
jButtonInsert.setText("Insert");
jButtonInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonInsertActionPerformed(evt);
}
});
jButtonDelete.setText("Delete");
jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDeleteActionPerformed(evt);
}
});
jTableGenders.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Name"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jTableGenders.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane2.setViewportView(jTableGenders);
jLabel1.setText("Genders");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButtonEdit, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonInsert, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonClose, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jButtonClose, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonEdit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonInsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
dispose();
}//GEN-LAST:event_jButtonCloseActionPerformed
private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
Integer current_row = jTableGenders.getSelectedRow();
if(current_row != -1){
InsertGender dialog = new InsertGender(new javax.swing.JFrame(), true, (Integer) jTableGenders.getValueAt(current_row, 0));
dialog.setVisible(true);
try{
GenderCleanList();
GenderList();
}
catch (SQLException e){
JOptionPane.showMessageDialog(this, e.toString(), "Watch out", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this, "Select a row to edit", "Watch out", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_jButtonEditActionPerformed
private void jButtonInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInsertActionPerformed
InsertGender dialog = new InsertGender(new javax.swing.JFrame(), true, 0);
dialog.setVisible(true);
try{
GenderCleanList();
GenderList();
}
catch (SQLException e){
JOptionPane.showMessageDialog(this, e.toString(), "Watch out", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButtonInsertActionPerformed
private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
Integer current_row = jTableGenders.getSelectedRow();
if(current_row != -1){
try{
logic_connection.DataBaseConnection.deleteGender((Integer) jTableGenders.getValueAt(current_row, 0));
GenderCleanList();
GenderList();
}
catch (SQLException e){
JOptionPane.showMessageDialog(this, e.toString(), "Watch out", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(this, "Select a row to delete", "Watch out", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_jButtonDeleteActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonClose;
private javax.swing.JButton jButtonDelete;
private javax.swing.JButton jButtonEdit;
private javax.swing.JButton jButtonInsert;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTableGenders;
// End of variables declaration//GEN-END:variables
}
| true |
bf437f44b3274cfc55551146feb939f0d43a87a1 | Java | 40779948/Hackathon | /doc-samples/src/main/java/com/google/cloud/doc_samples/AsyncVoiceRecorder.java | UTF-8 | 4,206 | 2.15625 | 2 | [] | no_license | package com.google.cloud.doc_samples;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import com.google.api.gax.grpc.OperationFuture;
import com.google.cloud.speech.spi.v1.SpeechClient;
import com.google.cloud.speech.v1.LongRunningRecognizeResponse;
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
import com.google.protobuf.ByteString;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
class GoogleSpeech {
private SpeechClient speech;
private RecognitionConfig config;
private String fileURI;
GoogleSpeech(String fileURI) throws IOException {
// TODO Auto-generated constructor stub
this.fileURI = fileURI;
initSpeechConfig();
}
private void initSpeechConfig() throws IOException {
speech = SpeechClient.create();
config = RecognitionConfig.newBuilder().setEncoding(AudioEncoding.LINEAR16).setLanguageCode("en-US")
.setSampleRateHertz(16000).build();
}
public void processRequest() throws InterruptedException, ExecutionException, IOException {
Path path = Paths.get(fileURI);
byte[] data = Files.readAllBytes(path);
ByteString audioBytes = ByteString.copyFrom(data);
RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();
// Use non-blocking call for getting file transcription
OperationFuture<LongRunningRecognizeResponse> response = speech.longRunningRecognizeAsync(config, audio);
while (!response.isDone()) {
System.out.println("Waiting for response...");
Thread.sleep(10000);
}
List<SpeechRecognitionResult> results = response.get().getResultsList();
for (SpeechRecognitionResult result : results) {
List<SpeechRecognitionAlternative> alternatives = result.getAlternativesList();
for (SpeechRecognitionAlternative alternative : alternatives) {
System.out.printf("Transcription: %s%n", alternative.getTranscript());
}
}
try {
speech.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class AudioRecorder {
public void recordAudio() {
try {
AudioFormat format = new AudioFormat(16000.0f, 16, 1, true, true);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
System.out.println("'Line not supported");
System.exit(0);
}
final TargetDataLine targetLine = (TargetDataLine) AudioSystem.getLine(info);
targetLine.open();
System.out.println("Start Recording...");
targetLine.start();
Thread thread = new Thread() {
@Override
public void run() {
AudioInputStream audioStream = new AudioInputStream(targetLine);
File audioFile = new File("record.wav");
try {
AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, audioFile);
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
Thread.sleep(10000);
targetLine.stop();
targetLine.close();
} catch (LineUnavailableException lue) {
lue.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public class AsyncVoiceRecorder {
public static void main(String[] args) {
AudioRecorder audioRecorder = new AudioRecorder();
audioRecorder.recordAudio();
System.out.println("Stopped Recording...");
try {
GoogleSpeech googleSpeech = new GoogleSpeech("F:\\Tools\\workspace\\doc-samples\\record.wav");
googleSpeech.processRequest();
}catch(Exception e) {
e.printStackTrace();
}
}
} | true |
f1df10d3355ac2bf76cebef5692f983a6e629f59 | Java | OtabekRustamov/eWallet | /app/src/main/java/com/example/root/ewallet/app/paynow/presenter/PayNowPresenterIml.java | UTF-8 | 3,543 | 1.914063 | 2 | [] | no_license | package com.example.root.ewallet.app.paynow.presenter;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.example.root.ewallet.app.paynow.PayNowFragment;
import com.example.root.ewallet.app.paynow.model.CreatePay_Respose;
import com.example.root.ewallet.app.paynow.model.ModelGet;
import com.example.root.ewallet.app.paynow.model.ModelPost;
import com.example.root.ewallet.common.WalletResponse;
import com.example.root.ewallet.util.ApiManager;
import javax.inject.Inject;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
/**
* Created by root on 10/30/17.
*/
public class PayNowPresenterIml implements PayNowPresenter {
private PayNowFragment payNowFragment;
private ApiManager apiManager;
private Context context;
@Inject
public PayNowPresenterIml(PayNowFragment payNowFragment, ApiManager apiManager, Context context) {
this.payNowFragment = payNowFragment;
this.apiManager = apiManager;
this.context = context;
}
@Override
public void fillCreate(ModelPost post) {
apiManager.createPay(post)
.subscribe(new Observer<CreatePay_Respose>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(CreatePay_Respose respose) {
if (respose.getError().getCode() == 200) {
Toast.makeText(context, respose.getError().getUserMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, respose.getError().getUserMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Throwable e) {
Log.d("ooo", e.getMessage().toString());
}
@Override
public void onComplete() {
}
});
}
@Override
public void fillPaynow() {
payNowFragment.show();
apiManager.payNowModel()
.subscribe(new Observer<WalletResponse<ModelGet>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(WalletResponse<ModelGet> response) {
payNowFragment.dismiss();
if (response.isSuccess()) {
// Toast.makeText(context, response.getError().getUserMessage().toString(), Toast.LENGTH_SHORT).show();
payNowFragment.setSpFrom(response.getData().getFromAlias());
payNowFragment.setEtTo(response.getData().getToAlias());
payNowFragment.setEtCurrency(response.getData().getCurList());
} else {
Toast.makeText(context, response.getError().getUserMessage().toString(), Toast.LENGTH_SHORT).show();
payNowFragment.dismiss();
}
}
@Override
public void onError(Throwable e) {
payNowFragment.dismiss();
}
@Override
public void onComplete() {
}
});
}
}
| true |
345d039c7f83ee9c3607a1afc47ead1fbfdb824b | Java | heqiyoujing/vertxExample | /src/main/java/io/example/mainVerticle/FirstMain.java | UTF-8 | 2,977 | 2.578125 | 3 | [] | no_license | package io.example.mainVerticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
/**
* @author: yiqq
* @date: 2018/10/8
* @description: **********重点是这个类**********
*/
public class FirstMain extends AbstractVerticle {
private static Logger logger = LoggerFactory.getLogger(FirstMain.class);
public void start() {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.get("/hang/some").handler(routingContext -> { //指定get方法
// 所有的请求都会调用这个处理器处理
HttpServerResponse response = routingContext.response();
response.putHeader("content-type", "text/plain");
// 写入响应并结束处理
response.end("Hello World from Vert.x-Web!");
});
router.route("/hang/all").handler(routingContext -> {
// 所有的请求都会调用这个处理器处理
HttpServerResponse response = routingContext.response();
response.putHeader("content-type", "text/plain");
// 写入响应并结束处理
response.end("Hello World !");
});
router.route("/hang/put").handler(BodyHandler::getStr);
// router.route("/static/*").handler(StaticHandler.create());
//处理请求并调用下一个处理器
router.route(HttpMethod.POST,"/hang/add").handler(BodyHandler::getStr_1);//OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, PATCH, OTHER
router.route("/hang/add").handler(BodyHandler::getStr_2);
router.route("/hang/add").handler(BodyHandler::getStr_3);
router.route("/hello").blockingHandler(BodyHandler.bodyHandler()::getStr_4, false);
router.route("/hello_4s").blockingHandler(BodyHandler.bodyHandler()::getStr_4s, false);
router.route("/helloWorld").blockingHandler(BodyHandler.bodyHandler()::getStr_5, false);
server.requestHandler(router::accept).listen(8088);
}
public static void main(String[] args) {
// Vertx vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(40));
// vertx.deployVerticle(FirstMain.class.getName());
// System.out.println("vertx......启动");
Vertx.clusteredVertx(new VertxOptions(), res->{
if (res.succeeded()) {
res.result().deployVerticle(FirstMain.class.getName());
logger.info("success start!" );
System.out.println("success start!" );
} else {
logger.info("Failed: " + res.cause());
}
});
}
}
| true |
287d4c6af1ee842c95e3f81525f60791637220d5 | Java | vilinian/gamedemo | /src/test/java/com/example/gamedemo/npc/NpcTest.java | UTF-8 | 671 | 1.804688 | 2 | [] | no_license | package com.example.gamedemo.npc;
import com.example.gamedemo.common.resource.ResourceManager;
import com.example.gamedemo.server.game.npc.resource.NpcResource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
/**
* @author wengj
* @description
* @date 2019/6/19
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class NpcTest {
@Test
public void testNpcResource() {
Map<Object, NpcResource> resourceMap = ResourceManager.getResourceMap(NpcResource.class);
System.out.println(resourceMap);
}
}
| true |
c6c34fb45ee84af61d8def55dc7ebe4fb1916fb6 | Java | Ivanov911/academy | /academy/src/Classwork16/NewThread.java | UTF-8 | 296 | 2.828125 | 3 | [] | no_license | package Classwork16;
public class NewThread extends Thread {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int x = 1; x <= 100; x++) {
System.out.println(x);
}
}
}
| true |
723b3a465f78a5177d21f9eaf7378e7c540cbe35 | Java | anellocorp/Zolkin-Android-Google-Places | /zolkin/src/main/java/com/imd/zolkin/activity/FilterActivity.java | UTF-8 | 3,806 | 2.234375 | 2 | [] | no_license | package com.imd.zolkin.activity;
//Tela de filtro de subcategorias
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.imd.zolkin.adapter.FilterAdapter;
import com.imd.zolkin.model.ZLSubCategory;
import com.imd.zolkin.util.Constants;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import br.com.zolkin.R;
public class FilterActivity extends BaseZolkinActivity
{
ImageView btVoltar = null;
ImageView btLocation = null;
ListView lvSubCategories = null;
TextView tvBtLimpar = null;
TextView tvBtFiltrar = null;
//recebe Activity chamante um mapa de subcategorias, onde a chave é o ID da subCategoria
public static HashMap<Integer, ZLSubCategory> dSubCategories;
List<ZLSubCategory> subCategories;
FilterAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter);
btVoltar = (ImageView) findViewById(R.id.btVoltar);
btLocation = (ImageView) findViewById(R.id.btLocation);
lvSubCategories = (ListView) findViewById(R.id.lvSubCategories);
tvBtLimpar = (TextView) findViewById(R.id.tvBtLimpar);
tvBtFiltrar = (TextView) findViewById(R.id.tvBtFiltrar);
//pega as subCategorias do Map e adiciona em uma lista
subCategories = new ArrayList<ZLSubCategory>();
for (Integer intg : dSubCategories.keySet())
{
ZLSubCategory sc = dSubCategories.get(intg);
subCategories.add(sc);
}
//cria o adapter e mostra no listview
adapter = new FilterAdapter(this, subCategories);
lvSubCategories.setAdapter(adapter);
btVoltar.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
boolean atLeastOneSelected = false;
for (ZLSubCategory sc : subCategories)
{
if (sc.selected)
{
atLeastOneSelected = true;
}
}
if (!atLeastOneSelected)
{
for (ZLSubCategory sc : subCategories)
{
sc.selected = true;
}
dSubCategories = null;
ListaActivity.subCatsFilter = null;
finish();
}
finish();
}
});
//ao clicar em limpar, seleciona todas as categorias, remove o filtro, e volta para a tela de lista
tvBtLimpar.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
for (ZLSubCategory sc : subCategories)
{
sc.selected = true;
}
dSubCategories = null;
ListaActivity.subCatsFilter = null;
finish();
}
});
//ao clicar em filtrar
tvBtFiltrar.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
//loga no mixpanel as categorias que foram selecionadas e deselecionadas
MixpanelAPI mixPanel = MixpanelAPI.getInstance(FilterActivity.this, Constants.MIXPANEL_TOKEN);
boolean atLeastOneSelected = false;
for (int i = 0; i < adapter.getCount(); i++)
{
ZLSubCategory sc = (ZLSubCategory) adapter.getItem(i);
JSONObject props2 = new JSONObject();
props2.put("Nome", sc.name);
props2.put("ID", sc.subCatId);
if (sc.selected)
{
mixPanel.track("FiltroSubcategoriaIncluida", props2);
atLeastOneSelected = true;
}
else
mixPanel.track("FiltroSubcategoriaExcluida", props2);
}
//se todas estamas deselecionadas, remove o filtro
if (!atLeastOneSelected)
{
dSubCategories = null;
ListaActivity.subCatsFilter = null;
}
}
catch (Exception e)
{
}
//volta para a Lista
finish();
}
});
}
}
| true |
b5d526480e58a4e9daf1ba97500b9b78de231296 | Java | kpoorvibhat/PracticeExercise5_Java | /src/test/java/com/stackroute/MainTest.java | UTF-8 | 1,767 | 2.859375 | 3 | [] | no_license | package com.stackroute;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class MainTest {
private static Student student;
@BeforeClass
public static void setup(){
student = new Student();
}
@AfterClass
public static void teardown(){
student=null;
}
@Test
public void testStudentSorter_GivenStudentObjects_ShouldReturnSortedList() {
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
student1.setId(1); student1.setName("Poorvi"); student1.setAge(22);
student2.setId(2); student2.setName("Vinod"); student2.setAge(22);
student3.setId(3); student3.setName("Poorvi"); student3.setAge(22);
student4.setId(4); student4.setName("Nishchith"); student4.setAge(25);
student5.setId(5); student5.setName("Vaishnavi"); student5.setAge(18);
List<Student> studentList = new ArrayList<Student>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
studentList.add(student5);
List<Student> sortedList = new ArrayList<>();
sortedList.add(student4);
sortedList.add(student1);
sortedList.add(student3);
sortedList.add(student2);
sortedList.add(student5);
assertThat(sortedList, is(student.sortStudents(studentList)));
}
} | true |
0289d40c03b9fc3b249f35f9e894902b6f0922e7 | Java | RendhikaAditya/sayur | /app/src/main/java/com/example/sayur/activity/AlamatAdd.java | UTF-8 | 8,130 | 1.945313 | 2 | [] | no_license | package com.example.sayur.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.example.sayur.MainActivity;
import com.example.sayur.PrefManager;
import com.example.sayur.R;
import com.example.sayur.ServerApi;
import com.example.sayur.fragment.Profil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class AlamatAdd extends AppCompatActivity {
EditText nama, pos, alamat;
Button btnSimpanAlamat;
String edNama, edPos, edAlamat;
ImageView back;
private PrefManager prefManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alamat_add);
AndroidNetworking.initialize(this);
prefManager = new PrefManager(this);
back = findViewById(R.id.backAlamat);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
nama = findViewById(R.id.namaPenerima);
pos = findViewById(R.id.kodePos);
alamat = findViewById(R.id.alamatEdit);
getData();
// nama.setText(prefManager.getIdUser());
btnSimpanAlamat = findViewById(R.id.btnSimpanAlamat);
btnSimpanAlamat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setData();
}
});
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Perhatian")
.setMessage("Apakah anda yakin meningkalkan halaman ini?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(AlamatAdd.this, Keranjang.class);
startActivity(i);
}
})
.setNegativeButton("Tidak", null)
.show();
}
private void getData() {
int cod = 2;
AndroidNetworking.post(ServerApi.site_url+"get_alamat.php")
.addBodyParameter("id", prefManager.getIdUser())
.addBodyParameter("cod", String.valueOf(cod))
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
@Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
try {
Log.d("Sukses alamat","sukses : "+response);
JSONObject object = response.getJSONObject(i);
edNama = object.getString("nama");
edPos = object.getString("pos");
edAlamat = object.getString("alamat");
nama.setText(edNama);
pos.setText(edPos);
alamat.setText(edAlamat);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onError(ANError anError) {
Log.d("Error alamat", "eror : "+anError);
}
});
}
private void setData() {
final String H;
prefManager = new PrefManager(this);
final Intent intent = getIntent();
H = intent.getStringExtra("B");
String ICUS = null;
ICUS = intent.getStringExtra("IDCUS");
if(ICUS==null) {
AndroidNetworking.post(ServerApi.site_url + "set_alamat.php")
.addBodyParameter("id", prefManager.getIdUser())
.addBodyParameter("nama", nama.getText().toString())
.addBodyParameter("pos", pos.getText().toString())
.addBodyParameter("alamat", alamat.getText().toString())
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
String code = null;
try {
code = response.getString("cod");
if (code.equals(1)) {
Toast.makeText(getApplicationContext(), response.getString("response"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), response.getString("response"), Toast.LENGTH_SHORT).show();
if (H.isEmpty()) {
Intent intent = new Intent(AlamatAdd.this, MainActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(AlamatAdd.this, Checkout.class);
startActivity(intent);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(ANError anError) {
Log.d("error add", "error :"+anError);
}
});
}else {
AndroidNetworking.post(ServerApi.site_url + "set_alamat.php")
.addBodyParameter("id", ICUS)
.addBodyParameter("nama", nama.getText().toString())
.addBodyParameter("pos", pos.getText().toString())
.addBodyParameter("alamat", alamat.getText().toString())
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
String code = null;
try {
code = response.getString("cod");
if (code.equalsIgnoreCase("1")) {
// Toast.makeText(getApplicationContext(), "REgister Sukses", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Register gagal", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(ANError anError) {
Log.d("Error ini", "error :"+anError);
}
});
}
}
}
| true |
53475bee5a8579d1f1ec497de4bd6b6e3970b055 | Java | AkankGit123/basic | /ConcatenateStr.java | UTF-8 | 296 | 2.9375 | 3 | [] | no_license | package com.rays.basic;
public class ConcatenateStr {
public static void main(String[] args) {
String fname = "Vijay";
String lname = "Chohan";
System.out.println(fname + " " + lname);
// String concatedName =fname.concat(" "+ lname);
//System.out.println(concatedName);
}
}
| true |